-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlenc.c
108 lines (88 loc) · 2.01 KB
/
urlenc.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include "util.h"
#include "urldec.h"
#include "doc.h"
#define NAME "urlenc"
void urlenc(char *s, bool plus, bool ignore_ascii)
{
size_t size;
size_t i;
size = strnlen(s, BUFFER_SIZE-1);
for(i = 0; i < size; i++) {
if (plus && (char)s[i] == 0x20) {
printf("+");
continue;
}
if (ignore_ascii && isalnum(s[i])) {
printf("%c", s[i]);
continue;
}
/* do full conversion */
printf("%%%02hhx", (char)s[i]);
}
}
int main(int argc, char **argv)
{
bool decode = false; /* decode mode */
bool plus = false; /* use + instead of %20 */
bool ignore_ascii = false; /* example: hello%20world */
bool in_file = false;
char *filename = NULL; /* read input file */
/* parse arguments */
if (argc > 1) {
size_t optind;
for (optind = 1; optind < argc && argv[optind][0] == '-'; optind++) {
switch (argv[optind][1]) {
case 's': plus = true; break;
case 'a': ignore_ascii = true; break;
case 'd': decode = true; break;
case 'i':
in_file = true;
if (optind + 1 > argc-1) {
fprintf(stderr, "no file input\n");
break;
}
if (check_fname_len(argv[optind+1]) == 0)
filename = argv[optind+1];
break;
case 'v':
version(NAME);
break;
case 'h':
help_enc(NAME);
break;
default:
fprintf(stderr, "%s: Unrecognised option '%s'\n"
"try '%s -h' for more information\n",
NAME, argv[optind], NAME);
return 1;
break;
}
}
}
char *buffer;
int err = 0;
if (in_file) {
buffer = (char *)malloc(sizeof(char) * BUFFER_SIZE);
err = prepare_read(&buffer, BUFFER_SIZE, filename);
handle_readall_errors(err);
if (err != 0)
return 1;
} else
buffer = stdin_recv(BUFFER_SIZE);
if(buffer == NULL){
free(buffer);
return 1;
}
if (!decode)
urlenc(buffer, plus, ignore_ascii);
else
urldec(buffer);
free(buffer);
if (!in_file)
printf("\n");
return 0;
}