diff options
author | Federico Ceratto <federico.ceratto@gmail.com> | 2016-03-30 21:40:42 +0000 |
---|---|---|
committer | Federico Ceratto <federico.ceratto@gmail.com> | 2016-03-30 21:40:42 +0000 |
commit | 9ce153ce7167c11adba8ac225edc7a707e97c6eb (patch) | |
tree | 9f6e849cce2dcc7e5b4e9e6252c843dc2d0787a2 /src/url.c | |
download | netdata-9ce153ce7167c11adba8ac225edc7a707e97c6eb.tar.xz netdata-9ce153ce7167c11adba8ac225edc7a707e97c6eb.zip |
Imported Upstream version 1.0.0upstream/1.0.0
Diffstat (limited to 'src/url.c')
-rwxr-xr-x | src/url.c | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/src/url.c b/src/url.c new file mode 100755 index 00000000..c4933b20 --- /dev/null +++ b/src/url.c @@ -0,0 +1,81 @@ +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif +#include <stdlib.h> +#include <string.h> +#include <ctype.h> + +#include "common.h" +#include "log.h" +#include "url.h" + +// ---------------------------------------------------------------------------- +// URL encode / decode +// code from: http://www.geekhideout.com/urlcode.shtml + +/* Converts a hex character to its integer value */ +char from_hex(char ch) { + return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10); +} + +/* Converts an integer value to its hex character*/ +char to_hex(char code) { + static char hex[] = "0123456789abcdef"; + return hex[code & 15]; +} + +/* Returns a url-encoded version of str */ +/* IMPORTANT: be sure to free() the returned string after use */ +char *url_encode(char *str) { + char *pstr = str, + *buf = malloc(strlen(str) * 3 + 1), + *pbuf = buf; + + while (*pstr) { + if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') + *pbuf++ = *pstr; + + else if (*pstr == ' ') + *pbuf++ = '+'; + + else + *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15); + + pstr++; + } + + *pbuf = '\0'; + + return buf; +} + +/* Returns a url-decoded version of str */ +/* IMPORTANT: be sure to free() the returned string after use */ +char *url_decode(char *str) { + char *pstr = str, + *buf = malloc(strlen(str) + 1), + *pbuf = buf; + + if(!buf) fatal("Cannot allocate memory."); + + while (*pstr) { + if (*pstr == '%') { + if (pstr[1] && pstr[2]) { + *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]); + pstr += 2; + } + } + else if (*pstr == '+') + *pbuf++ = ' '; + + else + *pbuf++ = *pstr; + + pstr++; + } + + *pbuf = '\0'; + + return buf; +} + |