9 // ----------------------------------------------------------------------------
10 // URL encode / decode
11 // code from: http://www.geekhideout.com/urlcode.shtml
13 /* Converts a hex character to its integer value */
14 char from_hex(char ch) {
15 return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10);
18 /* Converts an integer value to its hex character*/
19 char to_hex(char code) {
20 static char hex[] = "0123456789abcdef";
21 return hex[code & 15];
24 /* Returns a url-encoded version of str */
25 /* IMPORTANT: be sure to free() the returned string after use */
26 char *url_encode(char *str) {
28 *buf = malloc(strlen(str) * 3 + 1),
32 if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
35 else if (*pstr == ' ')
39 *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
49 /* Returns a url-decoded version of str */
50 /* IMPORTANT: be sure to free() the returned string after use */
51 char *url_decode(char *str) {
53 *buf = malloc(strlen(str) + 1),
56 if(!buf) fatal("Cannot allocate memory.");
60 if (pstr[1] && pstr[2]) {
61 *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
65 else if (*pstr == '+')