]> arthur.barton.de Git - netdata.git/blob - src/url.c
Merge remote-tracking branch 'upstream/master' into health
[netdata.git] / src / url.c
1 #include "common.h"
2
3 // ----------------------------------------------------------------------------
4 // URL encode / decode
5 // code from: http://www.geekhideout.com/urlcode.shtml
6
7 /* Converts a hex character to its integer value */
8 char from_hex(char ch) {
9         return (char)(isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10);
10 }
11
12 /* Converts an integer value to its hex character*/
13 char to_hex(char code) {
14         static char hex[] = "0123456789abcdef";
15         return hex[code & 15];
16 }
17
18 /* Returns a url-encoded version of str */
19 /* IMPORTANT: be sure to free() the returned string after use */
20 char *url_encode(char *str) {
21         char *buf, *pbuf;
22
23         pbuf = buf = mallocz(strlen(str) * 3 + 1);
24
25         while (*str) {
26                 if (isalnum(*str) || *str == '-' || *str == '_' || *str == '.' || *str == '~')
27                         *pbuf++ = *str;
28
29                 else if (*str == ' ')
30                         *pbuf++ = '+';
31
32                 else
33                         *pbuf++ = '%', *pbuf++ = to_hex(*str >> 4), *pbuf++ = to_hex(*str & 15);
34
35                 str++;
36         }
37         *pbuf = '\0';
38
39         pbuf = strdupz(buf);
40         freez(buf);
41         return pbuf;
42 }
43
44 /* Returns a url-decoded version of str */
45 /* IMPORTANT: be sure to free() the returned string after use */
46 char *url_decode(char *str) {
47         size_t size = strlen(str) + 1;
48
49         char *buf = mallocz(size);
50         return url_decode_r(buf, str, size);
51 }
52
53 char *url_decode_r(char *to, char *url, size_t size) {
54         char *s = url,           // source
55                  *d = to,            // destination
56                  *e = &to[size - 1]; // destination end
57
58         while(*s && d < e) {
59                 if(unlikely(*s == '%')) {
60                         if(likely(s[1] && s[2])) {
61                                 *d++ = from_hex(s[1]) << 4 | from_hex(s[2]);
62                                 s += 2;
63                         }
64                 }
65                 else if(unlikely(*s == '+'))
66                         *d++ = ' ';
67
68                 else
69                         *d++ = *s;
70
71                 s++;
72         }
73
74         *d = '\0';
75
76         return to;
77 }