JSON: fix escape of '"' and '\' characters
authorJens Axboe <axboe@kernel.dk>
Tue, 13 Nov 2012 03:52:10 +0000 (20:52 -0700)
committerJens Axboe <axboe@kernel.dk>
Tue, 13 Nov 2012 03:52:10 +0000 (20:52 -0700)
Reported-by: Kepler Kramer <kkramer@fusionio.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
json.c

diff --git a/json.c b/json.c
index 8efbbda..ea61af7 100644 (file)
--- a/json.c
+++ b/json.c
@@ -57,13 +57,38 @@ static struct json_value *json_create_value_float(float number)
        return value;
 }
 
+static char *strdup_escape(const char *str)
+{
+       const char *input = str;
+       char *p, *ret;
+       int escapes;
+
+       escapes = 0;
+       while ((input = strpbrk(input, "\\\"")) != NULL) {
+               escapes++;
+               input++;
+       }
+
+       p = ret = malloc(strlen(str) + escapes);
+       while (*str) {
+               if (*str == '\\' || *str == '\"')
+                       *p++ = '\\';
+               *p++ = *str++;
+       }
+
+       return ret;
+}
+
+/*
+ * Valid JSON strings must escape '"' and '/' with a preceeding '/'
+ */
 static struct json_value *json_create_value_string(const char *str)
 {
        struct json_value *value = malloc(sizeof(struct json_value));
 
        if (value) {
                value->type = JSON_TYPE_STRING;
-               value->string = strdup(str);
+               value->string = strdup_escape(str);
                if (!value->string) {
                        free(value);
                        value = NULL;