From: Waldemar Kozaczuk <jwkozac...@gmail.com>
Committer: Nadav Har'El <n...@scylladb.com>
Branch: master

Changed json formatter to escape strings according to the spec

Changed formatter::to_json methods that format string to JSON to properly
escape according to http://www.json.org/.

Fixes #836.

Signed-off-by: Waldemar Kozaczuk <jwkozac...@gmail.com>
Message-Id: <1484801545-11777-1-git-send-email-jwkozac...@gmail.com>

---
diff --git a/modules/httpserver/json/formatter.cc b/modules/httpserver/json/formatter.cc
--- a/modules/httpserver/json/formatter.cc
+++ b/modules/httpserver/json/formatter.cc
@@ -9,6 +9,7 @@
 #include "json_elements.hh"
 #include <float.h>
 #include <boost/math/special_functions/fpclassify.hpp>
+#include <iomanip>

 using namespace std;

@@ -18,13 +19,13 @@ namespace json {

 string formatter::to_json(const string& str)
 {
-    return '"' + str + '"';
+    return '"' + json_escape_UTF8_string(str) + '"';
 }

 string formatter::to_json(const char* str)
 {
     string res = "\"";
-    res += str;
+    res += json_escape_UTF8_string(str);
     return res + '"';
 }

@@ -71,5 +72,28 @@ std::string formatter::to_json(unsigned long l) {
     return to_string(l);
 }

+std::string formatter::json_escape_UTF8_string(const std::string& utf8_string) {
+    std::ostringstream o;
+    for (auto c = utf8_string.cbegin(); c != utf8_string.cend(); 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();
+}
+
 }
 }
diff --git a/modules/httpserver/json/formatter.hh b/modules/httpserver/json/formatter.hh
--- a/modules/httpserver/json/formatter.hh
+++ b/modules/httpserver/json/formatter.hh
@@ -118,6 +118,8 @@ private:

     constexpr static const char* TIME_FORMAT = "%a %b %d %H:%M:%S %Z %Y";

+ static std::string json_escape_UTF8_string(const std::string& utf8_string);
+
 };

 }

--
You received this message because you are subscribed to the Google Groups "OSv 
Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to osv-dev+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to