base64.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /* Base64 encode/decode strings or files.
  2. Copyright (C) 2004-2018 Free Software Foundation, Inc.
  3. This file is part of Base64.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. /* Written by Simon Josefsson <simon@josefsson.org>. */
  15. #include <config.h>
  16. #include <stdio.h>
  17. #include <getopt.h>
  18. #include <sys/types.h>
  19. #include "system.h"
  20. #include "die.h"
  21. #include "error.h"
  22. #include "fadvise.h"
  23. #include "quote.h"
  24. #include "xstrtol.h"
  25. #include "xdectoint.h"
  26. #include "xbinary-io.h"
  27. #define AUTHORS proper_name ("Simon Josefsson")
  28. #if BASE_TYPE == 32
  29. # include "base32.h"
  30. # define PROGRAM_NAME "base32"
  31. #else
  32. # include "base64.h"
  33. # define PROGRAM_NAME "base64"
  34. #endif
  35. static struct option const long_options[] =
  36. {
  37. {"decode", no_argument, 0, 'd'},
  38. {"wrap", required_argument, 0, 'w'},
  39. {"ignore-garbage", no_argument, 0, 'i'},
  40. {GETOPT_HELP_OPTION_DECL},
  41. {GETOPT_VERSION_OPTION_DECL},
  42. {NULL, 0, NULL, 0}
  43. };
  44. void
  45. usage (int status)
  46. {
  47. if (status != EXIT_SUCCESS)
  48. emit_try_help ();
  49. else
  50. {
  51. printf (_("\
  52. Usage: %s [OPTION]... [FILE]\n\
  53. Base%d encode or decode FILE, or standard input, to standard output.\n\
  54. "), program_name, BASE_TYPE);
  55. emit_stdin_note ();
  56. emit_mandatory_arg_note ();
  57. fputs (_("\
  58. -d, --decode decode data\n\
  59. -i, --ignore-garbage when decoding, ignore non-alphabet characters\n\
  60. -w, --wrap=COLS wrap encoded lines after COLS character (default 76).\n\
  61. Use 0 to disable line wrapping\n\
  62. \n\
  63. "), stdout);
  64. fputs (HELP_OPTION_DESCRIPTION, stdout);
  65. fputs (VERSION_OPTION_DESCRIPTION, stdout);
  66. printf (_("\
  67. \n\
  68. The data are encoded as described for the %s alphabet in RFC 4648.\n\
  69. When decoding, the input may contain newlines in addition to the bytes of\n\
  70. the formal %s alphabet. Use --ignore-garbage to attempt to recover\n\
  71. from any other non-alphabet bytes in the encoded stream.\n"),
  72. PROGRAM_NAME, PROGRAM_NAME);
  73. emit_ancillary_info (PROGRAM_NAME);
  74. }
  75. exit (status);
  76. }
  77. #define ENC_BLOCKSIZE (1024*3*10)
  78. #if BASE_TYPE == 32
  79. # define BASE_LENGTH BASE32_LENGTH
  80. /* Note that increasing this may decrease performance if --ignore-garbage
  81. is used, because of the memmove operation below. */
  82. # define DEC_BLOCKSIZE (1024*5)
  83. /* Ensure that BLOCKSIZE is a multiple of 5 and 8. */
  84. verify (ENC_BLOCKSIZE % 40 == 0); /* So padding chars only on last block. */
  85. verify (DEC_BLOCKSIZE % 40 == 0); /* So complete encoded blocks are used. */
  86. # define base_encode base32_encode
  87. # define base_decode_context base32_decode_context
  88. # define base_decode_ctx_init base32_decode_ctx_init
  89. # define base_decode_ctx base32_decode_ctx
  90. # define isbase isbase32
  91. #else
  92. # define BASE_LENGTH BASE64_LENGTH
  93. /* Note that increasing this may decrease performance if --ignore-garbage
  94. is used, because of the memmove operation below. */
  95. # define DEC_BLOCKSIZE (1024*3)
  96. /* Ensure that BLOCKSIZE is a multiple of 3 and 4. */
  97. verify (ENC_BLOCKSIZE % 12 == 0); /* So padding chars only on last block. */
  98. verify (DEC_BLOCKSIZE % 12 == 0); /* So complete encoded blocks are used. */
  99. # define base_encode base64_encode
  100. # define base_decode_context base64_decode_context
  101. # define base_decode_ctx_init base64_decode_ctx_init
  102. # define base_decode_ctx base64_decode_ctx
  103. # define isbase isbase64
  104. #endif
  105. static void
  106. wrap_write (const char *buffer, size_t len,
  107. uintmax_t wrap_column, size_t *current_column, FILE *out)
  108. {
  109. size_t written;
  110. if (wrap_column == 0)
  111. {
  112. /* Simple write. */
  113. if (fwrite (buffer, 1, len, stdout) < len)
  114. die (EXIT_FAILURE, errno, _("write error"));
  115. }
  116. else
  117. for (written = 0; written < len;)
  118. {
  119. uintmax_t cols_remaining = wrap_column - *current_column;
  120. size_t to_write = MIN (cols_remaining, SIZE_MAX);
  121. to_write = MIN (to_write, len - written);
  122. if (to_write == 0)
  123. {
  124. if (fputc ('\n', out) == EOF)
  125. die (EXIT_FAILURE, errno, _("write error"));
  126. *current_column = 0;
  127. }
  128. else
  129. {
  130. if (fwrite (buffer + written, 1, to_write, stdout) < to_write)
  131. die (EXIT_FAILURE, errno, _("write error"));
  132. *current_column += to_write;
  133. written += to_write;
  134. }
  135. }
  136. }
  137. static void
  138. do_encode (FILE *in, FILE *out, uintmax_t wrap_column)
  139. {
  140. size_t current_column = 0;
  141. char inbuf[ENC_BLOCKSIZE];
  142. char outbuf[BASE_LENGTH (ENC_BLOCKSIZE)];
  143. size_t sum;
  144. do
  145. {
  146. size_t n;
  147. sum = 0;
  148. do
  149. {
  150. n = fread (inbuf + sum, 1, ENC_BLOCKSIZE - sum, in);
  151. sum += n;
  152. }
  153. while (!feof (in) && !ferror (in) && sum < ENC_BLOCKSIZE);
  154. if (sum > 0)
  155. {
  156. /* Process input one block at a time. Note that ENC_BLOCKSIZE
  157. is sized so that no pad chars will appear in output. */
  158. base_encode (inbuf, sum, outbuf, BASE_LENGTH (sum));
  159. wrap_write (outbuf, BASE_LENGTH (sum), wrap_column,
  160. &current_column, out);
  161. }
  162. }
  163. while (!feof (in) && !ferror (in) && sum == ENC_BLOCKSIZE);
  164. /* When wrapping, terminate last line. */
  165. if (wrap_column && current_column > 0 && fputc ('\n', out) == EOF)
  166. die (EXIT_FAILURE, errno, _("write error"));
  167. if (ferror (in))
  168. die (EXIT_FAILURE, errno, _("read error"));
  169. }
  170. static void
  171. do_decode (FILE *in, FILE *out, bool ignore_garbage)
  172. {
  173. char inbuf[BASE_LENGTH (DEC_BLOCKSIZE)];
  174. char outbuf[DEC_BLOCKSIZE];
  175. size_t sum;
  176. struct base_decode_context ctx;
  177. base_decode_ctx_init (&ctx);
  178. do
  179. {
  180. bool ok;
  181. size_t n;
  182. unsigned int k;
  183. sum = 0;
  184. do
  185. {
  186. n = fread (inbuf + sum, 1, BASE_LENGTH (DEC_BLOCKSIZE) - sum, in);
  187. if (ignore_garbage)
  188. {
  189. for (size_t i = 0; n > 0 && i < n;)
  190. {
  191. if (isbase (inbuf[sum + i]) || inbuf[sum + i] == '=')
  192. i++;
  193. else
  194. memmove (inbuf + sum + i, inbuf + sum + i + 1, --n - i);
  195. }
  196. }
  197. sum += n;
  198. if (ferror (in))
  199. die (EXIT_FAILURE, errno, _("read error"));
  200. }
  201. while (sum < BASE_LENGTH (DEC_BLOCKSIZE) && !feof (in));
  202. /* The following "loop" is usually iterated just once.
  203. However, when it processes the final input buffer, we want
  204. to iterate it one additional time, but with an indicator
  205. telling it to flush what is in CTX. */
  206. for (k = 0; k < 1 + !!feof (in); k++)
  207. {
  208. if (k == 1 && ctx.i == 0)
  209. break;
  210. n = DEC_BLOCKSIZE;
  211. ok = base_decode_ctx (&ctx, inbuf, (k == 0 ? sum : 0), outbuf, &n);
  212. if (fwrite (outbuf, 1, n, out) < n)
  213. die (EXIT_FAILURE, errno, _("write error"));
  214. if (!ok)
  215. die (EXIT_FAILURE, 0, _("invalid input"));
  216. }
  217. }
  218. while (!feof (in));
  219. }
  220. int
  221. main (int argc, char **argv)
  222. {
  223. int opt;
  224. FILE *input_fh;
  225. const char *infile;
  226. /* True if --decode has been given and we should decode data. */
  227. bool decode = false;
  228. /* True if we should ignore non-base-alphabetic characters. */
  229. bool ignore_garbage = false;
  230. /* Wrap encoded data around the 76:th column, by default. */
  231. uintmax_t wrap_column = 76;
  232. initialize_main (&argc, &argv);
  233. set_program_name (argv[0]);
  234. setlocale (LC_ALL, "");
  235. bindtextdomain (PACKAGE, LOCALEDIR);
  236. textdomain (PACKAGE);
  237. atexit (close_stdout);
  238. while ((opt = getopt_long (argc, argv, "diw:", long_options, NULL)) != -1)
  239. switch (opt)
  240. {
  241. case 'd':
  242. decode = true;
  243. break;
  244. case 'w':
  245. wrap_column = xdectoumax (optarg, 0, UINTMAX_MAX, "",
  246. _("invalid wrap size"), 0);
  247. break;
  248. case 'i':
  249. ignore_garbage = true;
  250. break;
  251. case_GETOPT_HELP_CHAR;
  252. case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
  253. default:
  254. usage (EXIT_FAILURE);
  255. break;
  256. }
  257. if (argc - optind > 1)
  258. {
  259. error (0, 0, _("extra operand %s"), quote (argv[optind]));
  260. usage (EXIT_FAILURE);
  261. }
  262. if (optind < argc)
  263. infile = argv[optind];
  264. else
  265. infile = "-";
  266. if (STREQ (infile, "-"))
  267. {
  268. xset_binary_mode (STDIN_FILENO, O_BINARY);
  269. input_fh = stdin;
  270. }
  271. else
  272. {
  273. input_fh = fopen (infile, "rb");
  274. if (input_fh == NULL)
  275. die (EXIT_FAILURE, errno, "%s", quotef (infile));
  276. }
  277. fadvise (input_fh, FADVISE_SEQUENTIAL);
  278. if (decode)
  279. do_decode (input_fh, stdout, ignore_garbage);
  280. else
  281. do_encode (input_fh, stdout, wrap_column);
  282. if (fclose (input_fh) == EOF)
  283. {
  284. if (STREQ (infile, "-"))
  285. die (EXIT_FAILURE, errno, _("closing standard input"));
  286. else
  287. die (EXIT_FAILURE, errno, "%s", quotef (infile));
  288. }
  289. return EXIT_SUCCESS;
  290. }