Dictionary.hpp 10 KB

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