Defragmenter.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_DEFRAGMENTER_HPP
  14. #define ZT_DEFRAGMENTER_HPP
  15. #include "Constants.hpp"
  16. #include "Buf.hpp"
  17. #include "SharedPtr.hpp"
  18. #include "Mutex.hpp"
  19. #include "Path.hpp"
  20. #include "FCV.hpp"
  21. #include "Map.hpp"
  22. #include <cstring>
  23. #include <cstdlib>
  24. #include <vector>
  25. namespace ZeroTier {
  26. /**
  27. * Generalized putter back together-er for fragmented messages
  28. *
  29. * This is used both for packet fragment assembly and multi-chunk network config
  30. * assembly. This is abstracted out of the code that uses it because it's a bit of
  31. * a hairy and difficult thing to get both correct and fast, and because its
  32. * hairiness makes it very desirable to be able to test and fuzz this code
  33. * independently.
  34. *
  35. * This class is thread-safe and handles locking internally.
  36. *
  37. * @tparam MF Maximum number of fragments that each message can possess
  38. * @tparam GCS Garbage collection target size for the incoming message queue
  39. * @tparam GCT Garbage collection trigger threshold, usually 2X GCS
  40. */
  41. template<unsigned int MF = 16,unsigned int GCS = 32,unsigned int GCT = 64>
  42. class Defragmenter
  43. {
  44. public:
  45. /**
  46. * Return values from assemble()
  47. */
  48. enum ResultCode
  49. {
  50. /**
  51. * No error occurred, fragment accepted
  52. */
  53. OK,
  54. /**
  55. * Message fully assembled and placed in message vector
  56. */
  57. COMPLETE,
  58. /**
  59. * We already have this fragment number or the message is complete
  60. */
  61. ERR_DUPLICATE_FRAGMENT,
  62. /**
  63. * The fragment is invalid, such as e.g. having a fragment number beyond the expected count.
  64. */
  65. ERR_INVALID_FRAGMENT,
  66. /**
  67. * Too many fragments are in flight for this path
  68. *
  69. * The message will be marked as if it's done (all fragments received) but will
  70. * be abandoned. Subsequent fragments will generate a DUPLICATE_FRAGMENT error.
  71. *
  72. * This is an anti-denial-of-service feature to limit the number of inbound
  73. * fragments that can be in flight over a given physical network path.
  74. */
  75. ERR_TOO_MANY_FRAGMENTS_FOR_PATH,
  76. /**
  77. * Memory (or some other limit) exhausted
  78. */
  79. ERR_OUT_OF_MEMORY
  80. };
  81. ZT_INLINE Defragmenter() {}
  82. /**
  83. * Process a fragment of a multi-part message
  84. *
  85. * The message ID is arbitrary but must be something that can uniquely
  86. * group fragments for a given final message. The total fragments expected
  87. * value is expectded to be the same for all fragments in a message. Results
  88. * are undefined and probably wrong if this value changes across a message.
  89. * Fragment numbers must be sequential starting with 0 and going up to
  90. * one minus total fragments expected (non-inclusive range).
  91. *
  92. * Fragments can arrive in any order. Duplicates are dropped and ignored.
  93. *
  94. * It's the responsibility of the caller to do whatever validation needs to
  95. * be done before considering a fragment valid and to make sure the fragment
  96. * data index and size parameters are valid.
  97. *
  98. * The fragment supplied to this function is kept and held under the supplied
  99. * message ID until or unless (1) the message is fully assembled, (2) the
  100. * message is orphaned and its entry is taken by a new message, or (3) the
  101. * clear() function is called to forget all incoming messages. The pointer
  102. * at the 'fragment' reference will be zeroed since this pointer is handed
  103. * off, so the SharedPtr<> passed in as 'fragment' will be NULL after this
  104. * function is called.
  105. *
  106. * The 'via' parameter causes this fragment to be registered with a path and
  107. * unregistered when done or abandoned. It's only used the first time it's
  108. * supplied (the first non-NULL) for a given message ID. This is a mitigation
  109. * against memory exhausting DOS attacks.
  110. *
  111. * @tparam X Template parameter type for Buf<> containing fragment (inferred)
  112. * @param messageId Message ID (a unique ID identifying this message)
  113. * @param message Fixed capacity vector that will be filled with the result if result code is DONE
  114. * @param fragment Buffer containing fragment that will be filed under this message's ID
  115. * @param fragmentDataIndex Index of data in fragment's data.bytes (fragment's data.fields type is ignored)
  116. * @param fragmentDataSize Length of data in fragment's data.bytes (fragment's data.fields type is ignored)
  117. * @param fragmentNo Number of fragment (0..totalFragmentsExpected, non-inclusive)
  118. * @param totalFragmentsExpected Total number of expected fragments in this message or 0 to use cached value
  119. * @param now Current time
  120. * @param via If non-NULL this is the path on which this message fragment was received
  121. * @param maxIncomingFragmentsPerPath If via is non-NULL this is a cutoff for maximum fragments in flight via this path
  122. * @return Result code
  123. */
  124. ZT_INLINE ResultCode assemble(
  125. const uint64_t messageId,
  126. FCV< Buf::Slice,MF > &message,
  127. SharedPtr<Buf> &fragment,
  128. const unsigned int fragmentDataIndex,
  129. const unsigned int fragmentDataSize,
  130. const unsigned int fragmentNo,
  131. const unsigned int totalFragmentsExpected,
  132. const int64_t now,
  133. const SharedPtr<Path> &via,
  134. const unsigned int maxIncomingFragmentsPerPath)
  135. {
  136. // Sanity checks for malformed fragments or invalid input parameters.
  137. if ((fragmentNo >= totalFragmentsExpected)||(totalFragmentsExpected > MF)||(totalFragmentsExpected == 0))
  138. return ERR_INVALID_FRAGMENT;
  139. // We hold the read lock on _messages unless we need to add a new entry or do GC.
  140. RWMutex::RMaybeWLock ml(_messages_l);
  141. // Check message hash table size and perform GC if necessary.
  142. if (_messages.size() >= GCT) {
  143. try {
  144. // Scan messages with read lock still locked first and make a sorted list of
  145. // message entries by last modified time. Then lock for writing and delete
  146. // the oldest entries to bring the size of the messages hash table down to
  147. // under the target size. This tries to minimize the amount of time the write
  148. // lock is held since many threads can hold the read lock but all threads must
  149. // wait if someone holds the write lock.
  150. std::vector<std::pair<int64_t,uint64_t> > messagesByLastUsedTime;
  151. messagesByLastUsedTime.reserve(_messages.size());
  152. for(typename Map< uint64_t,_E >::const_iterator i(_messages.begin());i!=_messages.end();++i)
  153. messagesByLastUsedTime.push_back(std::pair<int64_t,uint64_t>(i->second.lastUsed,i->first));
  154. std::sort(messagesByLastUsedTime.begin(),messagesByLastUsedTime.end());
  155. ml.writing(); // acquire write lock on _messages
  156. for (unsigned long x = 0,y = (messagesByLastUsedTime.size() - GCS); x <= y; ++x)
  157. _messages.erase(messagesByLastUsedTime[x].second);
  158. } catch (...) {
  159. return ERR_OUT_OF_MEMORY;
  160. }
  161. }
  162. // Get or create message fragment.
  163. _E *e = _messages.get(messageId);
  164. if (!e) {
  165. ml.writing(); // acquire write lock on _messages if not already
  166. try {
  167. e = &(_messages[messageId]);
  168. } catch (...) {
  169. return ERR_OUT_OF_MEMORY;
  170. }
  171. e->id = messageId;
  172. }
  173. // Switch back to holding only the read lock on _messages if we have locked for write
  174. ml.reading();
  175. // Acquire lock on entry itself
  176. Mutex::Lock el(e->lock);
  177. // This magic value means this message has already been assembled and is done.
  178. if (e->lastUsed < 0)
  179. return ERR_DUPLICATE_FRAGMENT;
  180. // Update last-activity timestamp for this entry, delaying GC.
  181. e->lastUsed = now;
  182. // Learn total fragments expected if a value is given. Otherwise the cached
  183. // value gets used. This is to support the implementation of fragmentation
  184. // in the ZT protocol where only fragments carry the total.
  185. if (totalFragmentsExpected > 0)
  186. e->totalFragmentsExpected = totalFragmentsExpected;
  187. // If there is a path associated with this fragment make sure we've registered
  188. // ourselves as in flight, check the limit, and abort if exceeded.
  189. if ((via)&&(!e->via)) {
  190. e->via = via;
  191. bool tooManyPerPath = false;
  192. via->_inboundFragmentedMessages_l.lock();
  193. try {
  194. if (via->_inboundFragmentedMessages.size() < maxIncomingFragmentsPerPath) {
  195. via->_inboundFragmentedMessages.insert(messageId);
  196. } else {
  197. tooManyPerPath = true;
  198. }
  199. } catch ( ... ) {
  200. // This would indicate something like bad_alloc thrown by the set. Treat
  201. // it as limit exceeded.
  202. tooManyPerPath = true;
  203. }
  204. via->_inboundFragmentedMessages_l.unlock();
  205. if (tooManyPerPath)
  206. return ERR_TOO_MANY_FRAGMENTS_FOR_PATH;
  207. }
  208. // If we already have fragment number X, abort. Note that we do not
  209. // actually compare data here. Two same-numbered fragments with different
  210. // data would just mean the transfer is corrupt and would be detected
  211. // later e.g. by packet MAC check. Other use cases of this code like
  212. // network configs check each fragment so this basically can't happen.
  213. Buf::Slice &s = e->message.at(fragmentNo);
  214. if (s.b)
  215. return ERR_DUPLICATE_FRAGMENT;
  216. // Take ownership of fragment, setting 'fragment' pointer to NULL. The simple
  217. // transfer of the pointer avoids a synchronized increment/decrement of the object's
  218. // reference count.
  219. s.b.move(fragment);
  220. s.s = fragmentDataIndex;
  221. s.e = fragmentDataIndex + fragmentDataSize;
  222. ++e->fragmentsReceived;
  223. // If we now have all fragments then assemble them.
  224. if ((e->fragmentsReceived >= e->totalFragmentsExpected)&&(e->totalFragmentsExpected > 0)) {
  225. // This message is done so de-register it with its path if one is associated.
  226. if (e->via) {
  227. e->via->_inboundFragmentedMessages_l.lock();
  228. e->via->_inboundFragmentedMessages.erase(messageId);
  229. e->via->_inboundFragmentedMessages_l.unlock();
  230. e->via.zero();
  231. }
  232. // Slices are TriviallyCopyable and so may be raw copied from e->message to
  233. // the result parameter. This is fast.
  234. e->message.unsafeMoveTo(message);
  235. e->lastUsed = -1; // mark as "done" and force GC to collect
  236. return COMPLETE;
  237. }
  238. return OK;
  239. }
  240. /**
  241. * Erase all message entries in the internal queue
  242. */
  243. ZT_INLINE void clear()
  244. {
  245. RWMutex::Lock ml(_messages_l);
  246. _messages.clear();
  247. }
  248. /**
  249. * @return Number of entries currently in message defragmentation cache
  250. */
  251. ZT_INLINE unsigned int cacheSize() noexcept
  252. {
  253. RWMutex::RLock ml(_messages_l);
  254. return _messages.size();
  255. }
  256. private:
  257. // _E is an entry in the message queue.
  258. struct _E
  259. {
  260. ZT_INLINE _E() noexcept :
  261. id(0),
  262. lastUsed(0),
  263. totalFragmentsExpected(0),
  264. fragmentsReceived(0) {}
  265. ZT_INLINE _E(const _E &e) noexcept :
  266. id(e.id),
  267. lastUsed(e.lastUsed),
  268. totalFragmentsExpected(e.totalFragmentsExpected),
  269. fragmentsReceived(e.fragmentsReceived),
  270. via(e.via),
  271. message(e.message),
  272. lock() {}
  273. ZT_INLINE ~_E()
  274. {
  275. if (via) {
  276. via->_inboundFragmentedMessages_l.lock();
  277. via->_inboundFragmentedMessages.erase(id);
  278. via->_inboundFragmentedMessages_l.unlock();
  279. }
  280. }
  281. ZT_INLINE _E &operator=(const _E &e)
  282. {
  283. if (this != &e) {
  284. id = e.id;
  285. lastUsed = e.lastUsed;
  286. totalFragmentsExpected = e.totalFragmentsExpected;
  287. fragmentsReceived = e.fragmentsReceived;
  288. via = e.via;
  289. message = e.message;
  290. }
  291. return *this;
  292. }
  293. uint64_t id;
  294. volatile int64_t lastUsed;
  295. unsigned int totalFragmentsExpected;
  296. unsigned int fragmentsReceived;
  297. SharedPtr<Path> via;
  298. FCV< Buf::Slice,MF > message;
  299. Mutex lock;
  300. };
  301. Map< uint64_t,_E > _messages;
  302. RWMutex _messages_l;
  303. };
  304. } // namespace ZeroTier
  305. #endif