Dictionary.hpp 11 KB

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