summaryrefslogblamecommitdiffstats
path: root/src/url.c
blob: 13081a00256d3598ded08203850b0633b58ca855 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
                                                                                                             

                          
                                                                             







                                                                                      
                            

                 
                                                                                                        

                          
                                                                           






                                                                 
                                          





                                                             
                            

                 
int urlencode (char * o, const char * i /* o must have at least strlen(i)*3+1 bytes of memory allocated */) {
	if (!o || !i)
		return -2;
	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 */) {
	if (!o || !i)
		return -2;
	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 -1;
			}
			o[written++] = strtol(buf, NULL, 16);
		} else {
			o[written++] = *i;
		}
	}
	o[written++] = '\0';
	return 1;
}