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