Dictionary.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef ZT_DICTIONARY_HPP
  19. #define ZT_DICTIONARY_HPP
  20. #include "Constants.hpp"
  21. #include "Utils.hpp"
  22. #include "Buffer.hpp"
  23. #include "Address.hpp"
  24. #include <stdint.h>
  25. namespace ZeroTier {
  26. /**
  27. * A small (in code and data) packed key=value store
  28. *
  29. * This stores data in the form of a compact blob that is sort of human
  30. * readable (depending on whether you put binary data in it) and is backward
  31. * compatible with older versions. Binary data is escaped such that the
  32. * serialized form of a Dictionary is always a valid null-terminated C string.
  33. *
  34. * Keys are restricted: no binary data, no CR/LF, and no equals (=). If a key
  35. * contains these characters it may not be retrievable. This is not checked.
  36. *
  37. * Lookup is via linear search and will be slow with a lot of keys. It's
  38. * designed for small things.
  39. *
  40. * There is code to test and fuzz this in selftest.cpp. Fuzzing a blob of
  41. * pointer tricks like this is important after any modifications.
  42. *
  43. * This is used for network configurations and for saving some things on disk
  44. * in the ZeroTier One service code.
  45. *
  46. * @tparam C Dictionary max capacity in bytes
  47. */
  48. template<unsigned int C>
  49. class Dictionary
  50. {
  51. public:
  52. Dictionary()
  53. {
  54. _d[0] = (char)0;
  55. }
  56. Dictionary(const char *s)
  57. {
  58. if (s) {
  59. Utils::scopy(_d,sizeof(_d),s);
  60. } else {
  61. _d[0] = (char)0;
  62. }
  63. }
  64. Dictionary(const char *s,unsigned int len)
  65. {
  66. if (s) {
  67. if (len > (C-1))
  68. len = C-1;
  69. memcpy(_d,s,len);
  70. _d[len] = (char)0;
  71. } else {
  72. _d[0] = (char)0;
  73. }
  74. }
  75. Dictionary(const Dictionary &d)
  76. {
  77. Utils::scopy(_d,sizeof(_d),d._d);
  78. }
  79. inline Dictionary &operator=(const Dictionary &d)
  80. {
  81. Utils::scopy(_d,sizeof(_d),d._d);
  82. return *this;
  83. }
  84. /**
  85. * Load a dictionary from a C-string
  86. *
  87. * @param s Dictionary in string form
  88. * @return False if 's' was longer than our capacity
  89. */
  90. inline bool load(const char *s)
  91. {
  92. if (s) {
  93. return Utils::scopy(_d,sizeof(_d),s);
  94. } else {
  95. _d[0] = (char)0;
  96. return true;
  97. }
  98. }
  99. /**
  100. * Delete all entries
  101. */
  102. inline void clear()
  103. {
  104. _d[0] = (char)0;
  105. }
  106. /**
  107. * @return Size of dictionary in bytes not including terminating NULL
  108. */
  109. inline unsigned int sizeBytes() const
  110. {
  111. for(unsigned int i=0;i<C;++i) {
  112. if (!_d[i])
  113. return i;
  114. }
  115. return C-1;
  116. }
  117. /**
  118. * Get an entry
  119. *
  120. * Note that to get binary values, dest[] should be at least one more than
  121. * the maximum size of the value being retrieved. That's because even if
  122. * the data is binary a terminating 0 is still appended to dest[] after it.
  123. *
  124. * If the key is not found, dest[0] is set to 0 to make dest[] an empty
  125. * C string in that case. The dest[] array will *never* be unterminated
  126. * after this call.
  127. *
  128. * Security note: if 'key' is ever directly based on anything that is not
  129. * a hard-code or internally-generated name, it must be checked to ensure
  130. * that the buffer is NULL-terminated since key[] does not take a secondary
  131. * size parameter. In NetworkConfig all keys are hard-coded strings so this
  132. * isn't a problem in the core.
  133. *
  134. * @param key Key to look up
  135. * @param dest Destination buffer
  136. * @param destlen Size of destination buffer
  137. * @return -1 if not found, or actual number of bytes stored in dest[] minus trailing 0
  138. */
  139. inline int get(const char *key,char *dest,unsigned int destlen) const
  140. {
  141. const char *p = _d;
  142. const char *const eof = p + C;
  143. const char *k;
  144. bool esc;
  145. int j;
  146. if (!destlen) // sanity check
  147. return -1;
  148. while (*p) {
  149. k = key;
  150. while ((*k)&&(*p)) {
  151. if (*p != *k)
  152. break;
  153. ++k;
  154. if (++p == eof) {
  155. dest[0] = (char)0;
  156. return -1;
  157. }
  158. }
  159. if ((!*k)&&(*p == '=')) {
  160. j = 0;
  161. esc = false;
  162. ++p;
  163. while ((*p != 0)&&(*p != '\r')&&(*p != '\n')) {
  164. if (esc) {
  165. esc = false;
  166. switch(*p) {
  167. case 'r': dest[j++] = '\r'; break;
  168. case 'n': dest[j++] = '\n'; break;
  169. case '0': dest[j++] = (char)0; break;
  170. case 'e': dest[j++] = '='; break;
  171. default: dest[j++] = *p; break;
  172. }
  173. if (j == (int)destlen) {
  174. dest[j-1] = (char)0;
  175. return j-1;
  176. }
  177. } else if (*p == '\\') {
  178. esc = true;
  179. } else {
  180. dest[j++] = *p;
  181. if (j == (int)destlen) {
  182. dest[j-1] = (char)0;
  183. return j-1;
  184. }
  185. }
  186. if (++p == eof) {
  187. dest[0] = (char)0;
  188. return -1;
  189. }
  190. }
  191. dest[j] = (char)0;
  192. return j;
  193. } else {
  194. while ((*p)&&(*p != '\r')&&(*p != '\n')) {
  195. if (++p == eof) {
  196. dest[0] = (char)0;
  197. return -1;
  198. }
  199. }
  200. if (*p) {
  201. if (++p == eof) {
  202. dest[0] = (char)0;
  203. return -1;
  204. }
  205. }
  206. else break;
  207. }
  208. }
  209. dest[0] = (char)0;
  210. return -1;
  211. }
  212. /**
  213. * Get the contents of a key into a buffer
  214. *
  215. * @param key Key to get
  216. * @param dest Destination buffer
  217. * @return True if key was found (if false, dest will be empty)
  218. * @tparam BC Buffer capacity (usually inferred)
  219. */
  220. template<unsigned int BC>
  221. inline bool get(const char *key,Buffer<BC> &dest) const
  222. {
  223. const int r = this->get(key,const_cast<char *>(reinterpret_cast<const char *>(dest.data())),BC);
  224. if (r >= 0) {
  225. dest.setSize((unsigned int)r);
  226. return true;
  227. } else {
  228. dest.clear();
  229. return false;
  230. }
  231. }
  232. /**
  233. * Get a boolean value
  234. *
  235. * @param key Key to look up
  236. * @param dfl Default value if not found in dictionary
  237. * @return Boolean value of key or 'dfl' if not found
  238. */
  239. bool getB(const char *key,bool dfl = false) const
  240. {
  241. char tmp[4];
  242. if (this->get(key,tmp,sizeof(tmp)) >= 0)
  243. return ((*tmp == '1')||(*tmp == 't')||(*tmp == 'T'));
  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 uint64_t getUI(const char *key,uint64_t dfl = 0) const
  254. {
  255. char tmp[128];
  256. if (this->get(key,tmp,sizeof(tmp)) >= 1)
  257. return Utils::hexStrToU64(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++] = '\n';
  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 '\r':
  305. case '\n':
  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 '\r': _d[j++] = 'r'; break;
  316. case '\n': _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. Utils::snprintf(tmp,sizeof(tmp),"%llx",(unsigned long long)value);
  356. return this->add(key,tmp,-1);
  357. }
  358. /**
  359. * Add a 64-bit integer (unsigned) as a hex value
  360. */
  361. inline bool add(const char *key,const Address &a)
  362. {
  363. char tmp[32];
  364. Utils::snprintf(tmp,sizeof(tmp),"%.10llx",(unsigned long long)a.toInt());
  365. return this->add(key,tmp,-1);
  366. }
  367. /**
  368. * Add a binary buffer's contents as a value
  369. *
  370. * @tparam BC Buffer capacity (usually inferred)
  371. */
  372. template<unsigned int BC>
  373. inline bool add(const char *key,const Buffer<BC> &value)
  374. {
  375. return this->add(key,(const char *)value.data(),(int)value.size());
  376. }
  377. /**
  378. * @param key Key to check
  379. * @return True if key is present
  380. */
  381. inline bool contains(const char *key) const
  382. {
  383. char tmp[2];
  384. return (this->get(key,tmp,2) >= 0);
  385. }
  386. /**
  387. * Erase a key from this dictionary
  388. *
  389. * Use this before add() to ensure that a key is replaced if it might
  390. * already be present.
  391. *
  392. * @param key Key to erase
  393. * @return True if key was found and erased
  394. */
  395. inline bool erase(const char *key)
  396. {
  397. char d2[C];
  398. char *saveptr = (char *)0;
  399. unsigned int d2ptr = 0;
  400. bool found = false;
  401. for(char *f=Utils::stok(_d,"\r\n",&saveptr);(f);f=Utils::stok((char *)0,"\r\n",&saveptr)) {
  402. if (*f) {
  403. const char *p = f;
  404. const char *k = key;
  405. while ((*k)&&(*p)) {
  406. if (*k != *p)
  407. break;
  408. ++k;
  409. ++p;
  410. }
  411. if (*k) {
  412. p = f;
  413. while (*p)
  414. d2[d2ptr++] = *(p++);
  415. d2[d2ptr++] = '\n';
  416. } else {
  417. found = true;
  418. }
  419. }
  420. }
  421. d2[d2ptr++] = (char)0;
  422. memcpy(_d,d2,d2ptr);
  423. return found;
  424. }
  425. /**
  426. * @return Value of C template parameter
  427. */
  428. inline unsigned int capacity() const { return C; }
  429. inline const char *data() const { return _d; }
  430. inline char *unsafeData() { return _d; }
  431. private:
  432. char _d[C];
  433. };
  434. } // namespace ZeroTier
  435. #endif