]> arthur.barton.de Git - netdata.git/blob - src/url.c
build: migrate to autotools
[netdata.git] / src / url.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <stdlib.h>
5 #include <string.h>
6 #include <ctype.h>
7
8 #include "common.h"
9 #include "log.h"
10 #include "url.h"
11
12 // ----------------------------------------------------------------------------
13 // URL encode / decode
14 // code from: http://www.geekhideout.com/urlcode.shtml
15
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);
19 }
20
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];
25 }
26
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) {
30         char *pstr = str,
31                 *buf = malloc(strlen(str) * 3 + 1),
32                 *pbuf = buf;
33
34         while (*pstr) {
35                 if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
36                         *pbuf++ = *pstr;
37
38                 else if (*pstr == ' ')
39                         *pbuf++ = '+';
40
41                 else
42                         *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
43
44                 pstr++;
45         }
46
47         *pbuf = '\0';
48
49         return buf;
50 }
51
52 /* Returns a url-decoded version of str */
53 /* IMPORTANT: be sure to free() the returned string after use */
54 char *url_decode(char *str) {
55         char *pstr = str,
56                 *buf = malloc(strlen(str) + 1),
57                 *pbuf = buf;
58
59         if(!buf) fatal("Cannot allocate memory.");
60
61         while (*pstr) {
62                 if (*pstr == '%') {
63                         if (pstr[1] && pstr[2]) {
64                                 *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
65                                 pstr += 2;
66                         }
67                 }
68                 else if (*pstr == '+')
69                         *pbuf++ = ' ';
70
71                 else
72                         *pbuf++ = *pstr;
73                 
74                 pstr++;
75         }
76         
77         *pbuf = '\0';
78         
79         return buf;
80 }
81