util_format.c 15 KB

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