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