util_format.c 15 KB

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