From c2e339489f16ebf0b0a2170991310f2c4d90d553 Mon Sep 17 00:00:00 2001 From: xmedia-systems Date: Tue, 12 May 2020 16:57:12 +0200 Subject: [PATCH] properly escape json strings --- trunk/src/protocol/srs_protocol_json.cpp | 27 +++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/trunk/src/protocol/srs_protocol_json.cpp b/trunk/src/protocol/srs_protocol_json.cpp index c742bb1583..53f947005c 100644 --- a/trunk/src/protocol/srs_protocol_json.cpp +++ b/trunk/src/protocol/srs_protocol_json.cpp @@ -74,6 +74,8 @@ #ifdef __cplusplus #include +#include +#include extern "C" { @@ -365,6 +367,29 @@ static unsigned char hex_value (json_char c) } } +static std::string escape_json(const std::string &s) { + std::ostringstream o; + for (std::string::const_iterator c = s.begin(); c != s.end(); c++) { + switch (*c) { + case '"': o << "\\\""; break; + case '\\': o << "\\\\"; break; + case '\b': o << "\\b"; break; + case '\f': o << "\\f"; break; + case '\n': o << "\\n"; break; + case '\r': o << "\\r"; break; + case '\t': o << "\\t"; break; + default: + if ('\x00' <= *c && *c <= '\x1f') { + o << "\\u" + << std::hex << std::setw(4) << std::setfill('0') << (int)*c; + } else { + o << *c; + } + } + } + return o.str(); +} + typedef struct { unsigned long used_memory; @@ -1576,7 +1601,7 @@ string SrsJsonAny::dumps() { switch (marker) { case SRS_JSON_String: { - return "\"" + to_str() + "\""; + return "\"" + escape_json(to_str()) + "\""; } case SRS_JSON_Boolean: { return to_boolean()? "true" : "false";