uuencode.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Copyright (C) 2000 by Glenn McGrath
  4. *
  5. * based on the function base64_encode from http.c in wget v1.6
  6. * Copyright (C) 1995, 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. //usage:#define uuencode_trivial_usage
  11. //usage: "[-m] [FILE] STORED_FILENAME"
  12. //usage:#define uuencode_full_usage "\n\n"
  13. //usage: "Uuencode FILE (or stdin) to stdout\n"
  14. //usage: "\n -m Use base64 encoding per RFC1521"
  15. //usage:
  16. //usage:#define uuencode_example_usage
  17. //usage: "$ uuencode busybox busybox\n"
  18. //usage: "begin 755 busybox\n"
  19. //usage: "<encoded file snipped>\n"
  20. //usage: "$ uudecode busybox busybox > busybox.uu\n"
  21. //usage: "$\n"
  22. #include "libbb.h"
  23. enum {
  24. SRC_BUF_SIZE = 15*3, /* This *MUST* be a multiple of 3 */
  25. DST_BUF_SIZE = 4 * ((SRC_BUF_SIZE + 2) / 3),
  26. };
  27. int uuencode_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  28. int uuencode_main(int argc UNUSED_PARAM, char **argv)
  29. {
  30. struct stat stat_buf;
  31. int src_fd = STDIN_FILENO;
  32. const char *tbl;
  33. mode_t mode;
  34. char src_buf[SRC_BUF_SIZE];
  35. char dst_buf[DST_BUF_SIZE + 1];
  36. tbl = bb_uuenc_tbl_std;
  37. mode = 0666 & ~umask(0666);
  38. opt_complementary = "-1:?2"; /* must have 1 or 2 args */
  39. if (getopt32(argv, "m")) {
  40. tbl = bb_uuenc_tbl_base64;
  41. }
  42. argv += optind;
  43. if (argv[1]) {
  44. src_fd = xopen(argv[0], O_RDONLY);
  45. fstat(src_fd, &stat_buf);
  46. mode = stat_buf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
  47. argv++;
  48. }
  49. printf("begin%s %o %s", tbl == bb_uuenc_tbl_std ? "" : "-base64", mode, *argv);
  50. while (1) {
  51. size_t size = full_read(src_fd, src_buf, SRC_BUF_SIZE);
  52. if (!size)
  53. break;
  54. if ((ssize_t)size < 0)
  55. bb_perror_msg_and_die(bb_msg_read_error);
  56. /* Encode the buffer we just read in */
  57. bb_uuencode(dst_buf, src_buf, size, tbl);
  58. bb_putchar('\n');
  59. if (tbl == bb_uuenc_tbl_std) {
  60. bb_putchar(tbl[size]);
  61. }
  62. fflush(stdout);
  63. xwrite(STDOUT_FILENO, dst_buf, 4 * ((size + 2) / 3));
  64. }
  65. printf(tbl == bb_uuenc_tbl_std ? "\n`\nend\n" : "\n====\n");
  66. fflush_stdout_and_exit(EXIT_SUCCESS);
  67. }