2 * UCW Library -- Line utility for encoding and decoding base64 & base224
4 * (c) 2008, Michal Vaner <vorner@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
15 #include "ucw/base64.h"
16 #include "ucw/base224.h"
17 #include "ucw/fastbuf.h"
18 #include "ucw/getopt.h"
20 static struct option opts[] = {
21 { "encode64", 0, 0, 'e' },
22 { "decode64", 0, 0, 'd' },
23 { "encode224", 0, 0, 'E' },
24 { "decode224", 0, 0, 'D' },
25 { "prefix", 1, 0, 'p' },
26 { "blocks", 1, 0, 'b' },
31 uns (*function)(byte *, const byte *, uns);
32 uns in_block, out_block, num_blocks;
37 BASE64_IN_CHUNK, BASE64_OUT_CHUNK, 20,
42 BASE64_OUT_CHUNK, BASE64_IN_CHUNK, 20,
47 BASE224_IN_CHUNK, BASE64_OUT_CHUNK, 6,
52 BASE224_OUT_CHUNK, BASE224_IN_CHUNK, 6,
57 int main(int argc, char **argv)
64 while ((opt = getopt_long(argc, argv, "edEDp:b:", opts, NULL)) >= 0)
67 case 'e': mode = 0; break;
68 case 'd': mode = 1; break;
69 case 'E': mode = 2; break;
70 case 'D': mode = 3; break;
71 case 'p': prefix = optarg; break;
75 blocks = strtol(optarg, &end, 0);
76 if ((blocks > 0) && !*end)
85 fprintf(stderr, "basecode mode [--prefix=prefix] [--blocks=number_of_blocks]\nMode is one of:\n\t--encode64 (-e)\n\t--decode64 (-d)\n\t--encode224 (-E)\n\t--decode224 (-D)\n");
89 blocks = actions[mode].num_blocks;
92 struct fastbuf *in = bfdopen_shared(0, 4096);
93 struct fastbuf *out = bfdopen_shared(1, 4096);
94 uns offset = (!actions[mode].add_prefix && prefix) ? strlen(prefix) : 0;
95 uns read_size = actions[mode].in_block * blocks + offset + !!offset;
96 uns write_size = actions[mode].out_block * blocks;
97 byte in_buff[read_size], out_buff[write_size];
101 while (isize = bread(in, in_buff, read_size))
105 if (actions[mode].add_prefix)
108 if ((isize < offset) || (in_buff[isize-1] != '\n')
109 || (strncmp(prefix, in_buff, offset)))
110 die("Invalid line syntax");
112 uns osize = actions[mode].function(out_buff, in_buff + offset, isize - offset - !!offset);
113 bwrite(out, out_buff, osize);
114 if (actions[mode].add_prefix && prefix)