Dictionary.hpp 12 KB

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