base64.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /* -*- buffer-read-only: t -*- vi: set ro: */
  2. /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
  3. /* base64.c -- Encode binary data using printable characters.
  4. Copyright (C) 1999, 2000, 2001, 2004, 2005, 2006, 2007 Free Software
  5. Foundation, Inc.
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  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. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software Foundation,
  16. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  17. /* Written by Simon Josefsson. Partially adapted from GNU MailUtils
  18. * (mailbox/filter_trans.c, as of 2004-11-28). Improved by review
  19. * from Paul Eggert, Bruno Haible, and Stepan Kasal.
  20. *
  21. * See also RFC 3548 <http://www.ietf.org/rfc/rfc3548.txt>.
  22. *
  23. * Be careful with error checking. Here is how you would typically
  24. * use these functions:
  25. *
  26. * bool ok = base64_decode_alloc (in, inlen, &out, &outlen);
  27. * if (!ok)
  28. * FAIL: input was not valid base64
  29. * if (out == NULL)
  30. * FAIL: memory allocation error
  31. * OK: data in OUT/OUTLEN
  32. *
  33. * size_t outlen = base64_encode_alloc (in, inlen, &out);
  34. * if (out == NULL && outlen == 0 && inlen != 0)
  35. * FAIL: input too long
  36. * if (out == NULL)
  37. * FAIL: memory allocation error
  38. * OK: data in OUT/OUTLEN.
  39. *
  40. */
  41. /*#include <config.h>*/
  42. /* Get prototype. */
  43. #include "base64.h"
  44. /* Get malloc. */
  45. #include <stdlib.h>
  46. /* Get UCHAR_MAX. */
  47. #include <limits.h>
  48. #include <string.h>
  49. /* C89 compliant way to cast 'char' to 'unsigned char'. */
  50. static unsigned char
  51. to_uchar (char ch)
  52. {
  53. return ch;
  54. }
  55. /* Base64 encode IN array of size INLEN into OUT array of size OUTLEN.
  56. If OUTLEN is less than BASE64_LENGTH(INLEN), write as many bytes as
  57. possible. If OUTLEN is larger than BASE64_LENGTH(INLEN), also zero
  58. terminate the output buffer. */
  59. void
  60. base64_encode (const char *in, size_t inlen,
  61. char *out, size_t outlen)
  62. {
  63. static const char b64str[] =
  64. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  65. while (inlen && outlen)
  66. {
  67. *out++ = b64str[(to_uchar (in[0]) >> 2) & 0x3f];
  68. if (!--outlen)
  69. break;
  70. *out++ = b64str[((to_uchar (in[0]) << 4)
  71. + (--inlen ? to_uchar (in[1]) >> 4 : 0))
  72. & 0x3f];
  73. if (!--outlen)
  74. break;
  75. *out++ =
  76. (inlen
  77. ? b64str[((to_uchar (in[1]) << 2)
  78. + (--inlen ? to_uchar (in[2]) >> 6 : 0))
  79. & 0x3f]
  80. : '=');
  81. if (!--outlen)
  82. break;
  83. *out++ = inlen ? b64str[to_uchar (in[2]) & 0x3f] : '=';
  84. if (!--outlen)
  85. break;
  86. if (inlen)
  87. inlen--;
  88. if (inlen)
  89. in += 3;
  90. }
  91. if (outlen)
  92. *out = '\0';
  93. }
  94. /* Allocate a buffer and store zero terminated base64 encoded data
  95. from array IN of size INLEN, returning BASE64_LENGTH(INLEN), i.e.,
  96. the length of the encoded data, excluding the terminating zero. On
  97. return, the OUT variable will hold a pointer to newly allocated
  98. memory that must be deallocated by the caller. If output string
  99. length would overflow, 0 is returned and OUT is set to NULL. If
  100. memory allocation failed, OUT is set to NULL, and the return value
  101. indicates length of the requested memory block, i.e.,
  102. BASE64_LENGTH(inlen) + 1. */
  103. size_t
  104. base64_encode_alloc (const char *in, size_t inlen, char **out)
  105. {
  106. size_t outlen = 1 + BASE64_LENGTH (inlen);
  107. /* Check for overflow in outlen computation.
  108. *
  109. * If there is no overflow, outlen >= inlen.
  110. *
  111. * If the operation (inlen + 2) overflows then it yields at most +1, so
  112. * outlen is 0.
  113. *
  114. * If the multiplication overflows, we lose at least half of the
  115. * correct value, so the result is < ((inlen + 2) / 3) * 2, which is
  116. * less than (inlen + 2) * 0.66667, which is less than inlen as soon as
  117. * (inlen > 4).
  118. */
  119. if (inlen > outlen)
  120. {
  121. *out = NULL;
  122. return 0;
  123. }
  124. *out = (char *)malloc (outlen);
  125. if (!*out)
  126. return outlen;
  127. base64_encode (in, inlen, *out, outlen);
  128. return outlen - 1;
  129. }
  130. /* With this approach this file works independent of the charset used
  131. (think EBCDIC). However, it does assume that the characters in the
  132. Base64 alphabet (A-Za-z0-9+/) are encoded in 0..255. POSIX
  133. 1003.1-2001 require that char and unsigned char are 8-bit
  134. quantities, though, taking care of that problem. But this may be a
  135. potential problem on non-POSIX C99 platforms.
  136. IBM C V6 for AIX mishandles "#define B64(x) ...'x'...", so use "_"
  137. as the formal parameter rather than "x". */
  138. #define B64(_) \
  139. ((_) == 'A' ? 0 \
  140. : (_) == 'B' ? 1 \
  141. : (_) == 'C' ? 2 \
  142. : (_) == 'D' ? 3 \
  143. : (_) == 'E' ? 4 \
  144. : (_) == 'F' ? 5 \
  145. : (_) == 'G' ? 6 \
  146. : (_) == 'H' ? 7 \
  147. : (_) == 'I' ? 8 \
  148. : (_) == 'J' ? 9 \
  149. : (_) == 'K' ? 10 \
  150. : (_) == 'L' ? 11 \
  151. : (_) == 'M' ? 12 \
  152. : (_) == 'N' ? 13 \
  153. : (_) == 'O' ? 14 \
  154. : (_) == 'P' ? 15 \
  155. : (_) == 'Q' ? 16 \
  156. : (_) == 'R' ? 17 \
  157. : (_) == 'S' ? 18 \
  158. : (_) == 'T' ? 19 \
  159. : (_) == 'U' ? 20 \
  160. : (_) == 'V' ? 21 \
  161. : (_) == 'W' ? 22 \
  162. : (_) == 'X' ? 23 \
  163. : (_) == 'Y' ? 24 \
  164. : (_) == 'Z' ? 25 \
  165. : (_) == 'a' ? 26 \
  166. : (_) == 'b' ? 27 \
  167. : (_) == 'c' ? 28 \
  168. : (_) == 'd' ? 29 \
  169. : (_) == 'e' ? 30 \
  170. : (_) == 'f' ? 31 \
  171. : (_) == 'g' ? 32 \
  172. : (_) == 'h' ? 33 \
  173. : (_) == 'i' ? 34 \
  174. : (_) == 'j' ? 35 \
  175. : (_) == 'k' ? 36 \
  176. : (_) == 'l' ? 37 \
  177. : (_) == 'm' ? 38 \
  178. : (_) == 'n' ? 39 \
  179. : (_) == 'o' ? 40 \
  180. : (_) == 'p' ? 41 \
  181. : (_) == 'q' ? 42 \
  182. : (_) == 'r' ? 43 \
  183. : (_) == 's' ? 44 \
  184. : (_) == 't' ? 45 \
  185. : (_) == 'u' ? 46 \
  186. : (_) == 'v' ? 47 \
  187. : (_) == 'w' ? 48 \
  188. : (_) == 'x' ? 49 \
  189. : (_) == 'y' ? 50 \
  190. : (_) == 'z' ? 51 \
  191. : (_) == '0' ? 52 \
  192. : (_) == '1' ? 53 \
  193. : (_) == '2' ? 54 \
  194. : (_) == '3' ? 55 \
  195. : (_) == '4' ? 56 \
  196. : (_) == '5' ? 57 \
  197. : (_) == '6' ? 58 \
  198. : (_) == '7' ? 59 \
  199. : (_) == '8' ? 60 \
  200. : (_) == '9' ? 61 \
  201. : (_) == '+' ? 62 \
  202. : (_) == '/' ? 63 \
  203. : -1)
  204. static const signed char b64[0x100] = {
  205. B64 (0), B64 (1), B64 (2), B64 (3),
  206. B64 (4), B64 (5), B64 (6), B64 (7),
  207. B64 (8), B64 (9), B64 (10), B64 (11),
  208. B64 (12), B64 (13), B64 (14), B64 (15),
  209. B64 (16), B64 (17), B64 (18), B64 (19),
  210. B64 (20), B64 (21), B64 (22), B64 (23),
  211. B64 (24), B64 (25), B64 (26), B64 (27),
  212. B64 (28), B64 (29), B64 (30), B64 (31),
  213. B64 (32), B64 (33), B64 (34), B64 (35),
  214. B64 (36), B64 (37), B64 (38), B64 (39),
  215. B64 (40), B64 (41), B64 (42), B64 (43),
  216. B64 (44), B64 (45), B64 (46), B64 (47),
  217. B64 (48), B64 (49), B64 (50), B64 (51),
  218. B64 (52), B64 (53), B64 (54), B64 (55),
  219. B64 (56), B64 (57), B64 (58), B64 (59),
  220. B64 (60), B64 (61), B64 (62), B64 (63),
  221. B64 (64), B64 (65), B64 (66), B64 (67),
  222. B64 (68), B64 (69), B64 (70), B64 (71),
  223. B64 (72), B64 (73), B64 (74), B64 (75),
  224. B64 (76), B64 (77), B64 (78), B64 (79),
  225. B64 (80), B64 (81), B64 (82), B64 (83),
  226. B64 (84), B64 (85), B64 (86), B64 (87),
  227. B64 (88), B64 (89), B64 (90), B64 (91),
  228. B64 (92), B64 (93), B64 (94), B64 (95),
  229. B64 (96), B64 (97), B64 (98), B64 (99),
  230. B64 (100), B64 (101), B64 (102), B64 (103),
  231. B64 (104), B64 (105), B64 (106), B64 (107),
  232. B64 (108), B64 (109), B64 (110), B64 (111),
  233. B64 (112), B64 (113), B64 (114), B64 (115),
  234. B64 (116), B64 (117), B64 (118), B64 (119),
  235. B64 (120), B64 (121), B64 (122), B64 (123),
  236. B64 (124), B64 (125), B64 (126), B64 (127),
  237. B64 (128), B64 (129), B64 (130), B64 (131),
  238. B64 (132), B64 (133), B64 (134), B64 (135),
  239. B64 (136), B64 (137), B64 (138), B64 (139),
  240. B64 (140), B64 (141), B64 (142), B64 (143),
  241. B64 (144), B64 (145), B64 (146), B64 (147),
  242. B64 (148), B64 (149), B64 (150), B64 (151),
  243. B64 (152), B64 (153), B64 (154), B64 (155),
  244. B64 (156), B64 (157), B64 (158), B64 (159),
  245. B64 (160), B64 (161), B64 (162), B64 (163),
  246. B64 (164), B64 (165), B64 (166), B64 (167),
  247. B64 (168), B64 (169), B64 (170), B64 (171),
  248. B64 (172), B64 (173), B64 (174), B64 (175),
  249. B64 (176), B64 (177), B64 (178), B64 (179),
  250. B64 (180), B64 (181), B64 (182), B64 (183),
  251. B64 (184), B64 (185), B64 (186), B64 (187),
  252. B64 (188), B64 (189), B64 (190), B64 (191),
  253. B64 (192), B64 (193), B64 (194), B64 (195),
  254. B64 (196), B64 (197), B64 (198), B64 (199),
  255. B64 (200), B64 (201), B64 (202), B64 (203),
  256. B64 (204), B64 (205), B64 (206), B64 (207),
  257. B64 (208), B64 (209), B64 (210), B64 (211),
  258. B64 (212), B64 (213), B64 (214), B64 (215),
  259. B64 (216), B64 (217), B64 (218), B64 (219),
  260. B64 (220), B64 (221), B64 (222), B64 (223),
  261. B64 (224), B64 (225), B64 (226), B64 (227),
  262. B64 (228), B64 (229), B64 (230), B64 (231),
  263. B64 (232), B64 (233), B64 (234), B64 (235),
  264. B64 (236), B64 (237), B64 (238), B64 (239),
  265. B64 (240), B64 (241), B64 (242), B64 (243),
  266. B64 (244), B64 (245), B64 (246), B64 (247),
  267. B64 (248), B64 (249), B64 (250), B64 (251),
  268. B64 (252), B64 (253), B64 (254), B64 (255)
  269. };
  270. #if UCHAR_MAX == 255
  271. # define uchar_in_range(c) true
  272. #else
  273. # define uchar_in_range(c) ((c) <= 255)
  274. #endif
  275. /* Return true if CH is a character from the Base64 alphabet, and
  276. false otherwise. Note that '=' is padding and not considered to be
  277. part of the alphabet. */
  278. bool
  279. isbase64 (char ch)
  280. {
  281. return uchar_in_range (to_uchar (ch)) && 0 <= b64[to_uchar (ch)];
  282. }
  283. /* Initialize decode-context buffer, CTX. */
  284. void
  285. base64_decode_ctx_init (struct base64_decode_context *ctx)
  286. {
  287. ctx->i = 0;
  288. }
  289. /* If CTX->i is 0 or 4, there are four or more bytes in [*IN..IN_END), and
  290. none of those four is a newline, then return *IN. Otherwise, copy up to
  291. 4 - CTX->i non-newline bytes from that range into CTX->buf, starting at
  292. index CTX->i and setting CTX->i to reflect the number of bytes copied,
  293. and return CTX->buf. In either case, advance *IN to point to the byte
  294. after the last one processed, and set *N_NON_NEWLINE to the number of
  295. verified non-newline bytes accessible through the returned pointer. */
  296. static char *
  297. get_4 (struct base64_decode_context *ctx,
  298. char const **in, char const *in_end,
  299. size_t *n_non_newline)
  300. {
  301. if (ctx->i == 4)
  302. ctx->i = 0;
  303. if (ctx->i == 0)
  304. {
  305. char const *t = *in;
  306. if (4 <= in_end - *in && memchr (t, '\n', 4) == NULL)
  307. {
  308. /* This is the common case: no newline. */
  309. *in += 4;
  310. *n_non_newline = 4;
  311. return (char *) t;
  312. }
  313. }
  314. {
  315. /* Copy non-newline bytes into BUF. */
  316. char const *p = *in;
  317. while (p < in_end)
  318. {
  319. char c = *p++;
  320. if (c != '\n')
  321. {
  322. ctx->buf[ctx->i++] = c;
  323. if (ctx->i == 4)
  324. break;
  325. }
  326. }
  327. *in = p;
  328. *n_non_newline = ctx->i;
  329. return ctx->buf;
  330. }
  331. }
  332. #define return_false \
  333. do \
  334. { \
  335. *outp = out; \
  336. return false; \
  337. } \
  338. while (false)
  339. /* Decode up to four bytes of base64-encoded data, IN, of length INLEN
  340. into the output buffer, *OUT, of size *OUTLEN bytes. Return true if
  341. decoding is successful, false otherwise. If *OUTLEN is too small,
  342. as many bytes as possible are written to *OUT. On return, advance
  343. *OUT to point to the byte after the last one written, and decrement
  344. *OUTLEN to reflect the number of bytes remaining in *OUT. */
  345. static bool
  346. decode_4 (char const *in, size_t inlen,
  347. char **outp, size_t *outleft)
  348. {
  349. char *out = *outp;
  350. if (inlen < 2)
  351. return false;
  352. if (!isbase64 (in[0]) || !isbase64 (in[1]))
  353. return false;
  354. if (*outleft)
  355. {
  356. *out++ = ((b64[to_uchar (in[0])] << 2)
  357. | (b64[to_uchar (in[1])] >> 4));
  358. --*outleft;
  359. }
  360. if (inlen == 2)
  361. return_false;
  362. if (in[2] == '=')
  363. {
  364. if (inlen != 4)
  365. return_false;
  366. if (in[3] != '=')
  367. return_false;
  368. }
  369. else
  370. {
  371. if (!isbase64 (in[2]))
  372. return_false;
  373. if (*outleft)
  374. {
  375. *out++ = (((b64[to_uchar (in[1])] << 4) & 0xf0)
  376. | (b64[to_uchar (in[2])] >> 2));
  377. --*outleft;
  378. }
  379. if (inlen == 3)
  380. return_false;
  381. if (in[3] == '=')
  382. {
  383. if (inlen != 4)
  384. return_false;
  385. }
  386. else
  387. {
  388. if (!isbase64 (in[3]))
  389. return_false;
  390. if (*outleft)
  391. {
  392. *out++ = (((b64[to_uchar (in[2])] << 6) & 0xc0)
  393. | b64[to_uchar (in[3])]);
  394. --*outleft;
  395. }
  396. }
  397. }
  398. *outp = out;
  399. return true;
  400. }
  401. /* Decode base64-encoded input array IN of length INLEN to output array
  402. OUT that can hold *OUTLEN bytes. The input data may be interspersed
  403. with newlines. Return true if decoding was successful, i.e. if the
  404. input was valid base64 data, false otherwise. If *OUTLEN is too
  405. small, as many bytes as possible will be written to OUT. On return,
  406. *OUTLEN holds the length of decoded bytes in OUT. Note that as soon
  407. as any non-alphabet, non-newline character is encountered, decoding
  408. is stopped and false is returned. If INLEN is zero, then process
  409. only whatever data is stored in CTX.
  410. Initially, CTX must have been initialized via base64_decode_ctx_init.
  411. Subsequent calls to this function must reuse whatever state is recorded
  412. in that buffer. It is necessary for when a quadruple of base64 input
  413. bytes spans two input buffers. */
  414. bool
  415. base64_decode (struct base64_decode_context *ctx,
  416. const char *in, size_t inlen,
  417. char *out, size_t *outlen)
  418. {
  419. size_t outleft = *outlen;
  420. bool flush_ctx = inlen == 0;
  421. while (true)
  422. {
  423. size_t outleft_save = outleft;
  424. if (ctx->i == 0 && !flush_ctx)
  425. {
  426. while (true)
  427. {
  428. /* Save a copy of outleft, in case we need to re-parse this
  429. block of four bytes. */
  430. outleft_save = outleft;
  431. if (!decode_4 (in, inlen, &out, &outleft))
  432. break;
  433. in += 4;
  434. inlen -= 4;
  435. }
  436. }
  437. if (inlen == 0 && !flush_ctx)
  438. break;
  439. /* Handle the common case of 72-byte wrapped lines.
  440. This also handles any other multiple-of-4-byte wrapping. */
  441. if (inlen && *in == '\n')
  442. {
  443. ++in;
  444. --inlen;
  445. continue;
  446. }
  447. /* Restore OUT and OUTLEFT. */
  448. out -= outleft_save - outleft;
  449. outleft = outleft_save;
  450. {
  451. char const *in_end = in + inlen;
  452. char const *non_nl = get_4 (ctx, &in, in_end, &inlen);
  453. /* If the input is empty or consists solely of newlines (0 non-newlines),
  454. then we're done. Likewise if there are fewer than 4 bytes when not
  455. flushing context. */
  456. if (inlen == 0 || (inlen < 4 && !flush_ctx))
  457. {
  458. inlen = 0;
  459. break;
  460. }
  461. if (!decode_4 (non_nl, inlen, &out, &outleft))
  462. break;
  463. inlen = in_end - in;
  464. }
  465. }
  466. *outlen -= outleft;
  467. return inlen == 0;
  468. }
  469. /* Allocate an output buffer in *OUT, and decode the base64 encoded
  470. data stored in IN of size INLEN to the *OUT buffer. On return, the
  471. size of the decoded data is stored in *OUTLEN. OUTLEN may be NULL,
  472. if the caller is not interested in the decoded length. *OUT may be
  473. NULL to indicate an out of memory error, in which case *OUTLEN
  474. contains the size of the memory block needed. The function returns
  475. true on successful decoding and memory allocation errors. (Use the
  476. *OUT and *OUTLEN parameters to differentiate between successful
  477. decoding and memory error.) The function returns false if the
  478. input was invalid, in which case *OUT is NULL and *OUTLEN is
  479. undefined. */
  480. bool
  481. base64_decode_alloc (struct base64_decode_context *ctx,
  482. const char *in, size_t inlen, char **out,
  483. size_t *outlen)
  484. {
  485. /* This may allocate a few bytes too many, depending on input,
  486. but it's not worth the extra CPU time to compute the exact size.
  487. The exact size is 3 * inlen / 4, minus 1 if the input ends
  488. with "=" and minus another 1 if the input ends with "==".
  489. Dividing before multiplying avoids the possibility of overflow. */
  490. size_t needlen = 3 * (inlen / 4) + 2;
  491. *out = (char *)malloc (needlen);
  492. if (!*out)
  493. return true;
  494. if (!base64_decode (ctx, in, inlen, *out, &needlen))
  495. {
  496. free (*out);
  497. *out = NULL;
  498. return false;
  499. }
  500. if (outlen)
  501. *outlen = needlen;
  502. return true;
  503. }