Skip to content

Commit

Permalink
Escape JSON strings correctly for error messages (microsoft#44)
Browse files Browse the repository at this point in the history
* Escape JSON strings correctly

* Add test examples with lots of carriage returns
  • Loading branch information
tmccrmck authored Apr 22, 2019
1 parent 16cbbfa commit 71227be
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 6 deletions.
29 changes: 28 additions & 1 deletion onnxruntime/hosting/http/json_handling.cc
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include <sstream>
#include <iomanip>

#include <boost/beast/core.hpp>
#include <google/protobuf/util/json_util.h>

Expand Down Expand Up @@ -32,7 +35,31 @@ protobufutil::Status GenerateResponseInJson(const onnxruntime::hosting::PredictR
}

std::string CreateJsonError(const http::status error_code, const std::string& error_message) {
return R"({"error_code": )" + std::to_string(int(error_code)) + R"(, "error_message": ")" + error_message + R"(" })" + "\n";
auto escaped_message = escape_string(error_message);
return R"({"error_code": )" + std::to_string(int(error_code)) + R"(, "error_message": ")" + escaped_message + R"("})" + "\n";
}

std::string escape_string(const std::string& message) {
std::ostringstream o;
for (char c : message) {
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();
}

} // namespace hosting
Expand Down
4 changes: 4 additions & 0 deletions onnxruntime/hosting/http/json_handling.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ google::protobuf::util::Status GenerateResponseInJson(const onnxruntime::hosting
// Constructs JSON error message from error code object and error message
std::string CreateJsonError(http::status error_code, const std::string& error_message);

// Escapes a string following the JSON standard
// Mostly taken from here: https://stackoverflow.com/questions/7724448/simple-json-string-escape-for-c/33799784#33799784
std::string escape_string(const std::string& message);

} // namespace hosting
} // namespace onnxruntime

Loading

0 comments on commit 71227be

Please sign in to comment.