Dictionary.hpp 10 KB

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