Module: kamailio
Branch: master
Commit: 0973bee70e2a7f6ea274c357083fb67b6b2e27ad
URL:
https://github.com/kamailio/kamailio/commit/0973bee70e2a7f6ea274c357083fb67…
Author: Armen Babikyan <armen(a)firespotter.com>
Committer: Armen Babikyan <armen(a)firespotter.com>
Date: 2020-03-27T14:32:29-07:00
core: strutils - add urlencode and urldecode functions
- moved from modules/pv/pv_trans.c and exported, so they can be used in other modules
- genericized fn names
---
Modified: src/core/strutils.c
Modified: src/core/strutils.h
---
Diff:
https://github.com/kamailio/kamailio/commit/0973bee70e2a7f6ea274c357083fb67…
Patch:
https://github.com/kamailio/kamailio/commit/0973bee70e2a7f6ea274c357083fb67…
---
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