Defragmenter.hpp 12 KB

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