util_format.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file util_format.c
  8. *
  9. * \brief Miscellaneous functions for encoding and decoding various things
  10. * in base{16,32,64}.
  11. */
  12. #include "orconfig.h"
  13. #include "torlog.h"
  14. #include "util.h"
  15. #include "util_format.h"
  16. #include "torint.h"
  17. #include <stddef.h>
  18. #include <string.h>
  19. #include <stdlib.h>
  20. /* Return the base32 encoded size in bytes using the source length srclen.
  21. * The NUL terminated byte is added as well since every base32 encoding
  22. * requires enough space for it. */
  23. size_t
  24. base32_encoded_size(size_t srclen)
  25. {
  26. size_t enclen;
  27. enclen = CEIL_DIV(srclen*8, 5) + 1;
  28. tor_assert(enclen < INT_MAX && enclen > srclen);
  29. return enclen;
  30. }
  31. /** Implements base32 encoding as in RFC 4648. */
  32. void
  33. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  34. {
  35. unsigned int i, v, u;
  36. size_t nbits = srclen * 8;
  37. size_t bit;
  38. tor_assert(srclen < SIZE_T_CEILING/8);
  39. /* We need enough space for the encoded data and the extra NUL byte. */
  40. tor_assert(base32_encoded_size(srclen) <= destlen);
  41. tor_assert(destlen < SIZE_T_CEILING);
  42. /* Make sure we leave no uninitialized data in the destination buffer. */
  43. memset(dest, 0, destlen);
  44. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  45. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  46. size_t idx = bit / 8;
  47. v = ((uint8_t)src[idx]) << 8;
  48. if (idx+1 < srclen)
  49. v += (uint8_t)src[idx+1];
  50. /* set u to the 5-bit value at the bit'th bit of buf. */
  51. u = (v >> (11-(bit%8))) & 0x1F;
  52. dest[i] = BASE32_CHARS[u];
  53. }
  54. dest[i] = '\0';
  55. }
  56. /** Implements base32 decoding as in RFC 4648.
  57. * Returns 0 if successful, -1 otherwise.
  58. */
  59. int
  60. base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  61. {
  62. /* XXXX we might want to rewrite this along the lines of base64_decode, if
  63. * it ever shows up in the profile. */
  64. unsigned int i;
  65. size_t nbits, j, bit;
  66. char *tmp;
  67. nbits = ((srclen * 5) / 8) * 8;
  68. tor_assert(srclen < SIZE_T_CEILING / 5);
  69. tor_assert((nbits/8) <= destlen); /* We need enough space. */
  70. tor_assert(destlen < SIZE_T_CEILING);
  71. /* Make sure we leave no uninitialized data in the destination buffer. */
  72. memset(dest, 0, destlen);
  73. /* Convert base32 encoded chars to the 5-bit values that they represent. */
  74. tmp = tor_malloc_zero(srclen);
  75. for (j = 0; j < srclen; ++j) {
  76. if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
  77. else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
  78. else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
  79. else {
  80. log_warn(LD_GENERAL, "illegal character in base32 encoded string");
  81. tor_free(tmp);
  82. return -1;
  83. }
  84. }
  85. /* Assemble result byte-wise by applying five possible cases. */
  86. for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
  87. switch (bit % 40) {
  88. case 0:
  89. dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
  90. (((uint8_t)tmp[(bit/5)+1]) >> 2);
  91. break;
  92. case 8:
  93. dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
  94. (((uint8_t)tmp[(bit/5)+1]) << 1) +
  95. (((uint8_t)tmp[(bit/5)+2]) >> 4);
  96. break;
  97. case 16:
  98. dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
  99. (((uint8_t)tmp[(bit/5)+1]) >> 1);
  100. break;
  101. case 24:
  102. dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
  103. (((uint8_t)tmp[(bit/5)+1]) << 2) +
  104. (((uint8_t)tmp[(bit/5)+2]) >> 3);
  105. break;
  106. case 32:
  107. dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
  108. ((uint8_t)tmp[(bit/5)+1]);
  109. break;
  110. }
  111. }
  112. memset(tmp, 0, srclen); /* on the heap, this should be safe */
  113. tor_free(tmp);
  114. tmp = NULL;
  115. return 0;
  116. }
  117. #define BASE64_OPENSSL_LINELEN 64
  118. /** Return the Base64 encoded size of <b>srclen</b> bytes of data in
  119. * bytes.
  120. *
  121. * If <b>flags</b>&amp;BASE64_ENCODE_MULTILINE is true, return the size
  122. * of the encoded output as multiline output (64 character, `\n' terminated
  123. * lines).
  124. */
  125. size_t
  126. base64_encode_size(size_t srclen, int flags)
  127. {
  128. size_t enclen;
  129. tor_assert(srclen < INT_MAX);
  130. if (srclen == 0)
  131. return 0;
  132. enclen = ((srclen - 1) / 3) * 4 + 4;
  133. if (flags & BASE64_ENCODE_MULTILINE) {
  134. size_t remainder = enclen % BASE64_OPENSSL_LINELEN;
  135. enclen += enclen / BASE64_OPENSSL_LINELEN;
  136. if (remainder)
  137. enclen++;
  138. }
  139. tor_assert(enclen < INT_MAX && enclen > srclen);
  140. return enclen;
  141. }
  142. /** Internal table mapping 6 bit values to the Base64 alphabet. */
  143. static const char base64_encode_table[64] = {
  144. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  145. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  146. 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  147. 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  148. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  149. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  150. 'w', 'x', 'y', 'z', '0', '1', '2', '3',
  151. '4', '5', '6', '7', '8', '9', '+', '/'
  152. };
  153. /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  154. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  155. * bytes. Return the number of bytes written on success; -1 if
  156. * destlen is too short, or other failure.
  157. *
  158. * If <b>flags</b>&amp;BASE64_ENCODE_MULTILINE is true, return encoded
  159. * output in multiline format (64 character, `\n' terminated lines).
  160. */
  161. int
  162. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen,
  163. int flags)
  164. {
  165. const unsigned char *usrc = (unsigned char *)src;
  166. const unsigned char *eous = usrc + srclen;
  167. char *d = dest;
  168. uint32_t n = 0;
  169. size_t linelen = 0;
  170. size_t enclen;
  171. int n_idx = 0;
  172. if (!src || !dest)
  173. return -1;
  174. /* Ensure that there is sufficient space, including the NUL. */
  175. enclen = base64_encode_size(srclen, flags);
  176. if (destlen < enclen + 1)
  177. return -1;
  178. if (destlen > SIZE_T_CEILING)
  179. return -1;
  180. if (enclen > INT_MAX)
  181. return -1;
  182. /* Make sure we leave no uninitialized data in the destination buffer. */
  183. memset(dest, 0, destlen);
  184. /* XXX/Yawning: If this ends up being too slow, this can be sped up
  185. * by separating the multiline format case and the normal case, and
  186. * processing 48 bytes of input at a time when newlines are desired.
  187. */
  188. #define ENCODE_CHAR(ch) \
  189. STMT_BEGIN \
  190. *d++ = ch; \
  191. if (flags & BASE64_ENCODE_MULTILINE) { \
  192. if (++linelen % BASE64_OPENSSL_LINELEN == 0) { \
  193. linelen = 0; \
  194. *d++ = '\n'; \
  195. } \
  196. } \
  197. STMT_END
  198. #define ENCODE_N(idx) \
  199. ENCODE_CHAR(base64_encode_table[(n >> ((3 - idx) * 6)) & 0x3f])
  200. #define ENCODE_PAD() ENCODE_CHAR('=')
  201. /* Iterate over all the bytes in src. Each one will add 8 bits to the
  202. * value we're encoding. Accumulate bits in <b>n</b>, and whenever we
  203. * have 24 bits, batch them into 4 bytes and flush those bytes to dest.
  204. */
  205. for ( ; usrc < eous; ++usrc) {
  206. n = (n << 8) | *usrc;
  207. if ((++n_idx) == 3) {
  208. ENCODE_N(0);
  209. ENCODE_N(1);
  210. ENCODE_N(2);
  211. ENCODE_N(3);
  212. n_idx = 0;
  213. n = 0;
  214. }
  215. }
  216. switch (n_idx) {
  217. case 0:
  218. /* 0 leftover bits, no pading to add. */
  219. break;
  220. case 1:
  221. /* 8 leftover bits, pad to 12 bits, write the 2 6-bit values followed
  222. * by 2 padding characters.
  223. */
  224. n <<= 4;
  225. ENCODE_N(2);
  226. ENCODE_N(3);
  227. ENCODE_PAD();
  228. ENCODE_PAD();
  229. break;
  230. case 2:
  231. /* 16 leftover bits, pad to 18 bits, write the 3 6-bit values followed
  232. * by 1 padding character.
  233. */
  234. n <<= 2;
  235. ENCODE_N(1);
  236. ENCODE_N(2);
  237. ENCODE_N(3);
  238. ENCODE_PAD();
  239. break;
  240. default:
  241. /* Something went catastrophically wrong. */
  242. tor_fragile_assert(); // LCOV_EXCL_LINE
  243. return -1;
  244. }
  245. #undef ENCODE_N
  246. #undef ENCODE_PAD
  247. #undef ENCODE_CHAR
  248. /* Multiline output always includes at least one newline. */
  249. if (flags & BASE64_ENCODE_MULTILINE && linelen != 0)
  250. *d++ = '\n';
  251. tor_assert(d - dest == (ptrdiff_t)enclen);
  252. *d++ = '\0'; /* NUL terminate the output. */
  253. return (int) enclen;
  254. }
  255. /** As base64_encode, but do not add any internal spaces or external padding
  256. * to the output stream. */
  257. int
  258. base64_encode_nopad(char *dest, size_t destlen,
  259. const uint8_t *src, size_t srclen)
  260. {
  261. int n = base64_encode(dest, destlen, (const char*) src, srclen, 0);
  262. if (n <= 0)
  263. return n;
  264. tor_assert((size_t)n < destlen && dest[n] == 0);
  265. char *in, *out;
  266. in = out = dest;
  267. while (*in) {
  268. if (*in == '=' || *in == '\n') {
  269. ++in;
  270. } else {
  271. *out++ = *in++;
  272. }
  273. }
  274. *out = 0;
  275. tor_assert(out - dest <= INT_MAX);
  276. return (int)(out - dest);
  277. }
  278. /** As base64_decode, but do not require any padding on the input */
  279. int
  280. base64_decode_nopad(uint8_t *dest, size_t destlen,
  281. const char *src, size_t srclen)
  282. {
  283. if (srclen > SIZE_T_CEILING - 4)
  284. return -1;
  285. char *buf = tor_malloc(srclen + 4);
  286. memcpy(buf, src, srclen+1);
  287. size_t buflen;
  288. switch (srclen % 4)
  289. {
  290. case 0:
  291. default:
  292. buflen = srclen;
  293. break;
  294. case 1:
  295. tor_free(buf);
  296. return -1;
  297. case 2:
  298. memcpy(buf+srclen, "==", 3);
  299. buflen = srclen + 2;
  300. break;
  301. case 3:
  302. memcpy(buf+srclen, "=", 2);
  303. buflen = srclen + 1;
  304. break;
  305. }
  306. int n = base64_decode((char*)dest, destlen, buf, buflen);
  307. tor_free(buf);
  308. return n;
  309. }
  310. #undef BASE64_OPENSSL_LINELEN
  311. /** @{ */
  312. /** Special values used for the base64_decode_table */
  313. #define X 255
  314. #define SP 64
  315. #define PAD 65
  316. /** @} */
  317. /** Internal table mapping byte values to what they represent in base64.
  318. * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
  319. * skipped. Xs are invalid and must not appear in base64. PAD indicates
  320. * end-of-string. */
  321. static const uint8_t base64_decode_table[256] = {
  322. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
  323. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  324. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  325. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  326. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  327. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  328. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  329. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  330. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  331. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  332. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  333. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  334. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  335. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  336. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  337. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  338. };
  339. /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  340. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  341. * bytes. Return the number of bytes written on success; -1 if
  342. * destlen is too short, or other failure.
  343. *
  344. * NOTE 1: destlen is checked conservatively, as though srclen contained no
  345. * spaces or padding.
  346. *
  347. * NOTE 2: This implementation does not check for the correct number of
  348. * padding "=" characters at the end of the string, and does not check
  349. * for internal padding characters.
  350. */
  351. int
  352. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  353. {
  354. const char *eos = src+srclen;
  355. uint32_t n=0;
  356. int n_idx=0;
  357. char *dest_orig = dest;
  358. /* Max number of bits == srclen*6.
  359. * Number of bytes required to hold all bits == (srclen*6)/8.
  360. * Yes, we want to round down: anything that hangs over the end of a
  361. * byte is padding. */
  362. if (!size_mul_check(srclen, 3) || destlen < (srclen*3)/4)
  363. return -1;
  364. if (destlen > SIZE_T_CEILING)
  365. return -1;
  366. /* Make sure we leave no uninitialized data in the destination buffer. */
  367. memset(dest, 0, destlen);
  368. /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
  369. * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
  370. * 24 bits, batch them into 3 bytes and flush those bytes to dest.
  371. */
  372. for ( ; src < eos; ++src) {
  373. unsigned char c = (unsigned char) *src;
  374. uint8_t v = base64_decode_table[c];
  375. switch (v) {
  376. case X:
  377. /* This character isn't allowed in base64. */
  378. return -1;
  379. case SP:
  380. /* This character is whitespace, and has no effect. */
  381. continue;
  382. case PAD:
  383. /* We've hit an = character: the data is over. */
  384. goto end_of_loop;
  385. default:
  386. /* We have an actual 6-bit value. Append it to the bits in n. */
  387. n = (n<<6) | v;
  388. if ((++n_idx) == 4) {
  389. /* We've accumulated 24 bits in n. Flush them. */
  390. *dest++ = (n>>16);
  391. *dest++ = (n>>8) & 0xff;
  392. *dest++ = (n) & 0xff;
  393. n_idx = 0;
  394. n = 0;
  395. }
  396. }
  397. }
  398. end_of_loop:
  399. /* If we have leftover bits, we need to cope. */
  400. switch (n_idx) {
  401. case 0:
  402. default:
  403. /* No leftover bits. We win. */
  404. break;
  405. case 1:
  406. /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
  407. return -1;
  408. case 2:
  409. /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
  410. *dest++ = n >> 4;
  411. break;
  412. case 3:
  413. /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
  414. *dest++ = n >> 10;
  415. *dest++ = n >> 2;
  416. }
  417. tor_assert((dest-dest_orig) <= (ssize_t)destlen);
  418. tor_assert((dest-dest_orig) <= INT_MAX);
  419. return (int)(dest-dest_orig);
  420. }
  421. #undef X
  422. #undef SP
  423. #undef PAD
  424. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  425. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  426. * <b>dest</b>.
  427. */
  428. void
  429. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  430. {
  431. const char *end;
  432. char *cp;
  433. tor_assert(destlen >= srclen*2+1);
  434. tor_assert(destlen < SIZE_T_CEILING);
  435. /* Make sure we leave no uninitialized data in the destination buffer. */
  436. memset(dest, 0, destlen);
  437. cp = dest;
  438. end = src+srclen;
  439. while (src<end) {
  440. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  441. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  442. ++src;
  443. }
  444. *cp = '\0';
  445. }
  446. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  447. static inline int
  448. hex_decode_digit_(char c)
  449. {
  450. switch (c) {
  451. case '0': return 0;
  452. case '1': return 1;
  453. case '2': return 2;
  454. case '3': return 3;
  455. case '4': return 4;
  456. case '5': return 5;
  457. case '6': return 6;
  458. case '7': return 7;
  459. case '8': return 8;
  460. case '9': return 9;
  461. case 'A': case 'a': return 10;
  462. case 'B': case 'b': return 11;
  463. case 'C': case 'c': return 12;
  464. case 'D': case 'd': return 13;
  465. case 'E': case 'e': return 14;
  466. case 'F': case 'f': return 15;
  467. default:
  468. return -1;
  469. }
  470. }
  471. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  472. int
  473. hex_decode_digit(char c)
  474. {
  475. return hex_decode_digit_(c);
  476. }
  477. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode
  478. * it and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  479. * Return the number of bytes decoded on success, -1 on failure. If
  480. * <b>destlen</b> is greater than INT_MAX or less than half of
  481. * <b>srclen</b>, -1 is returned. */
  482. int
  483. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  484. {
  485. const char *end;
  486. char *dest_orig = dest;
  487. int v1,v2;
  488. if ((srclen % 2) != 0)
  489. return -1;
  490. if (destlen < srclen/2 || destlen > INT_MAX)
  491. return -1;
  492. /* Make sure we leave no uninitialized data in the destination buffer. */
  493. memset(dest, 0, destlen);
  494. end = src+srclen;
  495. while (src<end) {
  496. v1 = hex_decode_digit_(*src);
  497. v2 = hex_decode_digit_(*(src+1));
  498. if (v1<0||v2<0)
  499. return -1;
  500. *(uint8_t*)dest = (v1<<4)|v2;
  501. ++dest;
  502. src+=2;
  503. }
  504. tor_assert((dest-dest_orig) <= (ptrdiff_t) destlen);
  505. return (int) (dest-dest_orig);
  506. }