]> arthur.barton.de Git - netdata.git/blob - src/url.c
layout: remove executable from unrelated files
[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         if(!buf)
35                 fatal("Cannot allocate memory.");
36
37         while (*pstr) {
38                 if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
39                         *pbuf++ = *pstr;
40
41                 else if (*pstr == ' ')
42                         *pbuf++ = '+';
43
44                 else
45                         *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
46
47                 pstr++;
48         }
49
50         *pbuf = '\0';
51
52         return buf;
53 }
54
55 /* Returns a url-decoded version of str */
56 /* IMPORTANT: be sure to free() the returned string after use */
57 char *url_decode(char *str) {
58         char *pstr = str,
59                 *buf = malloc(strlen(str) + 1),
60                 *pbuf = buf;
61
62         if(!buf)
63                 fatal("Cannot allocate memory.");
64
65         while (*pstr) {
66                 if (*pstr == '%') {
67                         if (pstr[1] && pstr[2]) {
68                                 *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
69                                 pstr += 2;
70                         }
71                 }
72                 else if (*pstr == '+')
73                         *pbuf++ = ' ';
74
75                 else
76                         *pbuf++ = *pstr;
77
78                 pstr++;
79         }
80
81         *pbuf = '\0';
82
83         return buf;
84 }
85