xref: /aosp_15_r20/external/toybox/toys/posix/uuencode.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* uuencode.c - uuencode / base64 encode
2  *
3  * Copyright 2013 Erich Plondke <[email protected]>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/uuencode.html
6 
7 USE_UUENCODE(NEWTOY(uuencode, "<1>2m", TOYFLAG_USR|TOYFLAG_BIN))
8 
9 config UUENCODE
10   bool "uuencode"
11   default y
12   help
13     usage: uuencode [-m] [INFILE] ENCODE_FILENAME
14 
15     Uuencode stdin (or INFILE) to stdout, with ENCODE_FILENAME in the output.
16 
17     -m	Base64
18 */
19 
20 #define FOR_uuencode
21 #include "toys.h"
22 
uuencode_main(void)23 void uuencode_main(void)
24 {
25   char *name = toys.optargs[toys.optc-1], buf[(76/4)*3];
26 
27   int i, fd = 0;
28 
29   if (toys.optc > 1) fd = xopenro(toys.optargs[0]);
30 
31   base64_init(toybuf);
32 
33   xprintf("begin%s 744 %s\n", FLAG(m) ? "-base64" : "", name);
34   for (;;) {
35     char *in;
36 
37     if (!(i = xread(fd, buf, FLAG(m) ? sizeof(buf) : 45))) break;
38 
39     if (!FLAG(m)) xputc(i+32);
40     in = buf;
41 
42     for (in = buf; in-buf < i; ) {
43       int j, x, bytes = i - (in-buf);
44 
45       if (bytes > 3) bytes = 3;
46 
47       for (j = x = 0; j<4; j++) {
48         int out;
49 
50         if (j < bytes) x |= (*(in++) & 0x0ff) << (8*(2-j));
51         out = (x>>((3-j)*6)) & 0x3f;
52         xputc(FLAG(m) ? (j > bytes ? '=' : toybuf[out])
53           : (out ? out + 0x20 : 0x60));
54       }
55     }
56     xputc('\n');
57   }
58   xputs(FLAG(m) ? "====" : "end");
59 }
60