12 // ----------------------------------------------------------------------------
13 // URL encode / decode
14 // code from: http://www.geekhideout.com/urlcode.shtml
16 /* Converts a hex character to its integer value */
17 char from_hex(char ch) {
18 return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10);
21 /* Converts an integer value to its hex character*/
22 char to_hex(char code) {
23 static char hex[] = "0123456789abcdef";
24 return hex[code & 15];
27 /* Returns a url-encoded version of str */
28 /* IMPORTANT: be sure to free() the returned string after use */
29 char *url_encode(char *str) {
31 *buf = malloc(strlen(str) * 3 + 1),
35 fatal("Cannot allocate memory.");
38 if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
41 else if (*pstr == ' ')
45 *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
55 /* Returns a url-decoded version of str */
56 /* IMPORTANT: be sure to free() the returned string after use */
57 char *url_decode(char *str) {
59 *buf = malloc(strlen(str) + 1),
63 fatal("Cannot allocate memory.");
67 if (pstr[1] && pstr[2]) {
68 *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
72 else if (*pstr == '+')