Better argument validation
[jansson.git] / src / load.c
index d28721e..aa7f99d 100644 (file)
@@ -1,3 +1,10 @@
+/*
+ * Copyright (c) 2009 Petri Lehtinen <petri@digip.org>
+ *
+ * Jansson is free software; you can redistribute it and/or modify
+ * it under the terms of the MIT license. See LICENSE for details.
+ */
+
 #define _GNU_SOURCE
 #include <ctype.h>
 #include <errno.h>
@@ -5,7 +12,6 @@
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
-#include <unistd.h>
 #include <assert.h>
 
 #include <jansson.h>
@@ -537,6 +543,17 @@ out:
     return lex->token;
 }
 
+static char *lex_steal_string(lex_t *lex)
+{
+    char *result = NULL;
+    if(lex->token == TOKEN_STRING)
+    {
+        result = lex->value.string;
+        lex->value.string = NULL;
+    }
+    return result;
+}
+
 static int lex_init(lex_t *lex, get_func get, eof_func eof, void *data)
 {
     stream_init(&lex->stream, get, eof, data);
@@ -580,7 +597,7 @@ static json_t *parse_object(lex_t *lex, json_error_t *error)
             goto error;
         }
 
-        key = strdup(lex->value.string);
+        key = lex_steal_string(lex);
         if(!key)
             return NULL;
 
@@ -798,7 +815,17 @@ json_t *json_loadf(FILE *input, json_error_t *error)
         return NULL;
 
     result = parse_json(&lex, error);
+    if(!result)
+        goto out;
 
+    lex_scan(&lex, error);
+    if(lex.token != TOKEN_EOF) {
+        error_set(error, &lex, "end of file expected");
+        json_decref(result);
+        result = NULL;
+    }
+
+out:
     lex_close(&lex);
     return result;
 }