Thu, 27 Jan 2022 15:50:42 +0100
add util_html_escape implementation from Open Web Server
src/server/util/util.c | file | annotate | diff | comparison | revisions |
--- a/src/server/util/util.c Thu Jan 27 15:47:18 2022 +0100 +++ b/src/server/util/util.c Thu Jan 27 15:50:42 2022 +0100 @@ -1033,3 +1033,97 @@ return pos; } + + +/* ------------------------- util_html_escape -------------------------- */ + +NSAPI_PUBLIC char *util_html_escape(const char *s) +{ + const char *in; + + int len = 0; + for (in = s; *in; in++) { + switch (*in) { + case '<': + len += 4; // < + break; + case '>': + len += 4; // > + break; + case '&': + len += 5; // & + break; + case '"': + len += 6; // " + break; + case '\'': + len += 6; // ' + break; + case '+': + len += 5; // + + break; + default: + len++; + break; + } + } + + char *ns = (char *) MALLOC(len + 1); + if (!ns) + return ns; + + char *out = ns; + for (in = s; *in; in++) { + switch (*in) { + case '<': + *out++ = '&'; + *out++ = 'l'; + *out++ = 't'; + *out++ = ';'; + break; + case '>': + *out++ = '&'; + *out++ = 'g'; + *out++ = 't'; + *out++ = ';'; + break; + case '&': + *out++ = '&'; + *out++ = 'a'; + *out++ = 'm'; + *out++ = 'p'; + *out++ = ';'; + break; + case '"': + *out++ = '&'; + *out++ = 'q'; + *out++ = 'u'; + *out++ = 'o'; + *out++ = 't'; + *out++ = ';'; + break; + case '\'': + *out++ = '&'; + *out++ = 'a'; + *out++ = 'p'; + *out++ = 'o'; + *out++ = 's'; + *out++ = ';'; + break; + case '+': + *out++ = '&'; + *out++ = '#'; + *out++ = '4'; + *out++ = '3'; + *out++ = ';'; + break; + default: + *out++ = *in; + break; + } + } + *out = '\0'; + + return ns; +} +