Dictionary.hpp 10 KB

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