Dictionary.hpp 10 KB

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