Dictionary.hpp 11 KB

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