2
0

Dictionary.hpp 10 KB

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