]> arthur.barton.de Git - netdata.git/blob - src/url.c
splitted netdata to multiple source files
[netdata.git] / src / url.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include <ctype.h>
4
5 #include "log.h"
6 #include "url.h"
7
8 // ----------------------------------------------------------------------------
9 // URL encode / decode
10 // code from: http://www.geekhideout.com/urlcode.shtml
11
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);
15 }
16
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];
21 }
22
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) {
26         char *pstr = str,
27                 *buf = malloc(strlen(str) * 3 + 1),
28                 *pbuf = buf;
29
30         while (*pstr) {
31                 if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
32                         *pbuf++ = *pstr;
33
34                 else if (*pstr == ' ')
35                         *pbuf++ = '+';
36
37                 else
38                         *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
39
40                 pstr++;
41         }
42
43         *pbuf = '\0';
44
45         return buf;
46 }
47
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) {
51         char *pstr = str,
52                 *buf = malloc(strlen(str) + 1),
53                 *pbuf = buf;
54
55         if(!buf) fatal("Cannot allocate memory.");
56
57         while (*pstr) {
58                 if (*pstr == '%') {
59                         if (pstr[1] && pstr[2]) {
60                                 *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
61                                 pstr += 2;
62                         }
63                 }
64                 else if (*pstr == '+')
65                         *pbuf++ = ' ';
66
67                 else
68                         *pbuf++ = *pstr;
69                 
70                 pstr++;
71         }
72         
73         *pbuf = '\0';
74         
75         return buf;
76 }
77