Dictionary.hpp 12 KB

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