Dictionary.hpp 9.6 KB

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