Module: kamailio
Branch: master
Commit: c5bac15472ad7db452e35f000a3236a839f14cf8
URL:
https://github.com/kamailio/kamailio/commit/c5bac15472ad7db452e35f000a3236a…
Author: Daniel-Constantin Mierla <miconda(a)gmail.com>
Committer: GitHub <noreply(a)github.com>
Date: 2020-03-28T08:30:16+01:00
Merge pull request #2264 from armenb/core_strutils_urlencode_urldecode
core: strutils - add urlencode and urldecode functions
---
Modified: src/core/strutils.c
Modified: src/core/strutils.h
---
Diff:
https://github.com/kamailio/kamailio/commit/c5bac15472ad7db452e35f000a3236a…
Patch:
https://github.com/kamailio/kamailio/commit/c5bac15472ad7db452e35f000a3236a…
---
diff --git a/src/core/strutils.c b/src/core/strutils.c
index b06fa44175..7df31727cb 100644
--- a/src/core/strutils.c
+++ b/src/core/strutils.c
@@ -701,3 +701,76 @@ int reg_replace(char *pattern, char *replacement, char *string, str
*result)
return replace(&pmatch[0], string, replacement, result);
}
+
+/* Converts a hex character to its integer value */
+char hex_to_char(char hex_code)
+{
+ return isdigit(hex_code) ? hex_code - '0' : tolower(hex_code) - 'a' +
10;
+}
+
+/* Converts an integer value to its hex character */
+char char_to_hex(char char_code)
+{
+ static char hex[] = "0123456789abcdef";
+ return hex[char_code & 15];
+}
+
+/*! \brief
+ * URL Encodes a string
+ */
+int urlencode(str *sin, str *sout)
+{
+ char *at, *p;
+
+ if (sin==NULL || sout==NULL || sin->s==NULL || sout->s==NULL ||
+ sin->len<0 || sout->len < 3*sin->len+1)
+ return -1;
+
+ at = sout->s;
+ p = sin->s;
+
+ while (p < sin->s+sin->len) {
+ if (isalnum(*p) || *p == '-' || *p == '_' || *p == '.' || *p ==
'~')
+ *at++ = *p;
+ else
+ *at++ = '%', *at++ = char_to_hex(*p >> 4), *at++ = char_to_hex(*p &
15);
+ p++;
+ }
+
+ *at = 0;
+ sout->len = at - sout->s;
+ LM_DBG("urlencoded string is <%s>\n", sout->s);
+
+ return 0;
+}
+
+/*! \brief
+ * URL Decodes a string
+ */
+int urldecode(str *sin, str *sout)
+{
+ char *at, *p;
+
+ at = sout->s;
+ p = sin->s;
+
+ while (p < sin->s+sin->len) {
+ if (*p == '%') {
+ if (p[1] && p[2]) {
+ *at++ = hex_to_char(p[1]) << 4 | hex_to_char(p[2]);
+ p += 2;
+ }
+ } else if (*p == '+') {
+ *at++ = ' ';
+ } else {
+ *at++ = *p;
+ }
+ p++;
+ }
+
+ *at = 0;
+ sout->len = at - sout->s;
+
+ LM_DBG("urldecoded string is <%s>\n", sout->s);
+ return 0;
+}
diff --git a/src/core/strutils.h b/src/core/strutils.h
index 37152dd18d..8b20f72e44 100644
--- a/src/core/strutils.h
+++ b/src/core/strutils.h
@@ -61,4 +61,8 @@ int escape_param(str *sin, str *sout);
int unescape_param(str *sin, str *sout);
int escape_csv(str *sin, str *sout);
+char hex_to_char(char hex_code);
+char char_to_hex(char char_code);
+int urlencode(str *sin, str *sout);
+int urldecode(str *sin, str *sout);
#endif