diff --git a/src/core/strutils.c b/src/core/strutils.c index b06fa44175b..7df31727cbc 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 37152dd18d1..8b20f72e445 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