1/* uudecode.c - uudecode / base64 decode 2 * 3 * Copyright 2013 Erich Plondke <toybox@erich.wreck.org> 4 * 5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/uudecode.html 6 7USE_UUDECODE(NEWTOY(uudecode, ">1o:", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_UMASK)) 8 9config UUDECODE 10 bool "uudecode" 11 default y 12 help 13 usage: uudecode [-o OUTFILE] [INFILE] 14 15 Decode file from stdin (or INFILE). 16 17 -o write to OUTFILE instead of filename in header 18*/ 19 20#define FOR_uudecode 21#include "toys.h" 22 23GLOBALS( 24 char *o; 25) 26 27void uudecode_main(void) 28{ 29 int ifd = 0, ofd, idx = 0, m = m; 30 char *line = 0, mode[16], 31 *class[] = {"begin%*[ ]%15s%*[ ]%n", "begin-base64%*[ ]%15s%*[ ]%n"}; 32 33 if (toys.optc) ifd = xopenro(*toys.optargs); 34 35 while (!idx) { 36 free(line); 37 if (!(line = get_line(ifd))) error_exit("bad EOF"); 38 for (m=0; m < 2; m++) { 39 sscanf(line, class[m], mode, &idx); 40 if (idx) break; 41 } 42 } 43 44 ofd = xcreate(TT.o ? TT.o : line+idx, O_WRONLY|O_CREAT|O_TRUNC, 45 string_to_mode(mode, 0777^toys.old_umask)); 46 47 for(;;) { 48 char *in, *out; 49 int olen; 50 51 free(line); 52 if (m == 2 || !(line = get_line(ifd))) break; 53 if (!strcmp(line, m ? "====" : "end")) { 54 m = 2; 55 continue; 56 } 57 58 olen = 0; 59 in = out = line; 60 if (!m) olen = (*(in++) - 32) & 0x3f; 61 62 for (;;) { 63 int i = 0, x = 0, len = 4; 64 char c = 0; 65 66 if (!m) { 67 if (olen < 1) break; 68 if (olen < 3) len = olen + 1; 69 } 70 71 while (i < len) { 72 if (!(c = *(in++))) goto line_done; 73 74 if (m) { 75 if (c == '=') { 76 len--; 77 continue; 78 } else if (len != 4) break; 79 80 if (c >= 'A' && c <= 'Z') c -= 'A'; 81 else if (c >= 'a' && c <= 'z') c += 26 - 'a'; 82 else if (c >= '0' && c <= '9') c += 52 - '0'; 83 else if (c == '+') c = 62; 84 else if (c == '/') c = 63; 85 else continue; 86 } else c = (c - 32) & 0x3f; 87 88 x |= c << (6*(3-i)); 89 90 if (i && i < len) { 91 *(out++) = (x>>(8*(3-i))) & 0xff; 92 olen--; 93 } 94 i++; 95 } 96 97 if (i && i!=len) error_exit("bad %s", line); 98 } 99line_done: 100 xwrite(ofd, line, out-line); 101 } 102 103 if (CFG_TOYBOX_FREE) { 104 if (ifd) close(ifd); 105 close(ofd); 106 } 107} 108