uuencode.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #include "libbb.h"
  11. enum {
  12. SRC_BUF_SIZE = 15*3, /* This *MUST* be a multiple of 3 */
  13. DST_BUF_SIZE = 4 * ((SRC_BUF_SIZE + 2) / 3),
  14. };
  15. int uuencode_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  16. int uuencode_main(int argc UNUSED_PARAM, char **argv)
  17. {
  18. struct stat stat_buf;
  19. int src_fd = STDIN_FILENO;
  20. const char *tbl;
  21. mode_t mode;
  22. char src_buf[SRC_BUF_SIZE];
  23. char dst_buf[DST_BUF_SIZE + 1];
  24. tbl = bb_uuenc_tbl_std;
  25. mode = 0666 & ~umask(0666);
  26. opt_complementary = "-1:?2"; /* must have 1 or 2 args */
  27. if (getopt32(argv, "m")) {
  28. tbl = bb_uuenc_tbl_base64;
  29. }
  30. argv += optind;
  31. if (argv[1]) {
  32. src_fd = xopen(argv[0], O_RDONLY);
  33. fstat(src_fd, &stat_buf);
  34. mode = stat_buf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
  35. argv++;
  36. }
  37. printf("begin%s %o %s", tbl == bb_uuenc_tbl_std ? "" : "-base64", mode, *argv);
  38. while (1) {
  39. size_t size = full_read(src_fd, src_buf, SRC_BUF_SIZE);
  40. if (!size)
  41. break;
  42. if ((ssize_t)size < 0)
  43. bb_perror_msg_and_die(bb_msg_read_error);
  44. /* Encode the buffer we just read in */
  45. bb_uuencode(dst_buf, src_buf, size, tbl);
  46. bb_putchar('\n');
  47. if (tbl == bb_uuenc_tbl_std) {
  48. bb_putchar(tbl[size]);
  49. }
  50. fflush(stdout);
  51. xwrite(STDOUT_FILENO, dst_buf, 4 * ((size + 2) / 3));
  52. }
  53. printf(tbl == bb_uuenc_tbl_std ? "\n`\nend\n" : "\n====\n");
  54. fflush_stdout_and_exit(EXIT_SUCCESS);
  55. }