OSDN Git Service

json: escape u0000 .. u001F when outputting json
authorAnthony Liguori <aliguori@us.ibm.com>
Mon, 25 Jan 2010 14:56:53 +0000 (08:56 -0600)
committerAnthony Liguori <aliguori@us.ibm.com>
Tue, 26 Jan 2010 20:54:59 +0000 (14:54 -0600)
Markus Armbruster pointed out:

JSON requires control characters in strings to be escaped.  RFC 4627
section 2.5:

   A string begins and ends with quotation marks.  All Unicode
   characters may be placed within the quotation marks except for the
   characters that must be escaped: quotation mark, reverse solidus, and
   the control characters (U+0000 through U+001F).

We've been quoting the special escape sequences that JSON defines but we
haven't been encoding the full control character range.  This patch fixes that.

Signed-off-by: Anthony Liguori <aliguori@us.ibm.com>
qjson.c

diff --git a/qjson.c b/qjson.c
index 60c904d..9ad8a91 100644 (file)
--- a/qjson.c
+++ b/qjson.c
@@ -163,8 +163,14 @@ static void to_json(const QObject *obj, QString *str)
                     qstring_append(str, "\\t");
                     break;
                 default: {
-                    char buf[2] = { ptr[0], 0 };
-                    qstring_append(str, buf);
+                    if (ptr[0] <= 0x1F) {
+                        char escape[7];
+                        snprintf(escape, sizeof(escape), "\\u%04X", ptr[0]);
+                        qstring_append(str, escape);
+                    } else {
+                        char buf[2] = { ptr[0], 0 };
+                        qstring_append(str, buf);
+                    }
                     break;
                 }
                 }