8 // ----------------------------------------------------------------------------
10 // code from: http://www.geekhideout.com/urlcode.shtml
12 /* Converts a hex character to its integer value */
13 char from_hex(char ch) {
14 return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10);
17 /* Converts an integer value to its hex character*/
18 char to_hex(char code) {
19 static char hex[] = "0123456789abcdef";
20 return hex[code & 15];
23 /* Returns a url-encoded version of str */
24 /* IMPORTANT: be sure to free() the returned string after use */
25 char *url_encode(char *str) {
27 *buf = malloc(strlen(str) * 3 + 1),
31 if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
34 else if (*pstr == ' ')
38 *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
48 /* Returns a url-decoded version of str */
49 /* IMPORTANT: be sure to free() the returned string after use */
50 char *url_decode(char *str) {
52 *buf = malloc(strlen(str) + 1),
55 if(!buf) fatal("Cannot allocate memory.");
59 if (pstr[1] && pstr[2]) {
60 *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
64 else if (*pstr == '+')