ovn-controller: Drop unknown datapath log message.
[cascardo/ovs.git] / lib / json.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2014, 2015 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "json.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <float.h>
24 #include <limits.h>
25 #include <string.h>
26
27 #include "dynamic-string.h"
28 #include "hash.h"
29 #include "shash.h"
30 #include "unicode.h"
31 #include "util.h"
32
33 /* The type of a JSON token. */
34 enum json_token_type {
35     T_EOF = 0,
36     T_BEGIN_ARRAY = '[',
37     T_END_ARRAY = ']',
38     T_BEGIN_OBJECT = '{',
39     T_END_OBJECT = '}',
40     T_NAME_SEPARATOR = ':',
41     T_VALUE_SEPARATOR = ',',
42     T_FALSE = UCHAR_MAX + 1,
43     T_NULL,
44     T_TRUE,
45     T_INTEGER,
46     T_REAL,
47     T_STRING
48 };
49
50 /* A JSON token.
51  *
52  * RFC 4627 doesn't define a lexical structure for JSON but I believe this to
53  * be compliant with the standard.
54  */
55 struct json_token {
56     enum json_token_type type;
57     union {
58         double real;
59         long long int integer;
60         const char *string;
61     } u;
62 };
63
64 enum json_lex_state {
65     JSON_LEX_START,             /* Not inside a token. */
66     JSON_LEX_NUMBER,            /* Reading a number. */
67     JSON_LEX_KEYWORD,           /* Reading a keyword. */
68     JSON_LEX_STRING,            /* Reading a quoted string. */
69     JSON_LEX_ESCAPE             /* In a quoted string just after a "\". */
70 };
71
72 enum json_parse_state {
73     JSON_PARSE_START,           /* Beginning of input. */
74     JSON_PARSE_END,             /* End of input. */
75
76     /* Objects. */
77     JSON_PARSE_OBJECT_INIT,     /* Expecting '}' or an object name. */
78     JSON_PARSE_OBJECT_NAME,     /* Expecting an object name. */
79     JSON_PARSE_OBJECT_COLON,    /* Expecting ':'. */
80     JSON_PARSE_OBJECT_VALUE,    /* Expecting an object value. */
81     JSON_PARSE_OBJECT_NEXT,     /* Expecting ',' or '}'. */
82
83     /* Arrays. */
84     JSON_PARSE_ARRAY_INIT,      /* Expecting ']' or a value. */
85     JSON_PARSE_ARRAY_VALUE,     /* Expecting a value. */
86     JSON_PARSE_ARRAY_NEXT       /* Expecting ',' or ']'. */
87 };
88
89 struct json_parser_node {
90     struct json *json;
91 };
92
93 /* A JSON parser. */
94 struct json_parser {
95     int flags;
96
97     /* Lexical analysis. */
98     enum json_lex_state lex_state;
99     struct ds buffer;           /* Buffer for accumulating token text. */
100     int line_number;
101     int column_number;
102     int byte_number;
103
104     /* Parsing. */
105     enum json_parse_state parse_state;
106 #define JSON_MAX_HEIGHT 1000
107     struct json_parser_node *stack;
108     size_t height, allocated_height;
109     char *member_name;
110
111     /* Parse status. */
112     bool done;
113     char *error;                /* Error message, if any, null if none yet. */
114 };
115
116 static struct json *json_create(enum json_type type);
117 static void json_parser_input(struct json_parser *, struct json_token *);
118
119 static void json_error(struct json_parser *p, const char *format, ...)
120     OVS_PRINTF_FORMAT(2, 3);
121 \f
122 const char *
123 json_type_to_string(enum json_type type)
124 {
125     switch (type) {
126     case JSON_NULL:
127         return "null";
128
129     case JSON_FALSE:
130         return "false";
131
132     case JSON_TRUE:
133         return "true";
134
135     case JSON_OBJECT:
136         return "object";
137
138     case JSON_ARRAY:
139         return "array";
140
141     case JSON_INTEGER:
142     case JSON_REAL:
143         return "number";
144
145     case JSON_STRING:
146         return "string";
147
148     case JSON_N_TYPES:
149     default:
150         return "<invalid>";
151     }
152 }
153 \f
154 /* Functions for manipulating struct json. */
155
156 struct json *
157 json_null_create(void)
158 {
159     return json_create(JSON_NULL);
160 }
161
162 struct json *
163 json_boolean_create(bool b)
164 {
165     return json_create(b ? JSON_TRUE : JSON_FALSE);
166 }
167
168 struct json *
169 json_string_create_nocopy(char *s)
170 {
171     struct json *json = json_create(JSON_STRING);
172     json->u.string = s;
173     return json;
174 }
175
176 struct json *
177 json_string_create(const char *s)
178 {
179     return json_string_create_nocopy(xstrdup(s));
180 }
181
182 struct json *
183 json_array_create_empty(void)
184 {
185     struct json *json = json_create(JSON_ARRAY);
186     json->u.array.elems = NULL;
187     json->u.array.n = 0;
188     json->u.array.n_allocated = 0;
189     return json;
190 }
191
192 void
193 json_array_add(struct json *array_, struct json *element)
194 {
195     struct json_array *array = json_array(array_);
196     if (array->n >= array->n_allocated) {
197         array->elems = x2nrealloc(array->elems, &array->n_allocated,
198                                   sizeof *array->elems);
199     }
200     array->elems[array->n++] = element;
201 }
202
203 void
204 json_array_trim(struct json *array_)
205 {
206     struct json_array *array = json_array(array_);
207     if (array->n < array->n_allocated){
208         array->n_allocated = array->n;
209         array->elems = xrealloc(array->elems, array->n * sizeof *array->elems);
210     }
211 }
212
213 struct json *
214 json_array_create(struct json **elements, size_t n)
215 {
216     struct json *json = json_create(JSON_ARRAY);
217     json->u.array.elems = elements;
218     json->u.array.n = n;
219     json->u.array.n_allocated = n;
220     return json;
221 }
222
223 struct json *
224 json_array_create_1(struct json *elem0)
225 {
226     struct json **elems = xmalloc(sizeof *elems);
227     elems[0] = elem0;
228     return json_array_create(elems, 1);
229 }
230
231 struct json *
232 json_array_create_2(struct json *elem0, struct json *elem1)
233 {
234     struct json **elems = xmalloc(2 * sizeof *elems);
235     elems[0] = elem0;
236     elems[1] = elem1;
237     return json_array_create(elems, 2);
238 }
239
240 struct json *
241 json_array_create_3(struct json *elem0, struct json *elem1, struct json *elem2)
242 {
243     struct json **elems = xmalloc(3 * sizeof *elems);
244     elems[0] = elem0;
245     elems[1] = elem1;
246     elems[2] = elem2;
247     return json_array_create(elems, 3);
248 }
249
250 struct json *
251 json_object_create(void)
252 {
253     struct json *json = json_create(JSON_OBJECT);
254     json->u.object = xmalloc(sizeof *json->u.object);
255     shash_init(json->u.object);
256     return json;
257 }
258
259 struct json *
260 json_integer_create(long long int integer)
261 {
262     struct json *json = json_create(JSON_INTEGER);
263     json->u.integer = integer;
264     return json;
265 }
266
267 struct json *
268 json_real_create(double real)
269 {
270     struct json *json = json_create(JSON_REAL);
271     json->u.real = real;
272     return json;
273 }
274
275 void
276 json_object_put(struct json *json, const char *name, struct json *value)
277 {
278     json_destroy(shash_replace(json->u.object, name, value));
279 }
280
281 void
282 json_object_put_string(struct json *json, const char *name, const char *value)
283 {
284     json_object_put(json, name, json_string_create(value));
285 }
286
287 const char *
288 json_string(const struct json *json)
289 {
290     ovs_assert(json->type == JSON_STRING);
291     return json->u.string;
292 }
293
294 struct json_array *
295 json_array(const struct json *json)
296 {
297     ovs_assert(json->type == JSON_ARRAY);
298     return CONST_CAST(struct json_array *, &json->u.array);
299 }
300
301 struct shash *
302 json_object(const struct json *json)
303 {
304     ovs_assert(json->type == JSON_OBJECT);
305     return CONST_CAST(struct shash *, json->u.object);
306 }
307
308 bool
309 json_boolean(const struct json *json)
310 {
311     ovs_assert(json->type == JSON_TRUE || json->type == JSON_FALSE);
312     return json->type == JSON_TRUE;
313 }
314
315 double
316 json_real(const struct json *json)
317 {
318     ovs_assert(json->type == JSON_REAL || json->type == JSON_INTEGER);
319     return json->type == JSON_REAL ? json->u.real : json->u.integer;
320 }
321
322 int64_t
323 json_integer(const struct json *json)
324 {
325     ovs_assert(json->type == JSON_INTEGER);
326     return json->u.integer;
327 }
328 \f
329 static void json_destroy_object(struct shash *object);
330 static void json_destroy_array(struct json_array *array);
331
332 /* Frees 'json' and everything it points to, recursively. */
333 void
334 json_destroy(struct json *json)
335 {
336     if (json) {
337         switch (json->type) {
338         case JSON_OBJECT:
339             json_destroy_object(json->u.object);
340             break;
341
342         case JSON_ARRAY:
343             json_destroy_array(&json->u.array);
344             break;
345
346         case JSON_STRING:
347             free(json->u.string);
348             break;
349
350         case JSON_NULL:
351         case JSON_FALSE:
352         case JSON_TRUE:
353         case JSON_INTEGER:
354         case JSON_REAL:
355             break;
356
357         case JSON_N_TYPES:
358             OVS_NOT_REACHED();
359         }
360         free(json);
361     }
362 }
363
364 static void
365 json_destroy_object(struct shash *object)
366 {
367     struct shash_node *node, *next;
368
369     SHASH_FOR_EACH_SAFE (node, next, object) {
370         struct json *value = node->data;
371
372         json_destroy(value);
373         shash_delete(object, node);
374     }
375     shash_destroy(object);
376     free(object);
377 }
378
379 static void
380 json_destroy_array(struct json_array *array)
381 {
382     size_t i;
383
384     for (i = 0; i < array->n; i++) {
385         json_destroy(array->elems[i]);
386     }
387     free(array->elems);
388 }
389 \f
390 static struct json *json_clone_object(const struct shash *object);
391 static struct json *json_clone_array(const struct json_array *array);
392
393 /* Returns a deep copy of 'json'. */
394 struct json *
395 json_clone(const struct json *json)
396 {
397     switch (json->type) {
398     case JSON_OBJECT:
399         return json_clone_object(json->u.object);
400
401     case JSON_ARRAY:
402         return json_clone_array(&json->u.array);
403
404     case JSON_STRING:
405         return json_string_create(json->u.string);
406
407     case JSON_NULL:
408     case JSON_FALSE:
409     case JSON_TRUE:
410         return json_create(json->type);
411
412     case JSON_INTEGER:
413         return json_integer_create(json->u.integer);
414
415     case JSON_REAL:
416         return json_real_create(json->u.real);
417
418     case JSON_N_TYPES:
419     default:
420         OVS_NOT_REACHED();
421     }
422 }
423
424 static struct json *
425 json_clone_object(const struct shash *object)
426 {
427     struct shash_node *node;
428     struct json *json;
429
430     json = json_object_create();
431     SHASH_FOR_EACH (node, object) {
432         struct json *value = node->data;
433         json_object_put(json, node->name, json_clone(value));
434     }
435     return json;
436 }
437
438 static struct json *
439 json_clone_array(const struct json_array *array)
440 {
441     struct json **elems;
442     size_t i;
443
444     elems = xmalloc(array->n * sizeof *elems);
445     for (i = 0; i < array->n; i++) {
446         elems[i] = json_clone(array->elems[i]);
447     }
448     return json_array_create(elems, array->n);
449 }
450 \f
451 static size_t
452 json_hash_object(const struct shash *object, size_t basis)
453 {
454     const struct shash_node **nodes;
455     size_t n, i;
456
457     nodes = shash_sort(object);
458     n = shash_count(object);
459     for (i = 0; i < n; i++) {
460         const struct shash_node *node = nodes[i];
461         basis = hash_string(node->name, basis);
462         basis = json_hash(node->data, basis);
463     }
464     free(nodes);
465     return basis;
466 }
467
468 static size_t
469 json_hash_array(const struct json_array *array, size_t basis)
470 {
471     size_t i;
472
473     basis = hash_int(array->n, basis);
474     for (i = 0; i < array->n; i++) {
475         basis = json_hash(array->elems[i], basis);
476     }
477     return basis;
478 }
479
480 size_t
481 json_hash(const struct json *json, size_t basis)
482 {
483     switch (json->type) {
484     case JSON_OBJECT:
485         return json_hash_object(json->u.object, basis);
486
487     case JSON_ARRAY:
488         return json_hash_array(&json->u.array, basis);
489
490     case JSON_STRING:
491         return hash_string(json->u.string, basis);
492
493     case JSON_NULL:
494     case JSON_FALSE:
495     case JSON_TRUE:
496         return hash_int(json->type << 8, basis);
497
498     case JSON_INTEGER:
499         return hash_int(json->u.integer, basis);
500
501     case JSON_REAL:
502         return hash_double(json->u.real, basis);
503
504     case JSON_N_TYPES:
505     default:
506         OVS_NOT_REACHED();
507     }
508 }
509
510 static bool
511 json_equal_object(const struct shash *a, const struct shash *b)
512 {
513     struct shash_node *a_node;
514
515     if (shash_count(a) != shash_count(b)) {
516         return false;
517     }
518
519     SHASH_FOR_EACH (a_node, a) {
520         struct shash_node *b_node = shash_find(b, a_node->name);
521         if (!b_node || !json_equal(a_node->data, b_node->data)) {
522             return false;
523         }
524     }
525
526     return true;
527 }
528
529 static bool
530 json_equal_array(const struct json_array *a, const struct json_array *b)
531 {
532     size_t i;
533
534     if (a->n != b->n) {
535         return false;
536     }
537
538     for (i = 0; i < a->n; i++) {
539         if (!json_equal(a->elems[i], b->elems[i])) {
540             return false;
541         }
542     }
543
544     return true;
545 }
546
547 bool
548 json_equal(const struct json *a, const struct json *b)
549 {
550     if (a->type != b->type) {
551         return false;
552     }
553
554     switch (a->type) {
555     case JSON_OBJECT:
556         return json_equal_object(a->u.object, b->u.object);
557
558     case JSON_ARRAY:
559         return json_equal_array(&a->u.array, &b->u.array);
560
561     case JSON_STRING:
562         return !strcmp(a->u.string, b->u.string);
563
564     case JSON_NULL:
565     case JSON_FALSE:
566     case JSON_TRUE:
567         return true;
568
569     case JSON_INTEGER:
570         return a->u.integer == b->u.integer;
571
572     case JSON_REAL:
573         return a->u.real == b->u.real;
574
575     case JSON_N_TYPES:
576     default:
577         OVS_NOT_REACHED();
578     }
579 }
580 \f
581 /* Lexical analysis. */
582
583 static void
584 json_lex_keyword(struct json_parser *p)
585 {
586     struct json_token token;
587     const char *s;
588
589     s = ds_cstr(&p->buffer);
590     if (!strcmp(s, "false")) {
591         token.type = T_FALSE;
592     } else if (!strcmp(s, "true")) {
593         token.type = T_TRUE;
594     } else if (!strcmp(s, "null")) {
595         token.type = T_NULL;
596     } else {
597         json_error(p, "invalid keyword '%s'", s);
598         return;
599     }
600     json_parser_input(p, &token);
601 }
602
603 static void
604 json_lex_number(struct json_parser *p)
605 {
606     const char *cp = ds_cstr(&p->buffer);
607     unsigned long long int significand = 0;
608     struct json_token token;
609     bool imprecise = false;
610     bool negative = false;
611     int pow10 = 0;
612
613     /* Leading minus sign. */
614     if (*cp == '-') {
615         negative = true;
616         cp++;
617     }
618
619     /* At least one integer digit, but 0 may not be used as a leading digit for
620      * a longer number. */
621     significand = 0;
622     if (*cp == '0') {
623         cp++;
624         if (isdigit((unsigned char) *cp)) {
625             json_error(p, "leading zeros not allowed");
626             return;
627         }
628     } else if (isdigit((unsigned char) *cp)) {
629         do {
630             if (significand <= ULLONG_MAX / 10) {
631                 significand = significand * 10 + (*cp - '0');
632             } else {
633                 pow10++;
634                 if (*cp != '0') {
635                     imprecise = true;
636                 }
637             }
638             cp++;
639         } while (isdigit((unsigned char) *cp));
640     } else {
641         json_error(p, "'-' must be followed by digit");
642         return;
643     }
644
645     /* Optional fraction. */
646     if (*cp == '.') {
647         cp++;
648         if (!isdigit((unsigned char) *cp)) {
649             json_error(p, "decimal point must be followed by digit");
650             return;
651         }
652         do {
653             if (significand <= ULLONG_MAX / 10) {
654                 significand = significand * 10 + (*cp - '0');
655                 pow10--;
656             } else if (*cp != '0') {
657                 imprecise = true;
658             }
659             cp++;
660         } while (isdigit((unsigned char) *cp));
661     }
662
663     /* Optional exponent. */
664     if (*cp == 'e' || *cp == 'E') {
665         bool negative_exponent = false;
666         int exponent;
667
668         cp++;
669         if (*cp == '+') {
670             cp++;
671         } else if (*cp == '-') {
672             negative_exponent = true;
673             cp++;
674         }
675
676         if (!isdigit((unsigned char) *cp)) {
677             json_error(p, "exponent must contain at least one digit");
678             return;
679         }
680
681         exponent = 0;
682         do {
683             if (exponent >= INT_MAX / 10) {
684                 json_error(p, "exponent outside valid range");
685                 return;
686             }
687             exponent = exponent * 10 + (*cp - '0');
688             cp++;
689         } while (isdigit((unsigned char) *cp));
690
691         if (negative_exponent) {
692             pow10 -= exponent;
693         } else {
694             pow10 += exponent;
695         }
696     }
697
698     if (*cp != '\0') {
699         json_error(p, "syntax error in number");
700         return;
701     }
702
703     /* Figure out number.
704      *
705      * We suppress negative zeros as a matter of policy. */
706     if (!significand) {
707         token.type = T_INTEGER;
708         token.u.integer = 0;
709         json_parser_input(p, &token);
710         return;
711     }
712
713     if (!imprecise) {
714         while (pow10 > 0 && significand < ULLONG_MAX / 10) {
715             significand *= 10;
716             pow10--;
717         }
718         while (pow10 < 0 && significand % 10 == 0) {
719             significand /= 10;
720             pow10++;
721         }
722         if (pow10 == 0
723             && significand <= (negative
724                                ? (unsigned long long int) LLONG_MAX + 1
725                                : LLONG_MAX)) {
726             token.type = T_INTEGER;
727             token.u.integer = negative ? -significand : significand;
728             json_parser_input(p, &token);
729             return;
730         }
731     }
732
733     token.type = T_REAL;
734     if (!str_to_double(ds_cstr(&p->buffer), &token.u.real)) {
735         json_error(p, "number outside valid range");
736         return;
737     }
738     /* Suppress negative zero. */
739     if (token.u.real == 0) {
740         token.u.real = 0;
741     }
742     json_parser_input(p, &token);
743 }
744
745 static const char *
746 json_lex_4hex(const char *cp, const char *end, int *valuep)
747 {
748     unsigned int value;
749     bool ok;
750
751     if (cp + 4 > end) {
752         return "quoted string ends within \\u escape";
753     }
754
755     value = hexits_value(cp, 4, &ok);
756     if (!ok) {
757         return "malformed \\u escape";
758     }
759     if (!value) {
760         return "null bytes not supported in quoted strings";
761     }
762     *valuep = value;
763     return NULL;
764 }
765
766 static const char *
767 json_lex_unicode(const char *cp, const char *end, struct ds *out)
768 {
769     const char *error;
770     int c0, c1;
771
772     error = json_lex_4hex(cp, end, &c0);
773     if (error) {
774         ds_clear(out);
775         ds_put_cstr(out, error);
776         return NULL;
777     }
778     cp += 4;
779     if (!uc_is_leading_surrogate(c0)) {
780         ds_put_utf8(out, c0);
781         return cp;
782     }
783
784     if (cp + 2 > end || *cp++ != '\\' || *cp++ != 'u') {
785         ds_clear(out);
786         ds_put_cstr(out, "malformed escaped surrogate pair");
787         return NULL;
788     }
789
790     error = json_lex_4hex(cp, end, &c1);
791     if (error) {
792         ds_clear(out);
793         ds_put_cstr(out, error);
794         return NULL;
795     }
796     cp += 4;
797     if (!uc_is_trailing_surrogate(c1)) {
798         ds_clear(out);
799         ds_put_cstr(out, "second half of escaped surrogate pair is not "
800                     "trailing surrogate");
801         return NULL;
802     }
803
804     ds_put_utf8(out, utf16_decode_surrogate_pair(c0, c1));
805     return cp;
806 }
807
808 bool
809 json_string_unescape(const char *in, size_t in_len, char **outp)
810 {
811     const char *end = in + in_len;
812     bool ok = false;
813     struct ds out;
814
815     ds_init(&out);
816     ds_reserve(&out, in_len);
817     while (in < end) {
818         if (*in == '"') {
819             ds_clear(&out);
820             ds_put_cstr(&out, "quoted string may not include unescaped \"");
821             goto exit;
822         }
823         if (*in != '\\') {
824             ds_put_char(&out, *in++);
825             continue;
826         }
827
828         in++;
829         if (in >= end) {
830             /* The JSON parser will never trigger this message, because its
831              * lexer will never pass in a string that ends in a single
832              * backslash, but json_string_unescape() has other callers that
833              * are not as careful.*/
834             ds_put_cstr(&out, "quoted string may not end with backslash");
835             goto exit;
836         }
837         switch (*in++) {
838         case '"': case '\\': case '/':
839             ds_put_char(&out, in[-1]);
840             break;
841
842         case 'b':
843             ds_put_char(&out, '\b');
844             break;
845
846         case 'f':
847             ds_put_char(&out, '\f');
848             break;
849
850         case 'n':
851             ds_put_char(&out, '\n');
852             break;
853
854         case 'r':
855             ds_put_char(&out, '\r');
856             break;
857
858         case 't':
859             ds_put_char(&out, '\t');
860             break;
861
862         case 'u':
863             in = json_lex_unicode(in, end, &out);
864             if (!in) {
865                 goto exit;
866             }
867             break;
868
869         default:
870             ds_clear(&out);
871             ds_put_format(&out, "bad escape \\%c", in[-1]);
872             goto exit;
873         }
874     }
875     ok = true;
876
877 exit:
878     *outp = ds_cstr(&out);
879     return ok;
880 }
881
882 void
883 json_string_escape(const char *in, struct ds *out)
884 {
885     struct json json = {
886         .type = JSON_STRING,
887         .u.string = CONST_CAST(char *, in),
888     };
889     json_to_ds(&json, 0, out);
890 }
891
892 static void
893 json_parser_input_string(struct json_parser *p, const char *s)
894 {
895     struct json_token token;
896
897     token.type = T_STRING;
898     token.u.string = s;
899     json_parser_input(p, &token);
900 }
901
902 static void
903 json_lex_string(struct json_parser *p)
904 {
905     const char *raw = ds_cstr(&p->buffer);
906     if (!strchr(raw, '\\')) {
907         json_parser_input_string(p, raw);
908     } else {
909         char *cooked;
910
911         if (json_string_unescape(raw, strlen(raw), &cooked)) {
912             json_parser_input_string(p, cooked);
913         } else {
914             json_error(p, "%s", cooked);
915         }
916
917         free(cooked);
918     }
919 }
920
921 static bool
922 json_lex_input(struct json_parser *p, unsigned char c)
923 {
924     struct json_token token;
925
926     switch (p->lex_state) {
927     case JSON_LEX_START:
928         switch (c) {
929         case ' ': case '\t': case '\n': case '\r':
930             /* Nothing to do. */
931             return true;
932
933         case 'a': case 'b': case 'c': case 'd': case 'e':
934         case 'f': case 'g': case 'h': case 'i': case 'j':
935         case 'k': case 'l': case 'm': case 'n': case 'o':
936         case 'p': case 'q': case 'r': case 's': case 't':
937         case 'u': case 'v': case 'w': case 'x': case 'y':
938         case 'z':
939             p->lex_state = JSON_LEX_KEYWORD;
940             break;
941
942         case '[': case '{': case ']': case '}': case ':': case ',':
943             token.type = c;
944             json_parser_input(p, &token);
945             return true;
946
947         case '-':
948         case '0': case '1': case '2': case '3': case '4':
949         case '5': case '6': case '7': case '8': case '9':
950             p->lex_state = JSON_LEX_NUMBER;
951             break;
952
953         case '"':
954             p->lex_state = JSON_LEX_STRING;
955             return true;
956
957         default:
958             if (isprint(c)) {
959                 json_error(p, "invalid character '%c'", c);
960             } else {
961                 json_error(p, "invalid character U+%04x", c);
962             }
963             return true;
964         }
965         break;
966
967     case JSON_LEX_KEYWORD:
968         if (!isalpha((unsigned char) c)) {
969             json_lex_keyword(p);
970             return false;
971         }
972         break;
973
974     case JSON_LEX_NUMBER:
975         if (!strchr(".0123456789eE-+", c)) {
976             json_lex_number(p);
977             return false;
978         }
979         break;
980
981     case JSON_LEX_STRING:
982         if (c == '\\') {
983             p->lex_state = JSON_LEX_ESCAPE;
984         } else if (c == '"') {
985             json_lex_string(p);
986             return true;
987         } else if (c < 0x20) {
988             json_error(p, "U+%04X must be escaped in quoted string", c);
989             return true;
990         }
991         break;
992
993     case JSON_LEX_ESCAPE:
994         p->lex_state = JSON_LEX_STRING;
995         break;
996
997     default:
998         abort();
999     }
1000     ds_put_char(&p->buffer, c);
1001     return true;
1002 }
1003 \f
1004 /* Parsing. */
1005
1006 /* Parses 'string' as a JSON object or array and returns a newly allocated
1007  * 'struct json'.  The caller must free the returned structure with
1008  * json_destroy() when it is no longer needed.
1009  *
1010  * 'string' must be encoded in UTF-8.
1011  *
1012  * If 'string' is valid JSON, then the returned 'struct json' will be either an
1013  * object (JSON_OBJECT) or an array (JSON_ARRAY).
1014  *
1015  * If 'string' is not valid JSON, then the returned 'struct json' will be a
1016  * string (JSON_STRING) that describes the particular error encountered during
1017  * parsing.  (This is an acceptable means of error reporting because at its top
1018  * level JSON must be either an object or an array; a bare string is not
1019  * valid.) */
1020 struct json *
1021 json_from_string(const char *string)
1022 {
1023     struct json_parser *p = json_parser_create(JSPF_TRAILER);
1024     json_parser_feed(p, string, strlen(string));
1025     return json_parser_finish(p);
1026 }
1027
1028 /* Reads the file named 'file_name', parses its contents as a JSON object or
1029  * array, and returns a newly allocated 'struct json'.  The caller must free
1030  * the returned structure with json_destroy() when it is no longer needed.
1031  *
1032  * The file must be encoded in UTF-8.
1033  *
1034  * See json_from_string() for return value semantics.
1035  */
1036 struct json *
1037 json_from_file(const char *file_name)
1038 {
1039     struct json *json;
1040     FILE *stream;
1041
1042     stream = fopen(file_name, "r");
1043     if (!stream) {
1044         return json_string_create_nocopy(
1045             xasprintf("error opening \"%s\": %s", file_name,
1046                       ovs_strerror(errno)));
1047     }
1048     json = json_from_stream(stream);
1049     fclose(stream);
1050
1051     return json;
1052 }
1053
1054 /* Parses the contents of 'stream' as a JSON object or array, and returns a
1055  * newly allocated 'struct json'.  The caller must free the returned structure
1056  * with json_destroy() when it is no longer needed.
1057  *
1058  * The file must be encoded in UTF-8.
1059  *
1060  * See json_from_string() for return value semantics.
1061  */
1062 struct json *
1063 json_from_stream(FILE *stream)
1064 {
1065     struct json_parser *p;
1066     struct json *json;
1067
1068     p = json_parser_create(JSPF_TRAILER);
1069     for (;;) {
1070         char buffer[BUFSIZ];
1071         size_t n;
1072
1073         n = fread(buffer, 1, sizeof buffer, stream);
1074         if (!n || json_parser_feed(p, buffer, n) != n) {
1075             break;
1076         }
1077     }
1078     json = json_parser_finish(p);
1079
1080     if (ferror(stream)) {
1081         json_destroy(json);
1082         json = json_string_create_nocopy(
1083             xasprintf("error reading JSON stream: %s", ovs_strerror(errno)));
1084     }
1085
1086     return json;
1087 }
1088
1089 struct json_parser *
1090 json_parser_create(int flags)
1091 {
1092     struct json_parser *p = xzalloc(sizeof *p);
1093     p->flags = flags;
1094     return p;
1095 }
1096
1097 size_t
1098 json_parser_feed(struct json_parser *p, const char *input, size_t n)
1099 {
1100     size_t i;
1101     for (i = 0; !p->done && i < n; ) {
1102         if (json_lex_input(p, input[i])) {
1103             p->byte_number++;
1104             if (input[i] == '\n') {
1105                 p->column_number = 0;
1106                 p->line_number++;
1107             } else {
1108                 p->column_number++;
1109             }
1110             i++;
1111         }
1112     }
1113     return i;
1114 }
1115
1116 bool
1117 json_parser_is_done(const struct json_parser *p)
1118 {
1119     return p->done;
1120 }
1121
1122 struct json *
1123 json_parser_finish(struct json_parser *p)
1124 {
1125     struct json *json;
1126
1127     switch (p->lex_state) {
1128     case JSON_LEX_START:
1129         break;
1130
1131     case JSON_LEX_STRING:
1132     case JSON_LEX_ESCAPE:
1133         json_error(p, "unexpected end of input in quoted string");
1134         break;
1135
1136     case JSON_LEX_NUMBER:
1137     case JSON_LEX_KEYWORD:
1138         json_lex_input(p, ' ');
1139         break;
1140     }
1141
1142     if (p->parse_state == JSON_PARSE_START) {
1143         json_error(p, "empty input stream");
1144     } else if (p->parse_state != JSON_PARSE_END) {
1145         json_error(p, "unexpected end of input");
1146     }
1147
1148     if (!p->error) {
1149         ovs_assert(p->height == 1);
1150         ovs_assert(p->stack[0].json != NULL);
1151         json = p->stack[--p->height].json;
1152     } else {
1153         json = json_string_create_nocopy(p->error);
1154         p->error = NULL;
1155     }
1156
1157     json_parser_abort(p);
1158
1159     return json;
1160 }
1161
1162 void
1163 json_parser_abort(struct json_parser *p)
1164 {
1165     if (p) {
1166         ds_destroy(&p->buffer);
1167         if (p->height) {
1168             json_destroy(p->stack[0].json);
1169         }
1170         free(p->stack);
1171         free(p->member_name);
1172         free(p->error);
1173         free(p);
1174     }
1175 }
1176
1177 static struct json_parser_node *
1178 json_parser_top(struct json_parser *p)
1179 {
1180     return &p->stack[p->height - 1];
1181 }
1182
1183 static void
1184 json_parser_put_value(struct json_parser *p, struct json *value)
1185 {
1186     struct json_parser_node *node = json_parser_top(p);
1187     if (node->json->type == JSON_OBJECT) {
1188         json_object_put(node->json, p->member_name, value);
1189         free(p->member_name);
1190         p->member_name = NULL;
1191     } else if (node->json->type == JSON_ARRAY) {
1192         json_array_add(node->json, value);
1193     } else {
1194         OVS_NOT_REACHED();
1195     }
1196 }
1197
1198 static void
1199 json_parser_push(struct json_parser *p,
1200                  struct json *new_json, enum json_parse_state new_state)
1201 {
1202     if (p->height < JSON_MAX_HEIGHT) {
1203         struct json_parser_node *node;
1204
1205         if (p->height >= p->allocated_height) {
1206             p->stack = x2nrealloc(p->stack, &p->allocated_height,
1207                                   sizeof *p->stack);
1208         }
1209
1210         if (p->height > 0) {
1211             json_parser_put_value(p, new_json);
1212         }
1213
1214         node = &p->stack[p->height++];
1215         node->json = new_json;
1216         p->parse_state = new_state;
1217     } else {
1218         json_destroy(new_json);
1219         json_error(p, "input exceeds maximum nesting depth %d",
1220                    JSON_MAX_HEIGHT);
1221     }
1222 }
1223
1224 static void
1225 json_parser_push_object(struct json_parser *p)
1226 {
1227     json_parser_push(p, json_object_create(), JSON_PARSE_OBJECT_INIT);
1228 }
1229
1230 static void
1231 json_parser_push_array(struct json_parser *p)
1232 {
1233     json_parser_push(p, json_array_create_empty(), JSON_PARSE_ARRAY_INIT);
1234 }
1235
1236 static void
1237 json_parse_value(struct json_parser *p, struct json_token *token,
1238                  enum json_parse_state next_state)
1239 {
1240     struct json *value;
1241
1242     switch (token->type) {
1243     case T_FALSE:
1244         value = json_boolean_create(false);
1245         break;
1246
1247     case T_NULL:
1248         value = json_null_create();
1249         break;
1250
1251     case T_TRUE:
1252         value = json_boolean_create(true);
1253         break;
1254
1255     case '{':
1256         json_parser_push_object(p);
1257         return;
1258
1259     case '[':
1260         json_parser_push_array(p);
1261         return;
1262
1263     case T_INTEGER:
1264         value = json_integer_create(token->u.integer);
1265         break;
1266
1267     case T_REAL:
1268         value = json_real_create(token->u.real);
1269         break;
1270
1271     case T_STRING:
1272         value = json_string_create(token->u.string);
1273         break;
1274
1275     case T_EOF:
1276     case '}':
1277     case ']':
1278     case ':':
1279     case ',':
1280     default:
1281         json_error(p, "syntax error expecting value");
1282         return;
1283     }
1284
1285     json_parser_put_value(p, value);
1286     p->parse_state = next_state;
1287 }
1288
1289 static void
1290 json_parser_pop(struct json_parser *p)
1291 {
1292     struct json_parser_node *node;
1293
1294     /* Conserve memory. */
1295     node = json_parser_top(p);
1296     if (node->json->type == JSON_ARRAY) {
1297         json_array_trim(node->json);
1298     }
1299
1300     /* Pop off the top-of-stack. */
1301     if (p->height == 1) {
1302         p->parse_state = JSON_PARSE_END;
1303         if (!(p->flags & JSPF_TRAILER)) {
1304             p->done = true;
1305         }
1306     } else {
1307         p->height--;
1308         node = json_parser_top(p);
1309         if (node->json->type == JSON_ARRAY) {
1310             p->parse_state = JSON_PARSE_ARRAY_NEXT;
1311         } else if (node->json->type == JSON_OBJECT) {
1312             p->parse_state = JSON_PARSE_OBJECT_NEXT;
1313         } else {
1314             OVS_NOT_REACHED();
1315         }
1316     }
1317 }
1318
1319 static void
1320 json_parser_input(struct json_parser *p, struct json_token *token)
1321 {
1322     switch (p->parse_state) {
1323     case JSON_PARSE_START:
1324         if (token->type == '{') {
1325             json_parser_push_object(p);
1326         } else if (token->type == '[') {
1327             json_parser_push_array(p);
1328         } else {
1329             json_error(p, "syntax error at beginning of input");
1330         }
1331         break;
1332
1333     case JSON_PARSE_END:
1334         json_error(p, "trailing garbage at end of input");
1335         break;
1336
1337     case JSON_PARSE_OBJECT_INIT:
1338         if (token->type == '}') {
1339             json_parser_pop(p);
1340             break;
1341         }
1342         /* Fall through. */
1343     case JSON_PARSE_OBJECT_NAME:
1344         if (token->type == T_STRING) {
1345             p->member_name = xstrdup(token->u.string);
1346             p->parse_state = JSON_PARSE_OBJECT_COLON;
1347         } else {
1348             json_error(p, "syntax error parsing object expecting string");
1349         }
1350         break;
1351
1352     case JSON_PARSE_OBJECT_COLON:
1353         if (token->type == ':') {
1354             p->parse_state = JSON_PARSE_OBJECT_VALUE;
1355         } else {
1356             json_error(p, "syntax error parsing object expecting ':'");
1357         }
1358         break;
1359
1360     case JSON_PARSE_OBJECT_VALUE:
1361         json_parse_value(p, token, JSON_PARSE_OBJECT_NEXT);
1362         break;
1363
1364     case JSON_PARSE_OBJECT_NEXT:
1365         if (token->type == ',') {
1366             p->parse_state = JSON_PARSE_OBJECT_NAME;
1367         } else if (token->type == '}') {
1368             json_parser_pop(p);
1369         } else {
1370             json_error(p, "syntax error expecting '}' or ','");
1371         }
1372         break;
1373
1374     case JSON_PARSE_ARRAY_INIT:
1375         if (token->type == ']') {
1376             json_parser_pop(p);
1377             break;
1378         }
1379         /* Fall through. */
1380     case JSON_PARSE_ARRAY_VALUE:
1381         json_parse_value(p, token, JSON_PARSE_ARRAY_NEXT);
1382         break;
1383
1384     case JSON_PARSE_ARRAY_NEXT:
1385         if (token->type == ',') {
1386             p->parse_state = JSON_PARSE_ARRAY_VALUE;
1387         } else if (token->type == ']') {
1388             json_parser_pop(p);
1389         } else {
1390             json_error(p, "syntax error expecting ']' or ','");
1391         }
1392         break;
1393
1394     default:
1395         abort();
1396     }
1397
1398     p->lex_state = JSON_LEX_START;
1399     ds_clear(&p->buffer);
1400 }
1401
1402 static struct json *
1403 json_create(enum json_type type)
1404 {
1405     struct json *json = xmalloc(sizeof *json);
1406     json->type = type;
1407     return json;
1408 }
1409
1410 static void
1411 json_error(struct json_parser *p, const char *format, ...)
1412 {
1413     if (!p->error) {
1414         struct ds msg;
1415         va_list args;
1416
1417         ds_init(&msg);
1418         ds_put_format(&msg, "line %d, column %d, byte %d: ",
1419                       p->line_number, p->column_number, p->byte_number);
1420         va_start(args, format);
1421         ds_put_format_valist(&msg, format, args);
1422         va_end(args);
1423
1424         p->error = ds_steal_cstr(&msg);
1425
1426         p->done = true;
1427     }
1428 }
1429 \f
1430 #define SPACES_PER_LEVEL 2
1431
1432 struct json_serializer {
1433     struct ds *ds;
1434     int depth;
1435     int flags;
1436 };
1437
1438 static void json_serialize(const struct json *, struct json_serializer *);
1439 static void json_serialize_object(const struct shash *object,
1440                                   struct json_serializer *);
1441 static void json_serialize_array(const struct json_array *,
1442                                  struct json_serializer *);
1443 static void json_serialize_string(const char *, struct ds *);
1444
1445 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1446  * that string.  The caller is responsible for freeing the returned string,
1447  * with free(), when it is no longer needed.
1448  *
1449  * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1450  * nesting level introducing an additional indentation.  Otherwise, the
1451  * returned string does not contain any new-line characters.
1452  *
1453  * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1454  * in bytewise lexicographic order for reproducibility.  Otherwise, members of
1455  * objects are output in an indeterminate order.
1456  *
1457  * The returned string is valid JSON only if 'json' represents an array or an
1458  * object, since a bare literal does not satisfy the JSON grammar. */
1459 char *
1460 json_to_string(const struct json *json, int flags)
1461 {
1462     struct ds ds;
1463
1464     ds_init(&ds);
1465     json_to_ds(json, flags, &ds);
1466     return ds_steal_cstr(&ds);
1467 }
1468
1469 /* Same as json_to_string(), but the output is appended to 'ds'. */
1470 void
1471 json_to_ds(const struct json *json, int flags, struct ds *ds)
1472 {
1473     struct json_serializer s;
1474
1475     s.ds = ds;
1476     s.depth = 0;
1477     s.flags = flags;
1478     json_serialize(json, &s);
1479 }
1480
1481 static void
1482 json_serialize(const struct json *json, struct json_serializer *s)
1483 {
1484     struct ds *ds = s->ds;
1485
1486     switch (json->type) {
1487     case JSON_NULL:
1488         ds_put_cstr(ds, "null");
1489         break;
1490
1491     case JSON_FALSE:
1492         ds_put_cstr(ds, "false");
1493         break;
1494
1495     case JSON_TRUE:
1496         ds_put_cstr(ds, "true");
1497         break;
1498
1499     case JSON_OBJECT:
1500         json_serialize_object(json->u.object, s);
1501         break;
1502
1503     case JSON_ARRAY:
1504         json_serialize_array(&json->u.array, s);
1505         break;
1506
1507     case JSON_INTEGER:
1508         ds_put_format(ds, "%lld", json->u.integer);
1509         break;
1510
1511     case JSON_REAL:
1512         ds_put_format(ds, "%.*g", DBL_DIG, json->u.real);
1513         break;
1514
1515     case JSON_STRING:
1516         json_serialize_string(json->u.string, ds);
1517         break;
1518
1519     case JSON_N_TYPES:
1520     default:
1521         OVS_NOT_REACHED();
1522     }
1523 }
1524
1525 static void
1526 indent_line(struct json_serializer *s)
1527 {
1528     if (s->flags & JSSF_PRETTY) {
1529         ds_put_char(s->ds, '\n');
1530         ds_put_char_multiple(s->ds, ' ', SPACES_PER_LEVEL * s->depth);
1531     }
1532 }
1533
1534 static void
1535 json_serialize_object_member(size_t i, const struct shash_node *node,
1536                              struct json_serializer *s)
1537 {
1538     struct ds *ds = s->ds;
1539
1540     if (i) {
1541         ds_put_char(ds, ',');
1542         indent_line(s);
1543     }
1544
1545     json_serialize_string(node->name, ds);
1546     ds_put_char(ds, ':');
1547     if (s->flags & JSSF_PRETTY) {
1548         ds_put_char(ds, ' ');
1549     }
1550     json_serialize(node->data, s);
1551 }
1552
1553 static void
1554 json_serialize_object(const struct shash *object, struct json_serializer *s)
1555 {
1556     struct ds *ds = s->ds;
1557
1558     ds_put_char(ds, '{');
1559
1560     s->depth++;
1561     indent_line(s);
1562
1563     if (s->flags & JSSF_SORT) {
1564         const struct shash_node **nodes;
1565         size_t n, i;
1566
1567         nodes = shash_sort(object);
1568         n = shash_count(object);
1569         for (i = 0; i < n; i++) {
1570             json_serialize_object_member(i, nodes[i], s);
1571         }
1572         free(nodes);
1573     } else {
1574         struct shash_node *node;
1575         size_t i;
1576
1577         i = 0;
1578         SHASH_FOR_EACH (node, object) {
1579             json_serialize_object_member(i++, node, s);
1580         }
1581     }
1582
1583     ds_put_char(ds, '}');
1584     s->depth--;
1585 }
1586
1587 static void
1588 json_serialize_array(const struct json_array *array, struct json_serializer *s)
1589 {
1590     struct ds *ds = s->ds;
1591     size_t i;
1592
1593     ds_put_char(ds, '[');
1594     s->depth++;
1595
1596     if (array->n > 0) {
1597         indent_line(s);
1598
1599         for (i = 0; i < array->n; i++) {
1600             if (i) {
1601                 ds_put_char(ds, ',');
1602                 indent_line(s);
1603             }
1604             json_serialize(array->elems[i], s);
1605         }
1606     }
1607
1608     s->depth--;
1609     ds_put_char(ds, ']');
1610 }
1611
1612 static void
1613 json_serialize_string(const char *string, struct ds *ds)
1614 {
1615     uint8_t c;
1616
1617     ds_put_char(ds, '"');
1618     while ((c = *string++) != '\0') {
1619         switch (c) {
1620         case '"':
1621             ds_put_cstr(ds, "\\\"");
1622             break;
1623
1624         case '\\':
1625             ds_put_cstr(ds, "\\\\");
1626             break;
1627
1628         case '\b':
1629             ds_put_cstr(ds, "\\b");
1630             break;
1631
1632         case '\f':
1633             ds_put_cstr(ds, "\\f");
1634             break;
1635
1636         case '\n':
1637             ds_put_cstr(ds, "\\n");
1638             break;
1639
1640         case '\r':
1641             ds_put_cstr(ds, "\\r");
1642             break;
1643
1644         case '\t':
1645             ds_put_cstr(ds, "\\t");
1646             break;
1647
1648         default:
1649             if (c >= 32) {
1650                 ds_put_char(ds, c);
1651             } else {
1652                 ds_put_format(ds, "\\u%04x", c);
1653             }
1654             break;
1655         }
1656     }
1657     ds_put_char(ds, '"');
1658 }