diff --git a/lib/libwebsockets.c b/lib/libwebsockets.c index 51da8b49..cac78db5 100755 --- a/lib/libwebsockets.c +++ b/lib/libwebsockets.c @@ -1799,6 +1799,42 @@ lws_sql_purify(char *escaped, const char *string, int len) return escaped; } +/** + * lws_json_purify() - like strncpy but with escaping for json chars + * + * @escaped: output buffer + * @string: input buffer ('/0' terminated) + * @len: output buffer max length + * + * Because escaping expands the output string, it's not + * possible to do it in-place, ie, with escaped == string + */ + +LWS_VISIBLE LWS_EXTERN const char * +lws_json_purify(char *escaped, const char *string, int len) +{ + const char *p = string; + char *q = escaped; + + while (*p && len-- > 6) { + if (*p == '\"' || *p == '\\' || *p < 0x20) { + *q++ = '\\'; + *q++ = 'u'; + *q++ = '0'; + *q++ = '0'; + *q++ = hex[((*p) >> 4) & 15]; + *q++ = hex[(*p) & 15]; + len -= 5; + p++; + } else + *q++ = *p++; + } + *q = '\0'; + + return escaped; +} + + /** * lws_urlencode() - like strncpy but with urlencoding * diff --git a/lib/libwebsockets.h b/lib/libwebsockets.h index 96829a02..b6ec9bbc 100644 --- a/lib/libwebsockets.h +++ b/lib/libwebsockets.h @@ -1810,7 +1810,8 @@ lws_urlencode(char *escaped, const char *string, int len); LWS_VISIBLE LWS_EXTERN const char * lws_sql_purify(char *escaped, const char *string, int len); - +LWS_VISIBLE LWS_EXTERN const char * +lws_json_purify(char *escaped, const char *string, int len); /* * URLDECODE 1 / 2