Dictionary.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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_DICTIONARY_HPP
  14. #define ZT_DICTIONARY_HPP
  15. #include "Constants.hpp"
  16. #include "Utils.hpp"
  17. #include "Address.hpp"
  18. #include "Buf.hpp"
  19. #include "Containers.hpp"
  20. namespace ZeroTier {
  21. class Identity;
  22. /**
  23. * A simple key-value store for short keys
  24. *
  25. * This data structure is used for network configurations, node meta-data,
  26. * and other open-definition protocol objects.
  27. *
  28. * If this seems a little odd, it is. It dates back to the very first alpha
  29. * versions of ZeroTier and if it were redesigned today we'd use some kind
  30. * of simple or standardized binary encoding. Nevertheless it is efficient
  31. * and it works so there is no need to change it and break backward
  32. * compatibility.
  33. *
  34. * Use of the append functions is faster than building and then encoding a
  35. * dictionary for creating outbound packets.
  36. */
  37. class Dictionary
  38. {
  39. public:
  40. typedef SortedMap< String, Vector < uint8_t > >::const_iterator const_iterator;
  41. Dictionary();
  42. ~Dictionary();
  43. /**
  44. * Get a reference to a value
  45. *
  46. * @param k Key to look up
  47. * @return Reference to value
  48. */
  49. Vector <uint8_t> &operator[](const char *k);
  50. /**
  51. * Get a const reference to a value
  52. *
  53. * @param k Key to look up
  54. * @return Reference to value or to empty vector if not found
  55. */
  56. const Vector <uint8_t> &operator[](const char *k) const;
  57. /**
  58. * @return Start of key->value pairs
  59. */
  60. ZT_INLINE const_iterator begin() const noexcept
  61. { return m_entries.begin(); }
  62. /**
  63. * @return End of key->value pairs
  64. */
  65. ZT_INLINE const_iterator end() const noexcept
  66. { return m_entries.end(); }
  67. /**
  68. * Add a boolean as '1' or '0'
  69. */
  70. void add(const char *k, bool v);
  71. /**
  72. * Add an integer as a hexadecimal string value
  73. *
  74. * @param k Key to set
  75. * @param v Integer to set, will be cast to uint64_t and stored as hex
  76. */
  77. ZT_INLINE void add(const char *const k, const uint64_t v)
  78. { char buf[17]; add(k, Utils::hex((uint64_t)(v), buf)); }
  79. /**
  80. * Add an integer as a hexadecimal string value
  81. *
  82. * @param k Key to set
  83. * @param v Integer to set, will be cast to uint64_t and stored as hex
  84. */
  85. ZT_INLINE void add(const char *const k, const int64_t v)
  86. { char buf[17]; add(k, Utils::hex((uint64_t)(v), buf)); }
  87. /**
  88. * Add an address in 10-digit hex string format
  89. */
  90. void add(const char *k, const Address &v);
  91. /**
  92. * Add a C string as a value
  93. */
  94. void add(const char *k, const char *v);
  95. /**
  96. * Add a binary blob as a value
  97. */
  98. void add(const char *k, const void *data, unsigned int len);
  99. /**
  100. * Get a boolean
  101. *
  102. * @param k Key to look up
  103. * @param dfl Default value (default: false)
  104. * @return Value of key or default if not found
  105. */
  106. bool getB(const char *k, bool dfl = false) const;
  107. /**
  108. * Get an integer
  109. *
  110. * @param k Key to look up
  111. * @param dfl Default value (default: 0)
  112. * @return Value of key or default if not found
  113. */
  114. uint64_t getUI(const char *k, uint64_t dfl = 0) const;
  115. /**
  116. * Get a C string
  117. *
  118. * If the buffer is too small the string will be truncated, but the
  119. * buffer will always end in a terminating null no matter what.
  120. *
  121. * @param k Key to look up
  122. * @param v Buffer to hold string
  123. * @param cap Maximum size of string (including terminating null)
  124. */
  125. char *getS(const char *k, char *v, unsigned int cap) const;
  126. /**
  127. * Get an object supporting the marshal/unmarshal interface pattern
  128. *
  129. * @tparam T Object type (inferred)
  130. * @param k Key to look up
  131. * @param obj Object to unmarshal() into
  132. * @return True if unmarshal was successful
  133. */
  134. template< typename T >
  135. ZT_INLINE bool getO(const char *k, T &obj) const
  136. {
  137. const Vector< uint8_t > &d = (*this)[k];
  138. if (d.empty())
  139. return false;
  140. return (obj.unmarshal(d.data(), (unsigned int)d.size()) > 0);
  141. }
  142. /**
  143. * Add an object supporting the marshal/unmarshal interface pattern
  144. *
  145. * @tparam T Object type (inferred)
  146. * @param k Key to add
  147. * @param obj Object to marshal() into vector
  148. * @return True if successful
  149. */
  150. template< typename T >
  151. ZT_INLINE bool addO(const char *k, T &obj)
  152. {
  153. uint8_t tmp[4096];
  154. static_assert(sizeof(tmp) >= T::marshalSizeMax(),"buffer too small");
  155. int l = obj.marshal(tmp);
  156. if (l > 0) {
  157. (*this)[k].assign(tmp, tmp + l);
  158. return true;
  159. }
  160. return false;
  161. }
  162. /**
  163. * Erase all entries in dictionary
  164. */
  165. void clear();
  166. /**
  167. * @return Number of entries
  168. */
  169. ZT_INLINE unsigned int size() const noexcept
  170. { return m_entries.size(); }
  171. /**
  172. * @return True if dictionary is not empty
  173. */
  174. ZT_INLINE bool empty() const noexcept
  175. { return m_entries.empty(); }
  176. /**
  177. * Encode to a string in the supplied vector
  178. *
  179. * @param out String encoded dictionary
  180. */
  181. void encode(Vector <uint8_t> &out) const;
  182. /**
  183. * Decode a string encoded dictionary
  184. *
  185. * This will decode up to 'len' but will also abort if it finds a
  186. * null/zero as this could be a C string.
  187. *
  188. * @param data Data to decode
  189. * @param len Length of data
  190. * @return True if dictionary was formatted correctly and valid, false on error
  191. */
  192. bool decode(const void *data, unsigned int len);
  193. /**
  194. * Append a key=value pair to a buffer (vector or FCV)
  195. *
  196. * @param out Buffer
  197. * @param k Key (must be <= 8 characters)
  198. * @param v Value
  199. */
  200. template< typename V >
  201. ZT_INLINE static void append(V &out, const char *const k, const bool v)
  202. {
  203. s_appendKey(out, k);
  204. out.push_back((uint8_t)(v ? '1' : '0'));
  205. out.push_back((uint8_t)'\n');
  206. }
  207. /**
  208. * Append a key=value pair to a buffer (vector or FCV)
  209. *
  210. * @param out Buffer
  211. * @param k Key (must be <= 8 characters)
  212. * @param v Value
  213. */
  214. template< typename V >
  215. ZT_INLINE static void append(V &out, const char *const k, const Address v)
  216. {
  217. s_appendKey(out, k);
  218. const uint64_t a = v.toInt();
  219. static_assert(ZT_ADDRESS_LENGTH_HEX == 10, "this must be rewritten for any change in address length");
  220. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 36U) & 0xfU]);
  221. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 32U) & 0xfU]);
  222. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 28U) & 0xfU]);
  223. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 24U) & 0xfU]);
  224. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 20U) & 0xfU]);
  225. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 16U) & 0xfU]);
  226. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 12U) & 0xfU]);
  227. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 8U) & 0xfU]);
  228. out.push_back((uint8_t)Utils::HEXCHARS[(a >> 4U) & 0xfU]);
  229. out.push_back((uint8_t)Utils::HEXCHARS[a & 0xfU]);
  230. out.push_back((uint8_t)'\n');
  231. }
  232. /**
  233. * Append a key=value pair to a buffer (vector or FCV)
  234. *
  235. * @param out Buffer
  236. * @param k Key (must be <= 8 characters)
  237. * @param v Value
  238. */
  239. template< typename V >
  240. ZT_INLINE static void append(V &out, const char *const k, const uint64_t v)
  241. {
  242. s_appendKey(out, k);
  243. char buf[17];
  244. Utils::hex(v, buf);
  245. unsigned int i = 0;
  246. while (buf[i])
  247. out.push_back((uint8_t)buf[i++]);
  248. out.push_back((uint8_t)'\n');
  249. }
  250. template< typename V >
  251. ZT_INLINE static void append(V &out, const char *const k, const int64_t v)
  252. { append(out, k, (uint64_t)v); }
  253. template< typename V >
  254. ZT_INLINE static void append(V &out, const char *const k, const uint32_t v)
  255. { append(out, k, (uint64_t)v); }
  256. template< typename V >
  257. ZT_INLINE static void append(V &out, const char *const k, const int32_t v)
  258. { append(out, k, (uint64_t)v); }
  259. template< typename V >
  260. ZT_INLINE static void append(V &out, const char *const k, const uint16_t v)
  261. { append(out, k, (uint64_t)v); }
  262. template< typename V >
  263. ZT_INLINE static void append(V &out, const char *const k, const int16_t v)
  264. { append(out, k, (uint64_t)v); }
  265. template< typename V >
  266. ZT_INLINE static void append(V &out, const char *const k, const uint8_t v)
  267. { append(out, k, (uint64_t)v); }
  268. template< typename V >
  269. ZT_INLINE static void append(V &out, const char *const k, const int8_t v)
  270. { append(out, k, (uint64_t)v); }
  271. /**
  272. * Append a key=value pair to a buffer (vector or FCV)
  273. *
  274. * @param out Buffer
  275. * @param k Key (must be <= 8 characters)
  276. * @param v Value
  277. */
  278. template< typename V >
  279. ZT_INLINE static void append(V &out, const char *const k, const char *v)
  280. {
  281. if ((v) && (*v)) {
  282. s_appendKey(out, k);
  283. while (*v)
  284. s_appendValueByte(out, (uint8_t)*(v++));
  285. out.push_back((uint8_t)'\n');
  286. }
  287. }
  288. /**
  289. * Append a key=value pair to a buffer (vector or FCV)
  290. *
  291. * @param out Buffer
  292. * @param k Key (must be <= 8 characters)
  293. * @param v Value
  294. * @param vlen Value length in bytes
  295. */
  296. template< typename V >
  297. ZT_INLINE static void append(V &out, const char *const k, const void *const v, const unsigned int vlen)
  298. {
  299. s_appendKey(out, k);
  300. for (unsigned int i = 0; i < vlen; ++i)
  301. s_appendValueByte(out, reinterpret_cast<const uint8_t *>(v)[i]);
  302. out.push_back((uint8_t)'\n');
  303. }
  304. /**
  305. * Append a packet ID as raw bytes in the provided byte order
  306. *
  307. * @param out Buffer
  308. * @param k Key (must be <= 8 characters)
  309. * @param pid Packet ID
  310. */
  311. template< typename V >
  312. static ZT_INLINE void appendPacketId(V &out, const char *const k, const uint64_t pid)
  313. { append(out, k, &pid, 8); }
  314. /**
  315. * Append key=value with any object implementing the correct marshal interface
  316. *
  317. * @param out Buffer
  318. * @param k Key (must be <= 8 characters)
  319. * @param v Marshal-able object
  320. * @return Bytes appended or negative on error (return value of marshal())
  321. */
  322. template< typename V, typename T >
  323. static ZT_INLINE int appendObject(V &out, const char *const k, const T &v)
  324. {
  325. uint8_t tmp[4096]; // large enough for any current object
  326. if (T::marshalSizeMax() > sizeof(tmp))
  327. return -1;
  328. const int mlen = v.marshal(tmp);
  329. if (mlen > 0)
  330. append(out, k, tmp, (unsigned int)mlen);
  331. return mlen;
  332. }
  333. /**
  334. * Append #sub where sub is a hexadecimal string to 'name' and store in 'buf'
  335. *
  336. * @param buf Buffer to store subscript key
  337. * @param name Root name
  338. * @param sub Subscript index
  339. * @return Pointer to 'buf'
  340. */
  341. static char *arraySubscript(char buf[256],const char *name,const unsigned long sub) noexcept;
  342. private:
  343. template< typename V >
  344. ZT_INLINE static void s_appendValueByte(V &out, const uint8_t c)
  345. {
  346. switch (c) {
  347. case 0:
  348. out.push_back(92); // backslash
  349. out.push_back(48);
  350. break;
  351. case 10:
  352. out.push_back(92);
  353. out.push_back(110);
  354. break;
  355. case 13:
  356. out.push_back(92);
  357. out.push_back(114);
  358. break;
  359. case 61:
  360. out.push_back(92);
  361. out.push_back(101);
  362. break;
  363. case 92:
  364. out.push_back(92);
  365. out.push_back(92);
  366. break;
  367. default:
  368. out.push_back(c);
  369. break;
  370. }
  371. }
  372. template< typename V >
  373. ZT_INLINE static void s_appendKey(V &out, const char *k)
  374. {
  375. for (;;) {
  376. const char c = *(k++);
  377. if ((c >= 33) && (c <= 126) && (c != 61) && (c != 92)) // printable ASCII with no spaces, equals, or backslash
  378. out.push_back((uint8_t)c);
  379. else if (c == 0)
  380. break;
  381. }
  382. out.push_back((uint8_t)'=');
  383. }
  384. static String s_key(const char *k) noexcept;
  385. // Dictionary maps need to be sorted so that they always encode in the same order
  386. // to yield blobs that can be hashed and signed reproducibly. Other than for areas
  387. // where dictionaries are signed and verified the order doesn't matter.
  388. SortedMap < String, Vector< uint8_t > > m_entries;
  389. };
  390. } // namespace ZeroTier
  391. #endif