summaryrefslogtreecommitdiffstats
path: root/src/url.c
blob: df931387361d0288b1c70500e0c37b24b3c96f34 (plain) (blame)
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
int urlencode (char * o, const char * i /* o must have at least strlen(i)*3+1 bytes of memory allocated */) {
	size_t written = 0; /* o CANNOT be equal to i, unlike in urldecode */
	for (; *i; i++) {
		if (isalnum(*i) || *i == '.' || *i == '_' || *i == '-' || *i == '~') {
			o[written++] = *i;
		} else {
			sprintf(o+written, "%%%02X", *i);
			written += 3;
		}
	}
	o[written++] = '\0';
	return 1;
}
int urldecode (char * o, const char * i /* o must have at least strlen(i)+1 bytes memory allocated */) {
	size_t written = 0; /* o can be equal to i for decoding in-place */
	char buf[] = "00";
	for (; *i; i++) {
		if (*i == '%') {
			buf[0] = *++i;
			buf[1] = *++i;
			if (!buf[0] || !buf[1]) { /* malformed */
				o[written++] = '\0';
				return 0;
			}
			o[written++] = strtol(buf, NULL, 16);
		} else {
			o[written++] = *i;
		}
	}
	o[written++] = '\0';
	return 1;
}