Debian Codegraph @

madrisan-nagios-plugins-linux/nagios-plugins-linux/lib/url_encode.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 /*
3 * License: Public Domain
4 * Copyright (c) Fred Bulback
5 * Source Code: http://www.geekhideout.com/urlcode.shtml
6 *
7 * A library for encoding URLs.
8 *
9 * To the extent possible under law, Fred Bulback has waived all copyright
10 * and related or neighboring rights to URL Encoding/Decoding in C.
11 * This work is published from: United States. */
12
13 #include <stdio.h>
14 #include <ctype.h>
15 #include <stdlib.h>
16 #include <string.h>
17
18 /* Converts a hex character to its integer value */
19 char
20 from_hex (char ch)
21 {
22 return isdigit (ch) ? ch - '0' : tolower (ch) - 'a' + 10;
23 }
24
25 /* Converts an integer value to its hex character */
26 char
27 to_hex (char code)
28 {
29 const char hex[] = "0123456789abcdef";
30 return hex[code & 15];
31 }
32
33 /* Returns a url-encoded version of str */
34 /* IMPORTANT: be sure to free() the returned string after use */
35 char *
36 url_encode (char *str)
37 {
38 char *pstr = str, *buf = malloc (strlen (str) * 3 + 1), *pbuf = buf;
39 while (*pstr)
40 {
41 if (isalnum (*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.'
42 || *pstr == '~')
43 *pbuf++ = *pstr;
44 else if (*pstr == ' ')
45 *pbuf++ = '+';
46 else
47 {
48 *pbuf++ = '%';
49 *pbuf++ = to_hex (*pstr >> 4);
50 *pbuf++ = to_hex (*pstr & 15);
51 }
52 pstr++;
53 }
54 *pbuf = '\0';
55 return buf;
56 }