-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmb64.c
87 lines (77 loc) · 2.26 KB
/
mb64.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "mbase64.h"
#include "mdebug.h"
#define BUFSIZE 1024
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: mb64 [-d] <input|->\n");
fprintf(stderr, " [-d] decode (encode is default)\n");
exit(1);
}
int encode = 1;
int test = 0;
char *input = NULL;
FILE *input_file = NULL;
unsigned char buffer[BUFSIZE];
for (int i = 0; i < argc; ++i) {
if (strcmp(argv[i], "-d") == 0) {
encode = 0;
} else if (strcmp(argv[i], "-t") == 0) {
test = 1;
} else {
input = argv[i];
}
}
// If an input string is not provided, or it is -, then read
// input from stdin. Otherwise, read from the file path referenced.
if ((input == NULL) || ((input[0] == '-') && (input[1] == '\0'))) {
input_file = stdin;
} else {
input_file = fopen(input, "r");
if (input_file == NULL) {
perror("input file");
exit(1);
}
}
int fd = fileno(input_file);
int done = 0;
mdbgf("encode is %d\n", encode);
mdbgf("test is %d\n", test);
ssize_t input_size = 0;
while (! done) {
ssize_t bytes = read(fd, buffer, BUFSIZE);
mdbgf("read %d bytes from input file\n", bytes);
input_size += bytes;
switch (bytes) {
case 0:
done = 1;
break;
case -1:
done = 1;
perror("read error");
break;
default:
break;
}
}
if (encode) {
mdbgf("encoding '%s'\n", buffer);
char *b64string = mbase64_encode(buffer, input_size);
printf("%s\n", b64string);
// If test is set, decode again for comparison.
if (test) {
mdbgf("test set - decoding '%s'\n", b64string);
size_t outlen = 0;
printf("%s\n", mbase64_decode(b64string, &outlen));
printf("input size: %ld\n", input_size);
printf("output size: %ld\n", outlen);
if (input_size != outlen) {
fprintf(stderr, "ERROR: sizes do not match\n");
}
}
}
fflush(stdout);
return 0;
}