Dictionary.hpp 10 KB

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