Defragmenter.hpp 12 KB

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