Dictionary.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /*
  2. * Copyright (c)2019 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 "Buffer.hpp"
  18. #include "Address.hpp"
  19. #include <stdint.h>
  20. namespace ZeroTier {
  21. /**
  22. * A small (in code and data) packed key=value store
  23. *
  24. * This stores data in the form of a compact blob that is sort of human
  25. * readable (depending on whether you put binary data in it) and is backward
  26. * compatible with older versions. Binary data is escaped such that the
  27. * serialized form of a Dictionary is always a valid null-terminated C string.
  28. *
  29. * Keys are restricted: no binary data, no CR/LF, and no equals (=). If a key
  30. * contains these characters it may not be retrievable. This is not checked.
  31. *
  32. * Lookup is via linear search and will be slow with a lot of keys. It's
  33. * designed for small things.
  34. *
  35. * There is code to test and fuzz this in selftest.cpp. Fuzzing a blob of
  36. * pointer tricks like this is important after any modifications.
  37. *
  38. * This is used for network configurations and for saving some things on disk
  39. * in the ZeroTier One service code.
  40. *
  41. * @tparam C Dictionary max capacity in bytes
  42. */
  43. template<unsigned int C>
  44. class Dictionary
  45. {
  46. public:
  47. Dictionary() { memset(_d,0,sizeof(_d)); }
  48. Dictionary(const char *s) { this->load(s); }
  49. Dictionary(const char *s,unsigned int len)
  50. {
  51. for(unsigned int i=0;i<C;++i) {
  52. if ((s)&&(i < len)) {
  53. if (!(_d[i] = *s))
  54. s = (const char *)0;
  55. else ++s;
  56. } else _d[i] = (char)0;
  57. }
  58. _d[C - 1] = (char)0;
  59. }
  60. Dictionary(const Dictionary &d) { memcpy(_d,d._d,C); }
  61. inline Dictionary &operator=(const Dictionary &d)
  62. {
  63. memcpy(_d,d._d,C);
  64. return *this;
  65. }
  66. inline operator bool() const { return (_d[0] != 0); }
  67. /**
  68. * Load a dictionary from a C-string
  69. *
  70. * @param s Dictionary in string form
  71. * @return False if 's' was longer than our capacity
  72. */
  73. inline bool load(const char *s)
  74. {
  75. for(unsigned int i=0;i<C;++i) {
  76. if (s) {
  77. if (!(_d[i] = *s))
  78. s = (const char *)0;
  79. else ++s;
  80. } else _d[i] = (char)0;
  81. }
  82. _d[C - 1] = (char)0;
  83. return (!s);
  84. }
  85. /**
  86. * Delete all entries
  87. */
  88. inline void clear()
  89. {
  90. memset(_d,0,sizeof(_d));
  91. }
  92. /**
  93. * @return Size of dictionary in bytes not including terminating NULL
  94. */
  95. inline unsigned int sizeBytes() const
  96. {
  97. for(unsigned int i=0;i<C;++i) {
  98. if (!_d[i])
  99. return i;
  100. }
  101. return C-1;
  102. }
  103. /**
  104. * Get an entry
  105. *
  106. * Note that to get binary values, dest[] should be at least one more than
  107. * the maximum size of the value being retrieved. That's because even if
  108. * the data is binary a terminating 0 is still appended to dest[] after it.
  109. *
  110. * If the key is not found, dest[0] is set to 0 to make dest[] an empty
  111. * C string in that case. The dest[] array will *never* be unterminated
  112. * after this call.
  113. *
  114. * Security note: if 'key' is ever directly based on anything that is not
  115. * a hard-code or internally-generated name, it must be checked to ensure
  116. * that the buffer is NULL-terminated since key[] does not take a secondary
  117. * size parameter. In NetworkConfig all keys are hard-coded strings so this
  118. * isn't a problem in the core.
  119. *
  120. * @param key Key to look up
  121. * @param dest Destination buffer
  122. * @param destlen Size of destination buffer
  123. * @return -1 if not found, or actual number of bytes stored in dest[] minus trailing 0
  124. */
  125. inline int get(const char *key,char *dest,unsigned int destlen) const
  126. {
  127. const char *p = _d;
  128. const char *const eof = p + C;
  129. const char *k;
  130. bool esc;
  131. int j;
  132. if (!destlen) // sanity check
  133. return -1;
  134. while (*p) {
  135. k = key;
  136. while ((*k)&&(*p)) {
  137. if (*p != *k)
  138. break;
  139. ++k;
  140. if (++p == eof) {
  141. dest[0] = (char)0;
  142. return -1;
  143. }
  144. }
  145. if ((!*k)&&(*p == '=')) {
  146. j = 0;
  147. esc = false;
  148. ++p;
  149. while ((*p != 0)&&(*p != 13)&&(*p != 10)) {
  150. if (esc) {
  151. esc = false;
  152. switch(*p) {
  153. case 'r': dest[j++] = 13; break;
  154. case 'n': dest[j++] = 10; break;
  155. case '0': dest[j++] = (char)0; break;
  156. case 'e': dest[j++] = '='; break;
  157. default: dest[j++] = *p; break;
  158. }
  159. if (j == (int)destlen) {
  160. dest[j-1] = (char)0;
  161. return j-1;
  162. }
  163. } else if (*p == '\\') {
  164. esc = true;
  165. } else {
  166. dest[j++] = *p;
  167. if (j == (int)destlen) {
  168. dest[j-1] = (char)0;
  169. return j-1;
  170. }
  171. }
  172. if (++p == eof) {
  173. dest[0] = (char)0;
  174. return -1;
  175. }
  176. }
  177. dest[j] = (char)0;
  178. return j;
  179. } else {
  180. while ((*p)&&(*p != 13)&&(*p != 10)) {
  181. if (++p == eof) {
  182. dest[0] = (char)0;
  183. return -1;
  184. }
  185. }
  186. if (*p) {
  187. if (++p == eof) {
  188. dest[0] = (char)0;
  189. return -1;
  190. }
  191. }
  192. else break;
  193. }
  194. }
  195. dest[0] = (char)0;
  196. return -1;
  197. }
  198. /**
  199. * Get the contents of a key into a buffer
  200. *
  201. * @param key Key to get
  202. * @param dest Destination buffer
  203. * @return True if key was found (if false, dest will be empty)
  204. * @tparam BC Buffer capacity (usually inferred)
  205. */
  206. template<unsigned int BC>
  207. inline bool get(const char *key,Buffer<BC> &dest) const
  208. {
  209. const int r = this->get(key,const_cast<char *>(reinterpret_cast<const char *>(dest.data())),BC);
  210. if (r >= 0) {
  211. dest.setSize((unsigned int)r);
  212. return true;
  213. } else {
  214. dest.clear();
  215. return false;
  216. }
  217. }
  218. /**
  219. * Get a boolean value
  220. *
  221. * @param key Key to look up
  222. * @param dfl Default value if not found in dictionary
  223. * @return Boolean value of key or 'dfl' if not found
  224. */
  225. bool getB(const char *key,bool dfl = false) const
  226. {
  227. char tmp[4];
  228. if (this->get(key,tmp,sizeof(tmp)) >= 0)
  229. return ((*tmp == '1')||(*tmp == 't')||(*tmp == 'T'));
  230. return dfl;
  231. }
  232. /**
  233. * Get an unsigned int64 stored as hex in the dictionary
  234. *
  235. * @param key Key to look up
  236. * @param dfl Default value or 0 if unspecified
  237. * @return Decoded hex UInt value or 'dfl' if not found
  238. */
  239. inline uint64_t getUI(const char *key,uint64_t dfl = 0) const
  240. {
  241. char tmp[128];
  242. if (this->get(key,tmp,sizeof(tmp)) >= 1)
  243. return Utils::hexStrToU64(tmp);
  244. return dfl;
  245. }
  246. /**
  247. * Get an unsigned int64 stored as hex in the dictionary
  248. *
  249. * @param key Key to look up
  250. * @param dfl Default value or 0 if unspecified
  251. * @return Decoded hex UInt value or 'dfl' if not found
  252. */
  253. inline int64_t getI(const char *key,int64_t dfl = 0) const
  254. {
  255. char tmp[128];
  256. if (this->get(key,tmp,sizeof(tmp)) >= 1)
  257. return Utils::hexStrTo64(tmp);
  258. return dfl;
  259. }
  260. /**
  261. * Add a new key=value pair
  262. *
  263. * If the key is already present this will append another, but the first
  264. * will always be returned by get(). This is not checked. If you want to
  265. * ensure a key is not present use erase() first.
  266. *
  267. * Use the vlen parameter to add binary values. Nulls will be escaped.
  268. *
  269. * @param key Key -- nulls, CR/LF, and equals (=) are illegal characters
  270. * @param value Value to set
  271. * @param vlen Length of value in bytes or -1 to treat value[] as a C-string and look for terminating 0
  272. * @return True if there was enough room to add this key=value pair
  273. */
  274. inline bool add(const char *key,const char *value,int vlen = -1)
  275. {
  276. for(unsigned int i=0;i<C;++i) {
  277. if (!_d[i]) {
  278. unsigned int j = i;
  279. if (j > 0) {
  280. _d[j++] = (char)10;
  281. if (j == C) {
  282. _d[i] = (char)0;
  283. return false;
  284. }
  285. }
  286. const char *p = key;
  287. while (*p) {
  288. _d[j++] = *(p++);
  289. if (j == C) {
  290. _d[i] = (char)0;
  291. return false;
  292. }
  293. }
  294. _d[j++] = '=';
  295. if (j == C) {
  296. _d[i] = (char)0;
  297. return false;
  298. }
  299. p = value;
  300. int k = 0;
  301. while ( ((vlen < 0)&&(*p)) || (k < vlen) ) {
  302. switch(*p) {
  303. case 0:
  304. case 13:
  305. case 10:
  306. case '\\':
  307. case '=':
  308. _d[j++] = '\\';
  309. if (j == C) {
  310. _d[i] = (char)0;
  311. return false;
  312. }
  313. switch(*p) {
  314. case 0: _d[j++] = '0'; break;
  315. case 13: _d[j++] = 'r'; break;
  316. case 10: _d[j++] = 'n'; break;
  317. case '\\': _d[j++] = '\\'; break;
  318. case '=': _d[j++] = 'e'; break;
  319. }
  320. if (j == C) {
  321. _d[i] = (char)0;
  322. return false;
  323. }
  324. break;
  325. default:
  326. _d[j++] = *p;
  327. if (j == C) {
  328. _d[i] = (char)0;
  329. return false;
  330. }
  331. break;
  332. }
  333. ++p;
  334. ++k;
  335. }
  336. _d[j] = (char)0;
  337. return true;
  338. }
  339. }
  340. return false;
  341. }
  342. /**
  343. * Add a boolean as a '1' or a '0'
  344. */
  345. inline bool add(const char *key,bool value)
  346. {
  347. return this->add(key,(value) ? "1" : "0",1);
  348. }
  349. /**
  350. * Add a 64-bit integer (unsigned) as a hex value
  351. */
  352. inline bool add(const char *key,uint64_t value)
  353. {
  354. char tmp[32];
  355. return this->add(key,Utils::hex(value,tmp),-1);
  356. }
  357. /**
  358. * Add a 64-bit integer (unsigned) as a hex value
  359. */
  360. inline bool add(const char *key,int64_t value)
  361. {
  362. char tmp[32];
  363. if (value >= 0) {
  364. return this->add(key,Utils::hex((uint64_t)value,tmp),-1);
  365. } else {
  366. tmp[0] = '-';
  367. return this->add(key,Utils::hex((uint64_t)(value * -1),tmp+1),-1);
  368. }
  369. }
  370. /**
  371. * Add a 64-bit integer (unsigned) as a hex value
  372. */
  373. inline bool add(const char *key,const Address &a)
  374. {
  375. char tmp[32];
  376. return this->add(key,Utils::hex(a.toInt(),tmp),-1);
  377. }
  378. /**
  379. * Add a binary buffer's contents as a value
  380. *
  381. * @tparam BC Buffer capacity (usually inferred)
  382. */
  383. template<unsigned int BC>
  384. inline bool add(const char *key,const Buffer<BC> &value)
  385. {
  386. return this->add(key,(const char *)value.data(),(int)value.size());
  387. }
  388. /**
  389. * @param key Key to check
  390. * @return True if key is present
  391. */
  392. inline bool contains(const char *key) const
  393. {
  394. char tmp[2];
  395. return (this->get(key,tmp,2) >= 0);
  396. }
  397. /**
  398. * @return Value of C template parameter
  399. */
  400. inline unsigned int capacity() const { return C; }
  401. inline const char *data() const { return _d; }
  402. inline char *unsafeData() { return _d; }
  403. private:
  404. char _d[C];
  405. };
  406. } // namespace ZeroTier
  407. #endif