DeferredPackets.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "Constants.hpp"
  19. #include "DeferredPackets.hpp"
  20. #include "IncomingPacket.hpp"
  21. #include "RuntimeEnvironment.hpp"
  22. #include "Node.hpp"
  23. namespace ZeroTier {
  24. DeferredPackets::DeferredPackets(const RuntimeEnvironment *renv) :
  25. RR(renv),
  26. _readPtr(0),
  27. _writePtr(0),
  28. _waiting(0),
  29. _die(false)
  30. {
  31. }
  32. DeferredPackets::~DeferredPackets()
  33. {
  34. _q_m.lock();
  35. _die = true;
  36. while (_waiting > 0) {
  37. _q_m.unlock();
  38. _q_s.post();
  39. _q_m.lock();
  40. }
  41. }
  42. bool DeferredPackets::enqueue(IncomingPacket *pkt)
  43. {
  44. _q_m.lock();
  45. const unsigned long p = _writePtr % ZT_DEFFEREDPACKETS_MAX;
  46. if (_q[p]) {
  47. _q_m.unlock();
  48. return false;
  49. } else {
  50. _q[p].setToUnsafe(pkt);
  51. ++_writePtr;
  52. _q_m.unlock();
  53. _q_s.post();
  54. return true;
  55. }
  56. }
  57. int DeferredPackets::process()
  58. {
  59. SharedPtr<IncomingPacket> pkt;
  60. _q_m.lock();
  61. if (_die) {
  62. _q_m.unlock();
  63. return -1;
  64. }
  65. while (_readPtr == _writePtr) {
  66. ++_waiting;
  67. _q_m.unlock();
  68. _q_s.wait();
  69. _q_m.lock();
  70. --_waiting;
  71. if (_die) {
  72. _q_m.unlock();
  73. return -1;
  74. }
  75. }
  76. pkt.swap(_q[_readPtr++ % ZT_DEFFEREDPACKETS_MAX]);
  77. _q_m.unlock();
  78. pkt->tryDecode(RR,true);
  79. return 1;
  80. }
  81. } // namespace ZeroTier