Răsfoiți Sursa

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
Armen Babikyan 5 ani în urmă
părinte
comite
0973bee70e
2 a modificat fișierele cu 77 adăugiri și 0 ștergeri
  1. 73 0
      src/core/strutils.c
  2. 4 0
      src/core/strutils.h

+ 73 - 0
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);
 	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;
+}

+ 4 - 0
src/core/strutils.h

@@ -61,4 +61,8 @@ int escape_param(str *sin, str *sout);
 int unescape_param(str *sin, str *sout);
 int unescape_param(str *sin, str *sout);
 int escape_csv(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
 #endif