2
0

Defragmenter.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 "Hashtable.hpp"
  19. #include "Mutex.hpp"
  20. #include "Path.hpp"
  21. #include "FCV.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,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. /**
  82. * Process a fragment of a multi-part message
  83. *
  84. * The message ID is arbitrary but must be something that can uniquely
  85. * group fragments for a given final message. The total fragments expected
  86. * value is expectded to be the same for all fragments in a message. Results
  87. * are undefined and probably wrong if this value changes across a message.
  88. * Fragment numbers must be sequential starting with 0 and going up to
  89. * one minus total fragments expected (non-inclusive range).
  90. *
  91. * Fragments can arrive in any order. Duplicates are dropped and ignored.
  92. *
  93. * It's the responsibility of the caller to do whatever validation needs to
  94. * be done before considering a fragment valid and to make sure the fragment
  95. * data index and size parameters are valid.
  96. *
  97. * The fragment supplied to this function is kept and held under the supplied
  98. * message ID until or unless (1) the message is fully assembled, (2) the
  99. * message is orphaned and its entry is taken by a new message, or (3) the
  100. * clear() function is called to forget all incoming messages. The pointer
  101. * at the 'fragment' reference will be zeroed since this pointer is handed
  102. * off, so the SharedPtr<> passed in as 'fragment' will be NULL after this
  103. * function is called.
  104. *
  105. * The 'via' parameter causes this fragment to be registered with a path and
  106. * unregistered when done or abandoned. It's only used the first time it's
  107. * supplied (the first non-NULL) for a given message ID. This is a mitigation
  108. * against memory exhausting DOS attacks.
  109. *
  110. * @tparam X Template parameter type for Buf<> containing fragment (inferred)
  111. * @param messageId Message ID (a unique ID identifying this message)
  112. * @param message Fixed capacity vector that will be filled with the result if result code is DONE
  113. * @param fragment Buffer containing fragment that will be filed under this message's ID
  114. * @param fragmentDataIndex Index of data in fragment's data.bytes (fragment's data.fields type is ignored)
  115. * @param fragmentDataSize Length of data in fragment's data.bytes (fragment's data.fields type is ignored)
  116. * @param fragmentNo Number of fragment (0..totalFragmentsExpected, non-inclusive)
  117. * @param totalFragmentsExpected Total number of expected fragments in this message or 0 to use cached value
  118. * @param now Current time
  119. * @param via If non-NULL this is the path on which this message fragment was received
  120. * @param maxIncomingFragmentsPerPath If via is non-NULL this is a cutoff for maximum fragments in flight via this path
  121. * @return Result code
  122. */
  123. ZT_ALWAYS_INLINE ResultCode assemble(
  124. const uint64_t messageId,
  125. FCV< Buf::Slice,MF > &message,
  126. SharedPtr<Buf> &fragment,
  127. const unsigned int fragmentDataIndex,
  128. const unsigned int fragmentDataSize,
  129. const unsigned int fragmentNo,
  130. const unsigned int totalFragmentsExpected,
  131. const int64_t now,
  132. const SharedPtr< Path > &via,
  133. const unsigned int maxIncomingFragmentsPerPath)
  134. {
  135. // Sanity checks for malformed fragments or invalid input parameters.
  136. if ((fragmentNo >= totalFragmentsExpected)||(totalFragmentsExpected > MF)||(totalFragmentsExpected == 0))
  137. return ERR_INVALID_FRAGMENT;
  138. // We hold the read lock on _messages unless we need to add a new entry or do GC.
  139. RWMutex::RMaybeWLock ml(_messages_l);
  140. // Check message hash table size and perform GC if necessary.
  141. if (_messages.size() >= GCT) {
  142. try {
  143. // Scan messages with read lock still locked first and make a sorted list of
  144. // message entries by last modified time. Then lock for writing and delete
  145. // the oldest entries to bring the size of the messages hash table down to
  146. // under the target size. This tries to minimize the amount of time the write
  147. // lock is held since many threads can hold the read lock but all threads must
  148. // wait if someone holds the write lock.
  149. std::vector<std::pair<int64_t,uint64_t> > messagesByLastUsedTime;
  150. messagesByLastUsedTime.reserve(_messages.size());
  151. typename Hashtable<uint64_t,_E>::Iterator i(_messages);
  152. uint64_t *mk = nullptr;
  153. _E *mv = nullptr;
  154. while (i.next(mk,mv))
  155. messagesByLastUsedTime.push_back(std::pair<int64_t,uint64_t>(mv->lastUsed,*mk));
  156. std::sort(messagesByLastUsedTime.begin(),messagesByLastUsedTime.end());
  157. ml.writing(); // acquire write lock on _messages
  158. for (unsigned long x = 0,y = (messagesByLastUsedTime.size() - GCS); x <= y; ++x)
  159. _messages.erase(messagesByLastUsedTime[x].second);
  160. } catch (...) {
  161. return ERR_OUT_OF_MEMORY;
  162. }
  163. }
  164. // Get or create message fragment.
  165. _E *e = _messages.get(messageId);
  166. if (!e) {
  167. ml.writing(); // acquire write lock on _messages if not already
  168. try {
  169. e = &(_messages[messageId]);
  170. } catch (...) {
  171. return ERR_OUT_OF_MEMORY;
  172. }
  173. e->id = messageId;
  174. }
  175. // Switch back to holding only the read lock on _messages if we have locked for write
  176. ml.reading();
  177. // Acquire lock on entry itself
  178. Mutex::Lock el(e->lock);
  179. // This magic value means this message has already been assembled and is done.
  180. if (e->lastUsed < 0)
  181. return ERR_DUPLICATE_FRAGMENT;
  182. // Update last-activity timestamp for this entry, delaying GC.
  183. e->lastUsed = now;
  184. // Learn total fragments expected if a value is given. Otherwise the cached
  185. // value gets used. This is to support the implementation of fragmentation
  186. // in the ZT protocol where only fragments carry the total.
  187. if (totalFragmentsExpected > 0)
  188. e->totalFragmentsExpected = totalFragmentsExpected;
  189. // If there is a path associated with this fragment make sure we've registered
  190. // ourselves as in flight, check the limit, and abort if exceeded.
  191. if ((via)&&(!e->via)) {
  192. e->via = via;
  193. bool tooManyPerPath = false;
  194. via->_inboundFragmentedMessages_l.lock();
  195. try {
  196. if (via->_inboundFragmentedMessages.size() < maxIncomingFragmentsPerPath) {
  197. via->_inboundFragmentedMessages.insert(messageId);
  198. } else {
  199. tooManyPerPath = true;
  200. }
  201. } catch ( ... ) {
  202. // This would indicate something like bad_alloc thrown by the set. Treat
  203. // it as limit exceeded.
  204. tooManyPerPath = true;
  205. }
  206. via->_inboundFragmentedMessages_l.unlock();
  207. if (tooManyPerPath)
  208. return ERR_TOO_MANY_FRAGMENTS_FOR_PATH;
  209. }
  210. // If we already have fragment number X, abort. Note that we do not
  211. // actually compare data here. Two same-numbered fragments with different
  212. // data would just mean the transfer is corrupt and would be detected
  213. // later e.g. by packet MAC check. Other use cases of this code like
  214. // network configs check each fragment so this basically can't happen.
  215. Buf::Slice &s = e->message.at(fragmentNo);
  216. if (s.b)
  217. return ERR_DUPLICATE_FRAGMENT;
  218. // Take ownership of fragment, setting 'fragment' pointer to NULL. The simple
  219. // transfer of the pointer avoids a synchronized increment/decrement of the object's
  220. // reference count.
  221. s.b.move(fragment);
  222. s.s = fragmentDataIndex;
  223. s.e = fragmentDataIndex + fragmentDataSize;
  224. // If we now have all fragments then assemble them.
  225. if ((e->message.size() >= e->totalFragmentsExpected)&&(e->totalFragmentsExpected > 0)) {
  226. // This message is done so de-register it with its path if one is associated.
  227. if (e->via) {
  228. e->via->_inboundFragmentedMessages_l.lock();
  229. e->via->_inboundFragmentedMessages.erase(messageId);
  230. e->via->_inboundFragmentedMessages_l.unlock();
  231. e->via.zero();
  232. }
  233. // Slices are TriviallyCopyable and so may be memcpy'd from e->message to
  234. // the result parameter. This is fast.
  235. e->message.unsafeMoveTo(message);
  236. e->message.lastUsed = -1; // mark as "done" and force GC to collect
  237. return COMPLETE;
  238. }
  239. return OK;
  240. }
  241. /**
  242. * Erase all message entries in the internal queue
  243. */
  244. ZT_ALWAYS_INLINE void clear()
  245. {
  246. RWMutex::Lock ml(_messages_l);
  247. _messages.clear();
  248. }
  249. private:
  250. struct _E
  251. {
  252. ZT_ALWAYS_INLINE _E() : id(0),lastUsed(0),totalFragmentsExpected(0),via(),message(),lock() {}
  253. ZT_ALWAYS_INLINE ~_E()
  254. {
  255. via->_inboundFragmentedMessages_l.lock();
  256. via->_inboundFragmentedMessages.erase(id);
  257. via->_inboundFragmentedMessages_l.unlock();
  258. }
  259. uint64_t id;
  260. volatile int64_t lastUsed;
  261. unsigned int totalFragmentsExpected;
  262. SharedPtr<Path> via;
  263. FCV< Buf::Slice,MF > message;
  264. Mutex lock;
  265. };
  266. Hashtable< uint64_t,_E > _messages;
  267. RWMutex _messages_l;
  268. };
  269. } // namespace ZeroTier
  270. #endif