Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON: properly escape json strings #1758

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion trunk/src/protocol/srs_protocol_json.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@
#ifdef __cplusplus

#include <string.h>
#include <sstream>
#include <iomanip>

extern "C"
{
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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";
Expand Down