]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/json.c
tree-wide: drop string.h when string-util.h or friends are included
[thirdparty/systemd.git] / src / shared / json.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <locale.h>
5 #include <math.h>
6 #include <stdarg.h>
7 #include <stdlib.h>
8 #include <sys/types.h>
9
10 #include "sd-messages.h"
11
12 #include "alloc-util.h"
13 #include "errno-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "float.h"
17 #include "hexdecoct.h"
18 #include "json-internal.h"
19 #include "json.h"
20 #include "macro.h"
21 #include "memory-util.h"
22 #include "string-table.h"
23 #include "string-util.h"
24 #include "strv.h"
25 #include "terminal-util.h"
26 #include "utf8.h"
27
28 /* Refuse putting together variants with a larger depth than 4K by default (as a protection against overflowing stacks
29 * if code processes JSON objects recursively. Note that we store the depth in an uint16_t, hence make sure this
30 * remains under 2^16.
31 * The value was 16k, but it was discovered to be too high on llvm/x86-64. See also the issue #10738. */
32 #define DEPTH_MAX (4U*1024U)
33 assert_cc(DEPTH_MAX <= UINT16_MAX);
34
35 typedef struct JsonSource {
36 /* When we parse from a file or similar, encodes the filename, to indicate the source of a json variant */
37 size_t n_ref;
38 unsigned max_line;
39 unsigned max_column;
40 char name[];
41 } JsonSource;
42
43 /* On x86-64 this whole structure should have a size of 6 * 64 bit = 48 bytes */
44 struct JsonVariant {
45 union {
46 /* We either maintain a reference counter for this variant itself, or we are embedded into an
47 * array/object, in which case only that surrounding object is ref-counted. (If 'embedded' is false,
48 * see below.) */
49 size_t n_ref;
50
51 /* If this JsonVariant is part of an array/object, then this field points to the surrounding
52 * JSON_VARIANT_ARRAY/JSON_VARIANT_OBJECT object. (If 'embedded' is true, see below.) */
53 JsonVariant *parent;
54 };
55
56 /* If this was parsed from some file or buffer, this stores where from, as well as the source line/column */
57 JsonSource *source;
58 unsigned line, column;
59
60 JsonVariantType type:5;
61
62 /* A marker whether this variant is embedded into in array/object or not. If true, the 'parent' pointer above
63 * is valid. If false, the 'n_ref' field above is valid instead. */
64 bool is_embedded:1;
65
66 /* In some conditions (for example, if this object is part of an array of strings or objects), we don't store
67 * any data inline, but instead simply reference an external object and act as surrogate of it. In that case
68 * this bool is set, and the external object is referenced through the .reference field below. */
69 bool is_reference:1;
70
71 /* While comparing two arrays, we use this for marking what we already have seen */
72 bool is_marked:1;
73
74 /* The current 'depth' of the JsonVariant, i.e. how many levels of member variants this has */
75 uint16_t depth;
76
77 union {
78 /* For simple types we store the value in-line. */
79 JsonValue value;
80
81 /* For objects and arrays we store the number of elements immediately following */
82 size_t n_elements;
83
84 /* If is_reference as indicated above is set, this is where the reference object is actually stored. */
85 JsonVariant *reference;
86
87 /* Strings are placed immediately after the structure. Note that when this is a JsonVariant embedded
88 * into an array we might encode strings up to INLINE_STRING_LENGTH characters directly inside the
89 * element, while longer strings are stored as references. When this object is not embedded into an
90 * array, but stand-alone we allocate the right size for the whole structure, i.e. the array might be
91 * much larger than INLINE_STRING_LENGTH.
92 *
93 * Note that because we want to allocate arrays of the JsonVariant structure we specify [0] here,
94 * rather than the prettier []. If we wouldn't, then this char array would have undefined size, and so
95 * would the union and then the struct this is included in. And of structures with undefined size we
96 * can't allocate arrays (at least not easily). */
97 char string[0];
98 };
99 };
100
101 /* Inside string arrays we have a series of JasonVariant structures one after the other. In this case, strings longer
102 * than INLINE_STRING_MAX are stored as references, and all shorter ones inline. (This means — on x86-64 — strings up
103 * to 15 chars are stored within the array elements, and all others in separate allocations) */
104 #define INLINE_STRING_MAX (sizeof(JsonVariant) - offsetof(JsonVariant, string) - 1U)
105
106 /* Let's make sure this structure isn't increased in size accidentally. This check is only for our most relevant arch
107 * (x86-64). */
108 #ifdef __x86_64__
109 assert_cc(sizeof(JsonVariant) == 48U);
110 assert_cc(INLINE_STRING_MAX == 15U);
111 #endif
112
113 static JsonSource* json_source_new(const char *name) {
114 JsonSource *s;
115
116 assert(name);
117
118 s = malloc(offsetof(JsonSource, name) + strlen(name) + 1);
119 if (!s)
120 return NULL;
121
122 *s = (JsonSource) {
123 .n_ref = 1,
124 };
125 strcpy(s->name, name);
126
127 return s;
128 }
129
130 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(JsonSource, json_source, mfree);
131
132 static bool json_source_equal(JsonSource *a, JsonSource *b) {
133 if (a == b)
134 return true;
135
136 if (!a || !b)
137 return false;
138
139 return streq(a->name, b->name);
140 }
141
142 DEFINE_TRIVIAL_CLEANUP_FUNC(JsonSource*, json_source_unref);
143
144 /* There are four kind of JsonVariant* pointers:
145 *
146 * 1. NULL
147 * 2. A 'regular' one, i.e. pointing to malloc() memory
148 * 3. A 'magic' one, i.e. one of the special JSON_VARIANT_MAGIC_XYZ values, that encode a few very basic values directly in the pointer.
149 * 4. A 'const string' one, i.e. a pointer to a const string.
150 *
151 * The four kinds of pointers can be discerned like this:
152 *
153 * Detecting #1 is easy, just compare with NULL. Detecting #3 is similarly easy: all magic pointers are below
154 * _JSON_VARIANT_MAGIC_MAX (which is pretty low, within the first memory page, which is special on Linux and other
155 * OSes, as it is a faulting page). In order to discern #2 and #4 we check the lowest bit. If it's off it's #2,
156 * otherwise #4. This makes use of the fact that malloc() will return "maximum aligned" memory, which definitely
157 * means the pointer is even. This means we can use the uneven pointers to reference static strings, as long as we
158 * make sure that all static strings used like this are aligned to 2 (or higher), and that we mask the bit on
159 * access. The JSON_VARIANT_STRING_CONST() macro encodes strings as JsonVariant* pointers, with the bit set. */
160
161 static bool json_variant_is_magic(const JsonVariant *v) {
162 if (!v)
163 return false;
164
165 return v < _JSON_VARIANT_MAGIC_MAX;
166 }
167
168 static bool json_variant_is_const_string(const JsonVariant *v) {
169
170 if (v < _JSON_VARIANT_MAGIC_MAX)
171 return false;
172
173 /* A proper JsonVariant is aligned to whatever malloc() aligns things too, which is definitely not uneven. We
174 * hence use all uneven pointers as indicators for const strings. */
175
176 return (((uintptr_t) v) & 1) != 0;
177 }
178
179 static bool json_variant_is_regular(const JsonVariant *v) {
180
181 if (v < _JSON_VARIANT_MAGIC_MAX)
182 return false;
183
184 return (((uintptr_t) v) & 1) == 0;
185 }
186
187 static JsonVariant *json_variant_dereference(JsonVariant *v) {
188
189 /* Recursively dereference variants that are references to other variants */
190
191 if (!v)
192 return NULL;
193
194 if (!json_variant_is_regular(v))
195 return v;
196
197 if (!v->is_reference)
198 return v;
199
200 return json_variant_dereference(v->reference);
201 }
202
203 static uint16_t json_variant_depth(JsonVariant *v) {
204
205 v = json_variant_dereference(v);
206 if (!v)
207 return 0;
208
209 if (!json_variant_is_regular(v))
210 return 0;
211
212 return v->depth;
213 }
214
215 static JsonVariant *json_variant_normalize(JsonVariant *v) {
216
217 /* Converts json variants to their normalized form, i.e. fully dereferenced and wherever possible converted to
218 * the "magic" version if there is one */
219
220 if (!v)
221 return NULL;
222
223 v = json_variant_dereference(v);
224
225 switch (json_variant_type(v)) {
226
227 case JSON_VARIANT_BOOLEAN:
228 return json_variant_boolean(v) ? JSON_VARIANT_MAGIC_TRUE : JSON_VARIANT_MAGIC_FALSE;
229
230 case JSON_VARIANT_NULL:
231 return JSON_VARIANT_MAGIC_NULL;
232
233 case JSON_VARIANT_INTEGER:
234 return json_variant_integer(v) == 0 ? JSON_VARIANT_MAGIC_ZERO_INTEGER : v;
235
236 case JSON_VARIANT_UNSIGNED:
237 return json_variant_unsigned(v) == 0 ? JSON_VARIANT_MAGIC_ZERO_UNSIGNED : v;
238
239 case JSON_VARIANT_REAL:
240 #pragma GCC diagnostic push
241 #pragma GCC diagnostic ignored "-Wfloat-equal"
242 return json_variant_real(v) == 0.0 ? JSON_VARIANT_MAGIC_ZERO_REAL : v;
243 #pragma GCC diagnostic pop
244
245 case JSON_VARIANT_STRING:
246 return isempty(json_variant_string(v)) ? JSON_VARIANT_MAGIC_EMPTY_STRING : v;
247
248 case JSON_VARIANT_ARRAY:
249 return json_variant_elements(v) == 0 ? JSON_VARIANT_MAGIC_EMPTY_ARRAY : v;
250
251 case JSON_VARIANT_OBJECT:
252 return json_variant_elements(v) == 0 ? JSON_VARIANT_MAGIC_EMPTY_OBJECT : v;
253
254 default:
255 return v;
256 }
257 }
258
259 static JsonVariant *json_variant_conservative_normalize(JsonVariant *v) {
260
261 /* Much like json_variant_normalize(), but won't simplify if the variant has a source/line location attached to
262 * it, in order not to lose context */
263
264 if (!v)
265 return NULL;
266
267 if (!json_variant_is_regular(v))
268 return v;
269
270 if (v->source || v->line > 0 || v->column > 0)
271 return v;
272
273 return json_variant_normalize(v);
274 }
275
276 static int json_variant_new(JsonVariant **ret, JsonVariantType type, size_t space) {
277 JsonVariant *v;
278
279 assert_return(ret, -EINVAL);
280
281 v = malloc0(MAX(sizeof(JsonVariant),
282 offsetof(JsonVariant, value) + space));
283 if (!v)
284 return -ENOMEM;
285
286 v->n_ref = 1;
287 v->type = type;
288
289 *ret = v;
290 return 0;
291 }
292
293 int json_variant_new_integer(JsonVariant **ret, intmax_t i) {
294 JsonVariant *v;
295 int r;
296
297 assert_return(ret, -EINVAL);
298
299 if (i == 0) {
300 *ret = JSON_VARIANT_MAGIC_ZERO_INTEGER;
301 return 0;
302 }
303
304 r = json_variant_new(&v, JSON_VARIANT_INTEGER, sizeof(i));
305 if (r < 0)
306 return r;
307
308 v->value.integer = i;
309 *ret = v;
310
311 return 0;
312 }
313
314 int json_variant_new_unsigned(JsonVariant **ret, uintmax_t u) {
315 JsonVariant *v;
316 int r;
317
318 assert_return(ret, -EINVAL);
319 if (u == 0) {
320 *ret = JSON_VARIANT_MAGIC_ZERO_UNSIGNED;
321 return 0;
322 }
323
324 r = json_variant_new(&v, JSON_VARIANT_UNSIGNED, sizeof(u));
325 if (r < 0)
326 return r;
327
328 v->value.unsig = u;
329 *ret = v;
330
331 return 0;
332 }
333
334 int json_variant_new_real(JsonVariant **ret, long double d) {
335 JsonVariant *v;
336 int r;
337
338 assert_return(ret, -EINVAL);
339
340 #pragma GCC diagnostic push
341 #pragma GCC diagnostic ignored "-Wfloat-equal"
342 if (d == 0.0) {
343 #pragma GCC diagnostic pop
344 *ret = JSON_VARIANT_MAGIC_ZERO_REAL;
345 return 0;
346 }
347
348 r = json_variant_new(&v, JSON_VARIANT_REAL, sizeof(d));
349 if (r < 0)
350 return r;
351
352 v->value.real = d;
353 *ret = v;
354
355 return 0;
356 }
357
358 int json_variant_new_boolean(JsonVariant **ret, bool b) {
359 assert_return(ret, -EINVAL);
360
361 if (b)
362 *ret = JSON_VARIANT_MAGIC_TRUE;
363 else
364 *ret = JSON_VARIANT_MAGIC_FALSE;
365
366 return 0;
367 }
368
369 int json_variant_new_null(JsonVariant **ret) {
370 assert_return(ret, -EINVAL);
371
372 *ret = JSON_VARIANT_MAGIC_NULL;
373 return 0;
374 }
375
376 int json_variant_new_stringn(JsonVariant **ret, const char *s, size_t n) {
377 JsonVariant *v;
378 int r;
379
380 assert_return(ret, -EINVAL);
381 if (!s) {
382 assert_return(IN_SET(n, 0, (size_t) -1), -EINVAL);
383 return json_variant_new_null(ret);
384 }
385 if (n == (size_t) -1) /* determine length automatically */
386 n = strlen(s);
387 else if (memchr(s, 0, n)) /* don't allow embedded NUL, as we can't express that in JSON */
388 return -EINVAL;
389 if (n == 0) {
390 *ret = JSON_VARIANT_MAGIC_EMPTY_STRING;
391 return 0;
392 }
393
394 r = json_variant_new(&v, JSON_VARIANT_STRING, n + 1);
395 if (r < 0)
396 return r;
397
398 memcpy(v->string, s, n);
399 v->string[n] = 0;
400
401 *ret = v;
402 return 0;
403 }
404
405 static void json_variant_set(JsonVariant *a, JsonVariant *b) {
406 assert(a);
407
408 b = json_variant_dereference(b);
409 if (!b) {
410 a->type = JSON_VARIANT_NULL;
411 return;
412 }
413
414 a->type = json_variant_type(b);
415 switch (a->type) {
416
417 case JSON_VARIANT_INTEGER:
418 a->value.integer = json_variant_integer(b);
419 break;
420
421 case JSON_VARIANT_UNSIGNED:
422 a->value.unsig = json_variant_unsigned(b);
423 break;
424
425 case JSON_VARIANT_REAL:
426 a->value.real = json_variant_real(b);
427 break;
428
429 case JSON_VARIANT_BOOLEAN:
430 a->value.boolean = json_variant_boolean(b);
431 break;
432
433 case JSON_VARIANT_STRING: {
434 const char *s;
435
436 assert_se(s = json_variant_string(b));
437
438 /* Short strings we can store inline */
439 if (strnlen(s, INLINE_STRING_MAX+1) <= INLINE_STRING_MAX) {
440 strcpy(a->string, s);
441 break;
442 }
443
444 /* For longer strings, use a reference… */
445 _fallthrough_;
446 }
447
448 case JSON_VARIANT_ARRAY:
449 case JSON_VARIANT_OBJECT:
450 a->is_reference = true;
451 a->reference = json_variant_ref(json_variant_conservative_normalize(b));
452 break;
453
454 case JSON_VARIANT_NULL:
455 break;
456
457 default:
458 assert_not_reached("Unexpected variant type");
459 }
460 }
461
462 static void json_variant_copy_source(JsonVariant *v, JsonVariant *from) {
463 assert(v);
464 assert(from);
465
466 if (!json_variant_is_regular(from))
467 return;
468
469 v->line = from->line;
470 v->column = from->column;
471 v->source = json_source_ref(from->source);
472 }
473
474 int json_variant_new_array(JsonVariant **ret, JsonVariant **array, size_t n) {
475 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
476
477 assert_return(ret, -EINVAL);
478 if (n == 0) {
479 *ret = JSON_VARIANT_MAGIC_EMPTY_ARRAY;
480 return 0;
481 }
482 assert_return(array, -EINVAL);
483
484 v = new(JsonVariant, n + 1);
485 if (!v)
486 return -ENOMEM;
487
488 *v = (JsonVariant) {
489 .n_ref = 1,
490 .type = JSON_VARIANT_ARRAY,
491 };
492
493 for (v->n_elements = 0; v->n_elements < n; v->n_elements++) {
494 JsonVariant *w = v + 1 + v->n_elements,
495 *c = array[v->n_elements];
496 uint16_t d;
497
498 d = json_variant_depth(c);
499 if (d >= DEPTH_MAX) /* Refuse too deep nesting */
500 return -ELNRNG;
501 if (d >= v->depth)
502 v->depth = d + 1;
503
504 *w = (JsonVariant) {
505 .is_embedded = true,
506 .parent = v,
507 };
508
509 json_variant_set(w, c);
510 json_variant_copy_source(w, c);
511 }
512
513 *ret = TAKE_PTR(v);
514 return 0;
515 }
516
517 int json_variant_new_array_bytes(JsonVariant **ret, const void *p, size_t n) {
518 JsonVariant *v;
519 size_t i;
520
521 assert_return(ret, -EINVAL);
522 if (n == 0) {
523 *ret = JSON_VARIANT_MAGIC_EMPTY_ARRAY;
524 return 0;
525 }
526 assert_return(p, -EINVAL);
527
528 v = new(JsonVariant, n + 1);
529 if (!v)
530 return -ENOMEM;
531
532 *v = (JsonVariant) {
533 .n_ref = 1,
534 .type = JSON_VARIANT_ARRAY,
535 .n_elements = n,
536 .depth = 1,
537 };
538
539 for (i = 0; i < n; i++) {
540 JsonVariant *w = v + 1 + i;
541
542 *w = (JsonVariant) {
543 .is_embedded = true,
544 .parent = v,
545 .type = JSON_VARIANT_UNSIGNED,
546 .value.unsig = ((const uint8_t*) p)[i],
547 };
548 }
549
550 *ret = v;
551 return 0;
552 }
553
554 int json_variant_new_array_strv(JsonVariant **ret, char **l) {
555 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
556 size_t n;
557 int r;
558
559 assert(ret);
560
561 n = strv_length(l);
562 if (n == 0) {
563 *ret = JSON_VARIANT_MAGIC_EMPTY_ARRAY;
564 return 0;
565 }
566
567 v = new(JsonVariant, n + 1);
568 if (!v)
569 return -ENOMEM;
570
571 *v = (JsonVariant) {
572 .n_ref = 1,
573 .type = JSON_VARIANT_ARRAY,
574 .depth = 1,
575 };
576
577 for (v->n_elements = 0; v->n_elements < n; v->n_elements++) {
578 JsonVariant *w = v + 1 + v->n_elements;
579 size_t k;
580
581 *w = (JsonVariant) {
582 .is_embedded = true,
583 .parent = v,
584 .type = JSON_VARIANT_STRING,
585 };
586
587 k = strlen(l[v->n_elements]);
588
589 if (k > INLINE_STRING_MAX) {
590 /* If string is too long, store it as reference. */
591
592 r = json_variant_new_string(&w->reference, l[v->n_elements]);
593 if (r < 0)
594 return r;
595
596 w->is_reference = true;
597 } else
598 memcpy(w->string, l[v->n_elements], k+1);
599 }
600
601 *ret = TAKE_PTR(v);
602 return 0;
603 }
604
605 int json_variant_new_object(JsonVariant **ret, JsonVariant **array, size_t n) {
606 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
607
608 assert_return(ret, -EINVAL);
609 if (n == 0) {
610 *ret = JSON_VARIANT_MAGIC_EMPTY_OBJECT;
611 return 0;
612 }
613 assert_return(array, -EINVAL);
614 assert_return(n % 2 == 0, -EINVAL);
615
616 v = new(JsonVariant, n + 1);
617 if (!v)
618 return -ENOMEM;
619
620 *v = (JsonVariant) {
621 .n_ref = 1,
622 .type = JSON_VARIANT_OBJECT,
623 };
624
625 for (v->n_elements = 0; v->n_elements < n; v->n_elements++) {
626 JsonVariant *w = v + 1 + v->n_elements,
627 *c = array[v->n_elements];
628 uint16_t d;
629
630 if ((v->n_elements & 1) == 0 &&
631 !json_variant_is_string(c))
632 return -EINVAL; /* Every second one needs to be a string, as it is the key name */
633
634 d = json_variant_depth(c);
635 if (d >= DEPTH_MAX) /* Refuse too deep nesting */
636 return -ELNRNG;
637 if (d >= v->depth)
638 v->depth = d + 1;
639
640 *w = (JsonVariant) {
641 .is_embedded = true,
642 .parent = v,
643 };
644
645 json_variant_set(w, c);
646 json_variant_copy_source(w, c);
647 }
648
649 *ret = TAKE_PTR(v);
650 return 0;
651 }
652
653 static void json_variant_free_inner(JsonVariant *v) {
654 assert(v);
655
656 if (!json_variant_is_regular(v))
657 return;
658
659 json_source_unref(v->source);
660
661 if (v->is_reference) {
662 json_variant_unref(v->reference);
663 return;
664 }
665
666 if (IN_SET(v->type, JSON_VARIANT_ARRAY, JSON_VARIANT_OBJECT)) {
667 size_t i;
668
669 for (i = 0; i < v->n_elements; i++)
670 json_variant_free_inner(v + 1 + i);
671 }
672 }
673
674 JsonVariant *json_variant_ref(JsonVariant *v) {
675 if (!v)
676 return NULL;
677 if (!json_variant_is_regular(v))
678 return v;
679
680 if (v->is_embedded)
681 json_variant_ref(v->parent); /* ref the compounding variant instead */
682 else {
683 assert(v->n_ref > 0);
684 v->n_ref++;
685 }
686
687 return v;
688 }
689
690 JsonVariant *json_variant_unref(JsonVariant *v) {
691 if (!v)
692 return NULL;
693 if (!json_variant_is_regular(v))
694 return NULL;
695
696 if (v->is_embedded)
697 json_variant_unref(v->parent);
698 else {
699 assert(v->n_ref > 0);
700 v->n_ref--;
701
702 if (v->n_ref == 0) {
703 json_variant_free_inner(v);
704 free(v);
705 }
706 }
707
708 return NULL;
709 }
710
711 void json_variant_unref_many(JsonVariant **array, size_t n) {
712 size_t i;
713
714 assert(array || n == 0);
715
716 for (i = 0; i < n; i++)
717 json_variant_unref(array[i]);
718 }
719
720 const char *json_variant_string(JsonVariant *v) {
721 if (!v)
722 return NULL;
723 if (v == JSON_VARIANT_MAGIC_EMPTY_STRING)
724 return "";
725 if (json_variant_is_magic(v))
726 goto mismatch;
727 if (json_variant_is_const_string(v)) {
728 uintptr_t p = (uintptr_t) v;
729
730 assert((p & 1) != 0);
731 return (const char*) (p ^ 1U);
732 }
733
734 if (v->is_reference)
735 return json_variant_string(v->reference);
736 if (v->type != JSON_VARIANT_STRING)
737 goto mismatch;
738
739 return v->string;
740
741 mismatch:
742 log_debug("Non-string JSON variant requested as string, returning NULL.");
743 return NULL;
744 }
745
746 bool json_variant_boolean(JsonVariant *v) {
747 if (!v)
748 goto mismatch;
749 if (v == JSON_VARIANT_MAGIC_TRUE)
750 return true;
751 if (v == JSON_VARIANT_MAGIC_FALSE)
752 return false;
753 if (!json_variant_is_regular(v))
754 goto mismatch;
755 if (v->type != JSON_VARIANT_BOOLEAN)
756 goto mismatch;
757 if (v->is_reference)
758 return json_variant_boolean(v->reference);
759
760 return v->value.boolean;
761
762 mismatch:
763 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
764 return false;
765 }
766
767 intmax_t json_variant_integer(JsonVariant *v) {
768 if (!v)
769 goto mismatch;
770 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
771 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
772 v == JSON_VARIANT_MAGIC_ZERO_REAL)
773 return 0;
774 if (!json_variant_is_regular(v))
775 goto mismatch;
776 if (v->is_reference)
777 return json_variant_integer(v->reference);
778
779 switch (v->type) {
780
781 case JSON_VARIANT_INTEGER:
782 return v->value.integer;
783
784 case JSON_VARIANT_UNSIGNED:
785 if (v->value.unsig <= INTMAX_MAX)
786 return (intmax_t) v->value.unsig;
787
788 log_debug("Unsigned integer %ju requested as signed integer and out of range, returning 0.", v->value.unsig);
789 return 0;
790
791 case JSON_VARIANT_REAL: {
792 intmax_t converted;
793
794 converted = (intmax_t) v->value.real;
795
796 #pragma GCC diagnostic push
797 #pragma GCC diagnostic ignored "-Wfloat-equal"
798 if ((long double) converted == v->value.real)
799 #pragma GCC diagnostic pop
800 return converted;
801
802 log_debug("Real %Lg requested as integer, and cannot be converted losslessly, returning 0.", v->value.real);
803 return 0;
804 }
805
806 default:
807 break;
808 }
809
810 mismatch:
811 log_debug("Non-integer JSON variant requested as integer, returning 0.");
812 return 0;
813 }
814
815 uintmax_t json_variant_unsigned(JsonVariant *v) {
816 if (!v)
817 goto mismatch;
818 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
819 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
820 v == JSON_VARIANT_MAGIC_ZERO_REAL)
821 return 0;
822 if (!json_variant_is_regular(v))
823 goto mismatch;
824 if (v->is_reference)
825 return json_variant_integer(v->reference);
826
827 switch (v->type) {
828
829 case JSON_VARIANT_INTEGER:
830 if (v->value.integer >= 0)
831 return (uintmax_t) v->value.integer;
832
833 log_debug("Signed integer %ju requested as unsigned integer and out of range, returning 0.", v->value.integer);
834 return 0;
835
836 case JSON_VARIANT_UNSIGNED:
837 return v->value.unsig;
838
839 case JSON_VARIANT_REAL: {
840 uintmax_t converted;
841
842 converted = (uintmax_t) v->value.real;
843
844 #pragma GCC diagnostic push
845 #pragma GCC diagnostic ignored "-Wfloat-equal"
846 if ((long double) converted == v->value.real)
847 #pragma GCC diagnostic pop
848 return converted;
849
850 log_debug("Real %Lg requested as unsigned integer, and cannot be converted losslessly, returning 0.", v->value.real);
851 return 0;
852 }
853
854 default:
855 break;
856 }
857
858 mismatch:
859 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
860 return 0;
861 }
862
863 long double json_variant_real(JsonVariant *v) {
864 if (!v)
865 return 0.0;
866 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
867 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
868 v == JSON_VARIANT_MAGIC_ZERO_REAL)
869 return 0.0;
870 if (!json_variant_is_regular(v))
871 goto mismatch;
872 if (v->is_reference)
873 return json_variant_real(v->reference);
874
875 switch (v->type) {
876
877 case JSON_VARIANT_REAL:
878 return v->value.real;
879
880 case JSON_VARIANT_INTEGER: {
881 long double converted;
882
883 converted = (long double) v->value.integer;
884
885 if ((intmax_t) converted == v->value.integer)
886 return converted;
887
888 log_debug("Signed integer %ji requested as real, and cannot be converted losslessly, returning 0.", v->value.integer);
889 return 0.0;
890 }
891
892 case JSON_VARIANT_UNSIGNED: {
893 long double converted;
894
895 converted = (long double) v->value.unsig;
896
897 if ((uintmax_t) converted == v->value.unsig)
898 return converted;
899
900 log_debug("Unsigned integer %ju requested as real, and cannot be converted losslessly, returning 0.", v->value.unsig);
901 return 0.0;
902 }
903
904 default:
905 break;
906 }
907
908 mismatch:
909 log_debug("Non-integer JSON variant requested as integer, returning 0.");
910 return 0.0;
911 }
912
913 bool json_variant_is_negative(JsonVariant *v) {
914 if (!v)
915 goto mismatch;
916 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
917 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
918 v == JSON_VARIANT_MAGIC_ZERO_REAL)
919 return false;
920 if (!json_variant_is_regular(v))
921 goto mismatch;
922 if (v->is_reference)
923 return json_variant_is_negative(v->reference);
924
925 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
926 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
927 * values. */
928
929 switch (v->type) {
930
931 case JSON_VARIANT_REAL:
932 return v->value.real < 0;
933
934 case JSON_VARIANT_INTEGER:
935 return v->value.integer < 0;
936
937 case JSON_VARIANT_UNSIGNED:
938 return false;
939
940 default:
941 break;
942 }
943
944 mismatch:
945 log_debug("Non-integer JSON variant tested for negativity, returning false.");
946 return false;
947 }
948
949 JsonVariantType json_variant_type(JsonVariant *v) {
950
951 if (!v)
952 return _JSON_VARIANT_TYPE_INVALID;
953
954 if (json_variant_is_const_string(v))
955 return JSON_VARIANT_STRING;
956
957 if (v == JSON_VARIANT_MAGIC_TRUE || v == JSON_VARIANT_MAGIC_FALSE)
958 return JSON_VARIANT_BOOLEAN;
959
960 if (v == JSON_VARIANT_MAGIC_NULL)
961 return JSON_VARIANT_NULL;
962
963 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER)
964 return JSON_VARIANT_INTEGER;
965
966 if (v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED)
967 return JSON_VARIANT_UNSIGNED;
968
969 if (v == JSON_VARIANT_MAGIC_ZERO_REAL)
970 return JSON_VARIANT_REAL;
971
972 if (v == JSON_VARIANT_MAGIC_EMPTY_STRING)
973 return JSON_VARIANT_STRING;
974
975 if (v == JSON_VARIANT_MAGIC_EMPTY_ARRAY)
976 return JSON_VARIANT_ARRAY;
977
978 if (v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
979 return JSON_VARIANT_OBJECT;
980
981 return v->type;
982 }
983
984 bool json_variant_has_type(JsonVariant *v, JsonVariantType type) {
985 JsonVariantType rt;
986
987 v = json_variant_dereference(v);
988 if (!v)
989 return false;
990
991 rt = json_variant_type(v);
992 if (rt == type)
993 return true;
994
995 /* If it's a const string, then it only can be a string, and if it is not, it's not */
996 if (json_variant_is_const_string(v))
997 return false;
998
999 /* All three magic zeroes qualify as integer, unsigned and as real */
1000 if ((v == JSON_VARIANT_MAGIC_ZERO_INTEGER || v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED || v == JSON_VARIANT_MAGIC_ZERO_REAL) &&
1001 IN_SET(type, JSON_VARIANT_INTEGER, JSON_VARIANT_UNSIGNED, JSON_VARIANT_REAL, JSON_VARIANT_NUMBER))
1002 return true;
1003
1004 /* All other magic variant types are only equal to themselves */
1005 if (json_variant_is_magic(v))
1006 return false;
1007
1008 /* Handle the "number" pseudo type */
1009 if (type == JSON_VARIANT_NUMBER)
1010 return IN_SET(rt, JSON_VARIANT_INTEGER, JSON_VARIANT_UNSIGNED, JSON_VARIANT_REAL);
1011
1012 /* Integer conversions are OK in many cases */
1013 if (rt == JSON_VARIANT_INTEGER && type == JSON_VARIANT_UNSIGNED)
1014 return v->value.integer >= 0;
1015 if (rt == JSON_VARIANT_UNSIGNED && type == JSON_VARIANT_INTEGER)
1016 return v->value.unsig <= INTMAX_MAX;
1017
1018 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1019 if (rt == JSON_VARIANT_INTEGER && type == JSON_VARIANT_REAL)
1020 return (intmax_t) (long double) v->value.integer == v->value.integer;
1021 if (rt == JSON_VARIANT_UNSIGNED && type == JSON_VARIANT_REAL)
1022 return (uintmax_t) (long double) v->value.unsig == v->value.unsig;
1023
1024 #pragma GCC diagnostic push
1025 #pragma GCC diagnostic ignored "-Wfloat-equal"
1026 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1027 if (rt == JSON_VARIANT_REAL && type == JSON_VARIANT_INTEGER)
1028 return (long double) (intmax_t) v->value.real == v->value.real;
1029 if (rt == JSON_VARIANT_REAL && type == JSON_VARIANT_UNSIGNED)
1030 return (long double) (uintmax_t) v->value.real == v->value.real;
1031 #pragma GCC diagnostic pop
1032
1033 return false;
1034 }
1035
1036 size_t json_variant_elements(JsonVariant *v) {
1037 if (!v)
1038 return 0;
1039 if (v == JSON_VARIANT_MAGIC_EMPTY_ARRAY ||
1040 v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
1041 return 0;
1042 if (!json_variant_is_regular(v))
1043 goto mismatch;
1044 if (!IN_SET(v->type, JSON_VARIANT_ARRAY, JSON_VARIANT_OBJECT))
1045 goto mismatch;
1046 if (v->is_reference)
1047 return json_variant_elements(v->reference);
1048
1049 return v->n_elements;
1050
1051 mismatch:
1052 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1053 return 0;
1054 }
1055
1056 JsonVariant *json_variant_by_index(JsonVariant *v, size_t idx) {
1057 if (!v)
1058 return NULL;
1059 if (v == JSON_VARIANT_MAGIC_EMPTY_ARRAY ||
1060 v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
1061 return NULL;
1062 if (!json_variant_is_regular(v))
1063 goto mismatch;
1064 if (!IN_SET(v->type, JSON_VARIANT_ARRAY, JSON_VARIANT_OBJECT))
1065 goto mismatch;
1066 if (v->is_reference)
1067 return json_variant_by_index(v->reference, idx);
1068 if (idx >= v->n_elements)
1069 return NULL;
1070
1071 return json_variant_conservative_normalize(v + 1 + idx);
1072
1073 mismatch:
1074 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1075 return NULL;
1076 }
1077
1078 JsonVariant *json_variant_by_key_full(JsonVariant *v, const char *key, JsonVariant **ret_key) {
1079 size_t i;
1080
1081 if (!v)
1082 goto not_found;
1083 if (!key)
1084 goto not_found;
1085 if (v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
1086 goto not_found;
1087 if (!json_variant_is_regular(v))
1088 goto mismatch;
1089 if (v->type != JSON_VARIANT_OBJECT)
1090 goto mismatch;
1091 if (v->is_reference)
1092 return json_variant_by_key(v->reference, key);
1093
1094 for (i = 0; i < v->n_elements; i += 2) {
1095 JsonVariant *p;
1096
1097 p = json_variant_dereference(v + 1 + i);
1098
1099 if (!json_variant_has_type(p, JSON_VARIANT_STRING))
1100 continue;
1101
1102 if (streq(json_variant_string(p), key)) {
1103
1104 if (ret_key)
1105 *ret_key = json_variant_conservative_normalize(v + 1 + i);
1106
1107 return json_variant_conservative_normalize(v + 1 + i + 1);
1108 }
1109 }
1110
1111 not_found:
1112 if (ret_key)
1113 *ret_key = NULL;
1114
1115 return NULL;
1116
1117 mismatch:
1118 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1119 if (ret_key)
1120 *ret_key = NULL;
1121
1122 return NULL;
1123 }
1124
1125 JsonVariant *json_variant_by_key(JsonVariant *v, const char *key) {
1126 return json_variant_by_key_full(v, key, NULL);
1127 }
1128
1129 bool json_variant_equal(JsonVariant *a, JsonVariant *b) {
1130 JsonVariantType t;
1131
1132 a = json_variant_normalize(a);
1133 b = json_variant_normalize(b);
1134
1135 if (a == b)
1136 return true;
1137
1138 t = json_variant_type(a);
1139 if (!json_variant_has_type(b, t))
1140 return false;
1141
1142 switch (t) {
1143
1144 case JSON_VARIANT_STRING:
1145 return streq(json_variant_string(a), json_variant_string(b));
1146
1147 case JSON_VARIANT_INTEGER:
1148 return json_variant_integer(a) == json_variant_integer(b);
1149
1150 case JSON_VARIANT_UNSIGNED:
1151 return json_variant_unsigned(a) == json_variant_unsigned(b);
1152
1153 case JSON_VARIANT_REAL:
1154 #pragma GCC diagnostic push
1155 #pragma GCC diagnostic ignored "-Wfloat-equal"
1156 return json_variant_real(a) == json_variant_real(b);
1157 #pragma GCC diagnostic pop
1158
1159 case JSON_VARIANT_BOOLEAN:
1160 return json_variant_boolean(a) == json_variant_boolean(b);
1161
1162 case JSON_VARIANT_NULL:
1163 return true;
1164
1165 case JSON_VARIANT_ARRAY: {
1166 size_t i, n;
1167
1168 n = json_variant_elements(a);
1169 if (n != json_variant_elements(b))
1170 return false;
1171
1172 for (i = 0; i < n; i++) {
1173 if (!json_variant_equal(json_variant_by_index(a, i), json_variant_by_index(b, i)))
1174 return false;
1175 }
1176
1177 return true;
1178 }
1179
1180 case JSON_VARIANT_OBJECT: {
1181 size_t i, n;
1182
1183 n = json_variant_elements(a);
1184 if (n != json_variant_elements(b))
1185 return false;
1186
1187 /* Iterate through all keys in 'a' */
1188 for (i = 0; i < n; i += 2) {
1189 bool found = false;
1190 size_t j;
1191
1192 /* Match them against all keys in 'b' */
1193 for (j = 0; j < n; j += 2) {
1194 JsonVariant *key_b;
1195
1196 key_b = json_variant_by_index(b, j);
1197
1198 /* During the first iteration unmark everything */
1199 if (i == 0)
1200 key_b->is_marked = false;
1201 else if (key_b->is_marked) /* In later iterations if we already marked something, don't bother with it again */
1202 continue;
1203
1204 if (found)
1205 continue;
1206
1207 if (json_variant_equal(json_variant_by_index(a, i), key_b) &&
1208 json_variant_equal(json_variant_by_index(a, i+1), json_variant_by_index(b, j+1))) {
1209 /* Key and values match! */
1210 key_b->is_marked = found = true;
1211
1212 /* In the first iteration we continue the inner loop since we want to mark
1213 * everything, otherwise exit the loop quickly after we found what we were
1214 * looking for. */
1215 if (i != 0)
1216 break;
1217 }
1218 }
1219
1220 if (!found)
1221 return false;
1222 }
1223
1224 return true;
1225 }
1226
1227 default:
1228 assert_not_reached("Unknown variant type.");
1229 }
1230 }
1231
1232 int json_variant_get_source(JsonVariant *v, const char **ret_source, unsigned *ret_line, unsigned *ret_column) {
1233 assert_return(v, -EINVAL);
1234
1235 if (ret_source)
1236 *ret_source = json_variant_is_regular(v) && v->source ? v->source->name : NULL;
1237
1238 if (ret_line)
1239 *ret_line = json_variant_is_regular(v) ? v->line : 0;
1240
1241 if (ret_column)
1242 *ret_column = json_variant_is_regular(v) ? v->column : 0;
1243
1244 return 0;
1245 }
1246
1247 static int print_source(FILE *f, JsonVariant *v, JsonFormatFlags flags, bool whitespace) {
1248 size_t w, k;
1249
1250 if (!FLAGS_SET(flags, JSON_FORMAT_SOURCE|JSON_FORMAT_PRETTY))
1251 return 0;
1252
1253 if (!json_variant_is_regular(v))
1254 return 0;
1255
1256 if (!v->source && v->line == 0 && v->column == 0)
1257 return 0;
1258
1259 /* The max width we need to format the line numbers for this source file */
1260 w = (v->source && v->source->max_line > 0) ?
1261 DECIMAL_STR_WIDTH(v->source->max_line) :
1262 DECIMAL_STR_MAX(unsigned)-1;
1263 k = (v->source && v->source->max_column > 0) ?
1264 DECIMAL_STR_WIDTH(v->source->max_column) :
1265 DECIMAL_STR_MAX(unsigned) -1;
1266
1267 if (whitespace) {
1268 size_t i, n;
1269
1270 n = 1 + (v->source ? strlen(v->source->name) : 0) +
1271 ((v->source && (v->line > 0 || v->column > 0)) ? 1 : 0) +
1272 (v->line > 0 ? w : 0) +
1273 (((v->source || v->line > 0) && v->column > 0) ? 1 : 0) +
1274 (v->column > 0 ? k : 0) +
1275 2;
1276
1277 for (i = 0; i < n; i++)
1278 fputc(' ', f);
1279 } else {
1280 fputc('[', f);
1281
1282 if (v->source)
1283 fputs(v->source->name, f);
1284 if (v->source && (v->line > 0 || v->column > 0))
1285 fputc(':', f);
1286 if (v->line > 0)
1287 fprintf(f, "%*u", (int) w, v->line);
1288 if ((v->source || v->line > 0) || v->column > 0)
1289 fputc(':', f);
1290 if (v->column > 0)
1291 fprintf(f, "%*u", (int) k, v->column);
1292
1293 fputc(']', f);
1294 fputc(' ', f);
1295 }
1296
1297 return 0;
1298 }
1299
1300 static int json_format(FILE *f, JsonVariant *v, JsonFormatFlags flags, const char *prefix) {
1301 int r;
1302
1303 assert(f);
1304 assert(v);
1305
1306 switch (json_variant_type(v)) {
1307
1308 case JSON_VARIANT_REAL: {
1309 locale_t loc;
1310
1311 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
1312 if (loc == (locale_t) 0)
1313 return -errno;
1314
1315 if (flags & JSON_FORMAT_COLOR)
1316 fputs(ANSI_HIGHLIGHT_BLUE, f);
1317
1318 fprintf(f, "%.*Le", DECIMAL_DIG, json_variant_real(v));
1319
1320 if (flags & JSON_FORMAT_COLOR)
1321 fputs(ANSI_NORMAL, f);
1322
1323 freelocale(loc);
1324 break;
1325 }
1326
1327 case JSON_VARIANT_INTEGER:
1328 if (flags & JSON_FORMAT_COLOR)
1329 fputs(ANSI_HIGHLIGHT_BLUE, f);
1330
1331 fprintf(f, "%" PRIdMAX, json_variant_integer(v));
1332
1333 if (flags & JSON_FORMAT_COLOR)
1334 fputs(ANSI_NORMAL, f);
1335 break;
1336
1337 case JSON_VARIANT_UNSIGNED:
1338 if (flags & JSON_FORMAT_COLOR)
1339 fputs(ANSI_HIGHLIGHT_BLUE, f);
1340
1341 fprintf(f, "%" PRIuMAX, json_variant_unsigned(v));
1342
1343 if (flags & JSON_FORMAT_COLOR)
1344 fputs(ANSI_NORMAL, f);
1345 break;
1346
1347 case JSON_VARIANT_BOOLEAN:
1348
1349 if (flags & JSON_FORMAT_COLOR)
1350 fputs(ANSI_HIGHLIGHT, f);
1351
1352 if (json_variant_boolean(v))
1353 fputs("true", f);
1354 else
1355 fputs("false", f);
1356
1357 if (flags & JSON_FORMAT_COLOR)
1358 fputs(ANSI_NORMAL, f);
1359
1360 break;
1361
1362 case JSON_VARIANT_NULL:
1363 if (flags & JSON_FORMAT_COLOR)
1364 fputs(ANSI_HIGHLIGHT, f);
1365
1366 fputs("null", f);
1367
1368 if (flags & JSON_FORMAT_COLOR)
1369 fputs(ANSI_NORMAL, f);
1370 break;
1371
1372 case JSON_VARIANT_STRING: {
1373 const char *q;
1374
1375 fputc('"', f);
1376
1377 if (flags & JSON_FORMAT_COLOR)
1378 fputs(ANSI_GREEN, f);
1379
1380 for (q = json_variant_string(v); *q; q++) {
1381
1382 switch (*q) {
1383
1384 case '"':
1385 fputs("\\\"", f);
1386 break;
1387
1388 case '\\':
1389 fputs("\\\\", f);
1390 break;
1391
1392 case '\b':
1393 fputs("\\b", f);
1394 break;
1395
1396 case '\f':
1397 fputs("\\f", f);
1398 break;
1399
1400 case '\n':
1401 fputs("\\n", f);
1402 break;
1403
1404 case '\r':
1405 fputs("\\r", f);
1406 break;
1407
1408 case '\t':
1409 fputs("\\t", f);
1410 break;
1411
1412 default:
1413 if ((signed char) *q >= 0 && *q < ' ')
1414 fprintf(f, "\\u%04x", *q);
1415 else
1416 fputc(*q, f);
1417 break;
1418 }
1419 }
1420
1421 if (flags & JSON_FORMAT_COLOR)
1422 fputs(ANSI_NORMAL, f);
1423
1424 fputc('"', f);
1425 break;
1426 }
1427
1428 case JSON_VARIANT_ARRAY: {
1429 size_t i, n;
1430
1431 n = json_variant_elements(v);
1432
1433 if (n == 0)
1434 fputs("[]", f);
1435 else {
1436 _cleanup_free_ char *joined = NULL;
1437 const char *prefix2;
1438
1439 if (flags & JSON_FORMAT_PRETTY) {
1440 joined = strjoin(strempty(prefix), "\t");
1441 if (!joined)
1442 return -ENOMEM;
1443
1444 prefix2 = joined;
1445 fputs("[\n", f);
1446 } else {
1447 prefix2 = strempty(prefix);
1448 fputc('[', f);
1449 }
1450
1451 for (i = 0; i < n; i++) {
1452 JsonVariant *e;
1453
1454 assert_se(e = json_variant_by_index(v, i));
1455
1456 if (i > 0) {
1457 if (flags & JSON_FORMAT_PRETTY)
1458 fputs(",\n", f);
1459 else
1460 fputc(',', f);
1461 }
1462
1463 if (flags & JSON_FORMAT_PRETTY) {
1464 print_source(f, e, flags, false);
1465 fputs(prefix2, f);
1466 }
1467
1468 r = json_format(f, e, flags, prefix2);
1469 if (r < 0)
1470 return r;
1471 }
1472
1473 if (flags & JSON_FORMAT_PRETTY) {
1474 fputc('\n', f);
1475 print_source(f, v, flags, true);
1476 fputs(strempty(prefix), f);
1477 }
1478
1479 fputc(']', f);
1480 }
1481 break;
1482 }
1483
1484 case JSON_VARIANT_OBJECT: {
1485 size_t i, n;
1486
1487 n = json_variant_elements(v);
1488
1489 if (n == 0)
1490 fputs("{}", f);
1491 else {
1492 _cleanup_free_ char *joined = NULL;
1493 const char *prefix2;
1494
1495 if (flags & JSON_FORMAT_PRETTY) {
1496 joined = strjoin(strempty(prefix), "\t");
1497 if (!joined)
1498 return -ENOMEM;
1499
1500 prefix2 = joined;
1501 fputs("{\n", f);
1502 } else {
1503 prefix2 = strempty(prefix);
1504 fputc('{', f);
1505 }
1506
1507 for (i = 0; i < n; i += 2) {
1508 JsonVariant *e;
1509
1510 e = json_variant_by_index(v, i);
1511
1512 if (i > 0) {
1513 if (flags & JSON_FORMAT_PRETTY)
1514 fputs(",\n", f);
1515 else
1516 fputc(',', f);
1517 }
1518
1519 if (flags & JSON_FORMAT_PRETTY) {
1520 print_source(f, e, flags, false);
1521 fputs(prefix2, f);
1522 }
1523
1524 r = json_format(f, e, flags, prefix2);
1525 if (r < 0)
1526 return r;
1527
1528 fputs(flags & JSON_FORMAT_PRETTY ? " : " : ":", f);
1529
1530 r = json_format(f, json_variant_by_index(v, i+1), flags, prefix2);
1531 if (r < 0)
1532 return r;
1533 }
1534
1535 if (flags & JSON_FORMAT_PRETTY) {
1536 fputc('\n', f);
1537 print_source(f, v, flags, true);
1538 fputs(strempty(prefix), f);
1539 }
1540
1541 fputc('}', f);
1542 }
1543 break;
1544 }
1545
1546 default:
1547 assert_not_reached("Unexpected variant type.");
1548 }
1549
1550 return 0;
1551 }
1552
1553 int json_variant_format(JsonVariant *v, JsonFormatFlags flags, char **ret) {
1554 _cleanup_free_ char *s = NULL;
1555 size_t sz = 0;
1556 int r;
1557
1558 /* Returns the length of the generated string (without the terminating NUL),
1559 * or negative on error. */
1560
1561 assert_return(v, -EINVAL);
1562 assert_return(ret, -EINVAL);
1563
1564 {
1565 _cleanup_fclose_ FILE *f = NULL;
1566
1567 f = open_memstream_unlocked(&s, &sz);
1568 if (!f)
1569 return -ENOMEM;
1570
1571 json_variant_dump(v, flags, f, NULL);
1572
1573 /* Add terminating 0, so that the output buffer is a valid string. */
1574 fputc('\0', f);
1575
1576 r = fflush_and_check(f);
1577 }
1578 if (r < 0)
1579 return r;
1580
1581 assert(s);
1582 *ret = TAKE_PTR(s);
1583 assert(sz > 0);
1584 return (int) sz - 1;
1585 }
1586
1587 void json_variant_dump(JsonVariant *v, JsonFormatFlags flags, FILE *f, const char *prefix) {
1588 if (!v)
1589 return;
1590
1591 if (!f)
1592 f = stdout;
1593
1594 print_source(f, v, flags, false);
1595
1596 if (((flags & (JSON_FORMAT_COLOR_AUTO|JSON_FORMAT_COLOR)) == JSON_FORMAT_COLOR_AUTO) && colors_enabled())
1597 flags |= JSON_FORMAT_COLOR;
1598
1599 if (flags & JSON_FORMAT_SSE)
1600 fputs("data: ", f);
1601 if (flags & JSON_FORMAT_SEQ)
1602 fputc('\x1e', f); /* ASCII Record Separator */
1603
1604 json_format(f, v, flags, prefix);
1605
1606 if (flags & (JSON_FORMAT_PRETTY|JSON_FORMAT_SEQ|JSON_FORMAT_SSE|JSON_FORMAT_NEWLINE))
1607 fputc('\n', f);
1608 if (flags & JSON_FORMAT_SSE)
1609 fputc('\n', f); /* In case of SSE add a second newline */
1610 }
1611
1612 static int json_variant_copy(JsonVariant **nv, JsonVariant *v) {
1613 JsonVariantType t;
1614 JsonVariant *c;
1615 JsonValue value;
1616 const void *source;
1617 size_t k;
1618
1619 assert(nv);
1620 assert(v);
1621
1622 /* Let's copy the simple types literally, and the larger types by references */
1623 t = json_variant_type(v);
1624 switch (t) {
1625 case JSON_VARIANT_INTEGER:
1626 k = sizeof(intmax_t);
1627 value.integer = json_variant_integer(v);
1628 source = &value;
1629 break;
1630
1631 case JSON_VARIANT_UNSIGNED:
1632 k = sizeof(uintmax_t);
1633 value.unsig = json_variant_unsigned(v);
1634 source = &value;
1635 break;
1636
1637 case JSON_VARIANT_REAL:
1638 k = sizeof(long double);
1639 value.real = json_variant_real(v);
1640 source = &value;
1641 break;
1642
1643 case JSON_VARIANT_BOOLEAN:
1644 k = sizeof(bool);
1645 value.boolean = json_variant_boolean(v);
1646 source = &value;
1647 break;
1648
1649 case JSON_VARIANT_NULL:
1650 k = 0;
1651 source = NULL;
1652 break;
1653
1654 case JSON_VARIANT_STRING:
1655 source = json_variant_string(v);
1656 k = strnlen(source, INLINE_STRING_MAX + 1);
1657 if (k <= INLINE_STRING_MAX) {
1658 k ++;
1659 break;
1660 }
1661
1662 _fallthrough_;
1663
1664 default:
1665 /* Everything else copy by reference */
1666
1667 c = malloc0(MAX(sizeof(JsonVariant),
1668 offsetof(JsonVariant, reference) + sizeof(JsonVariant*)));
1669 if (!c)
1670 return -ENOMEM;
1671
1672 c->n_ref = 1;
1673 c->type = t;
1674 c->is_reference = true;
1675 c->reference = json_variant_ref(json_variant_normalize(v));
1676
1677 *nv = c;
1678 return 0;
1679 }
1680
1681 c = malloc0(MAX(sizeof(JsonVariant),
1682 offsetof(JsonVariant, value) + k));
1683 if (!c)
1684 return -ENOMEM;
1685
1686 c->n_ref = 1;
1687 c->type = t;
1688
1689 memcpy_safe(&c->value, source, k);
1690
1691 *nv = c;
1692 return 0;
1693 }
1694
1695 static bool json_single_ref(JsonVariant *v) {
1696
1697 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
1698
1699 if (!json_variant_is_regular(v))
1700 return false;
1701
1702 if (v->is_embedded)
1703 return json_single_ref(v->parent);
1704
1705 assert(v->n_ref > 0);
1706 return v->n_ref == 1;
1707 }
1708
1709 static int json_variant_set_source(JsonVariant **v, JsonSource *source, unsigned line, unsigned column) {
1710 JsonVariant *w;
1711 int r;
1712
1713 assert(v);
1714
1715 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole referencer of
1716 * the object. If not, allocates a new object, possibly a surrogate for the original one */
1717
1718 if (!*v)
1719 return 0;
1720
1721 if (source && line > source->max_line)
1722 source->max_line = line;
1723 if (source && column > source->max_column)
1724 source->max_column = column;
1725
1726 if (!json_variant_is_regular(*v)) {
1727
1728 if (!source && line == 0 && column == 0)
1729 return 0;
1730
1731 } else {
1732 if (json_source_equal((*v)->source, source) &&
1733 (*v)->line == line &&
1734 (*v)->column == column)
1735 return 0;
1736
1737 if (json_single_ref(*v)) { /* Sole reference? */
1738 json_source_unref((*v)->source);
1739 (*v)->source = json_source_ref(source);
1740 (*v)->line = line;
1741 (*v)->column = column;
1742 return 1;
1743 }
1744 }
1745
1746 r = json_variant_copy(&w, *v);
1747 if (r < 0)
1748 return r;
1749
1750 assert(json_variant_is_regular(w));
1751 assert(!w->is_embedded);
1752 assert(w->n_ref == 1);
1753 assert(!w->source);
1754
1755 w->source = json_source_ref(source);
1756 w->line = line;
1757 w->column = column;
1758
1759 json_variant_unref(*v);
1760 *v = w;
1761
1762 return 1;
1763 }
1764
1765 static void inc_lines_columns(unsigned *line, unsigned *column, const char *s, size_t n) {
1766 assert(line);
1767 assert(column);
1768 assert(s || n == 0);
1769
1770 while (n > 0) {
1771 if (*s == '\n') {
1772 (*line)++;
1773 *column = 1;
1774 } else if ((signed char) *s >= 0 && *s < 127) /* Process ASCII chars quickly */
1775 (*column)++;
1776 else {
1777 int w;
1778
1779 w = utf8_encoded_valid_unichar(s, n);
1780 if (w < 0) /* count invalid unichars as normal characters */
1781 w = 1;
1782 else if ((size_t) w > n) /* never read more than the specified number of characters */
1783 w = (int) n;
1784
1785 (*column)++;
1786
1787 s += w;
1788 n -= w;
1789 continue;
1790 }
1791
1792 s++;
1793 n--;
1794 }
1795 }
1796
1797 static int unhex_ucs2(const char *c, uint16_t *ret) {
1798 int aa, bb, cc, dd;
1799 uint16_t x;
1800
1801 assert(c);
1802 assert(ret);
1803
1804 aa = unhexchar(c[0]);
1805 if (aa < 0)
1806 return -EINVAL;
1807
1808 bb = unhexchar(c[1]);
1809 if (bb < 0)
1810 return -EINVAL;
1811
1812 cc = unhexchar(c[2]);
1813 if (cc < 0)
1814 return -EINVAL;
1815
1816 dd = unhexchar(c[3]);
1817 if (dd < 0)
1818 return -EINVAL;
1819
1820 x = ((uint16_t) aa << 12) |
1821 ((uint16_t) bb << 8) |
1822 ((uint16_t) cc << 4) |
1823 ((uint16_t) dd);
1824
1825 if (x <= 0)
1826 return -EINVAL;
1827
1828 *ret = x;
1829
1830 return 0;
1831 }
1832
1833 static int json_parse_string(const char **p, char **ret) {
1834 _cleanup_free_ char *s = NULL;
1835 size_t n = 0, allocated = 0;
1836 const char *c;
1837
1838 assert(p);
1839 assert(*p);
1840 assert(ret);
1841
1842 c = *p;
1843
1844 if (*c != '"')
1845 return -EINVAL;
1846
1847 c++;
1848
1849 for (;;) {
1850 int len;
1851
1852 /* Check for EOF */
1853 if (*c == 0)
1854 return -EINVAL;
1855
1856 /* Check for control characters 0x00..0x1f */
1857 if (*c > 0 && *c < ' ')
1858 return -EINVAL;
1859
1860 /* Check for control character 0x7f */
1861 if (*c == 0x7f)
1862 return -EINVAL;
1863
1864 if (*c == '"') {
1865 if (!s) {
1866 s = strdup("");
1867 if (!s)
1868 return -ENOMEM;
1869 } else
1870 s[n] = 0;
1871
1872 *p = c + 1;
1873
1874 *ret = TAKE_PTR(s);
1875 return JSON_TOKEN_STRING;
1876 }
1877
1878 if (*c == '\\') {
1879 char ch = 0;
1880 c++;
1881
1882 if (*c == 0)
1883 return -EINVAL;
1884
1885 if (IN_SET(*c, '"', '\\', '/'))
1886 ch = *c;
1887 else if (*c == 'b')
1888 ch = '\b';
1889 else if (*c == 'f')
1890 ch = '\f';
1891 else if (*c == 'n')
1892 ch = '\n';
1893 else if (*c == 'r')
1894 ch = '\r';
1895 else if (*c == 't')
1896 ch = '\t';
1897 else if (*c == 'u') {
1898 char16_t x;
1899 int r;
1900
1901 r = unhex_ucs2(c + 1, &x);
1902 if (r < 0)
1903 return r;
1904
1905 c += 5;
1906
1907 if (!GREEDY_REALLOC(s, allocated, n + 5))
1908 return -ENOMEM;
1909
1910 if (!utf16_is_surrogate(x))
1911 n += utf8_encode_unichar(s + n, (char32_t) x);
1912 else if (utf16_is_trailing_surrogate(x))
1913 return -EINVAL;
1914 else {
1915 char16_t y;
1916
1917 if (c[0] != '\\' || c[1] != 'u')
1918 return -EINVAL;
1919
1920 r = unhex_ucs2(c + 2, &y);
1921 if (r < 0)
1922 return r;
1923
1924 c += 6;
1925
1926 if (!utf16_is_trailing_surrogate(y))
1927 return -EINVAL;
1928
1929 n += utf8_encode_unichar(s + n, utf16_surrogate_pair_to_unichar(x, y));
1930 }
1931
1932 continue;
1933 } else
1934 return -EINVAL;
1935
1936 if (!GREEDY_REALLOC(s, allocated, n + 2))
1937 return -ENOMEM;
1938
1939 s[n++] = ch;
1940 c ++;
1941 continue;
1942 }
1943
1944 len = utf8_encoded_valid_unichar(c, (size_t) -1);
1945 if (len < 0)
1946 return len;
1947
1948 if (!GREEDY_REALLOC(s, allocated, n + len + 1))
1949 return -ENOMEM;
1950
1951 memcpy(s + n, c, len);
1952 n += len;
1953 c += len;
1954 }
1955 }
1956
1957 static int json_parse_number(const char **p, JsonValue *ret) {
1958 bool negative = false, exponent_negative = false, is_real = false;
1959 long double x = 0.0, y = 0.0, exponent = 0.0, shift = 1.0;
1960 intmax_t i = 0;
1961 uintmax_t u = 0;
1962 const char *c;
1963
1964 assert(p);
1965 assert(*p);
1966 assert(ret);
1967
1968 c = *p;
1969
1970 if (*c == '-') {
1971 negative = true;
1972 c++;
1973 }
1974
1975 if (*c == '0')
1976 c++;
1977 else {
1978 if (!strchr("123456789", *c) || *c == 0)
1979 return -EINVAL;
1980
1981 do {
1982 if (!is_real) {
1983 if (negative) {
1984
1985 if (i < INTMAX_MIN / 10) /* overflow */
1986 is_real = true;
1987 else {
1988 intmax_t t = 10 * i;
1989
1990 if (t < INTMAX_MIN + (*c - '0')) /* overflow */
1991 is_real = true;
1992 else
1993 i = t - (*c - '0');
1994 }
1995 } else {
1996 if (u > UINTMAX_MAX / 10) /* overflow */
1997 is_real = true;
1998 else {
1999 uintmax_t t = 10 * u;
2000
2001 if (t > UINTMAX_MAX - (*c - '0')) /* overflow */
2002 is_real = true;
2003 else
2004 u = t + (*c - '0');
2005 }
2006 }
2007 }
2008
2009 x = 10.0 * x + (*c - '0');
2010
2011 c++;
2012 } while (strchr("0123456789", *c) && *c != 0);
2013 }
2014
2015 if (*c == '.') {
2016 is_real = true;
2017 c++;
2018
2019 if (!strchr("0123456789", *c) || *c == 0)
2020 return -EINVAL;
2021
2022 do {
2023 y = 10.0 * y + (*c - '0');
2024 shift = 10.0 * shift;
2025 c++;
2026 } while (strchr("0123456789", *c) && *c != 0);
2027 }
2028
2029 if (IN_SET(*c, 'e', 'E')) {
2030 is_real = true;
2031 c++;
2032
2033 if (*c == '-') {
2034 exponent_negative = true;
2035 c++;
2036 } else if (*c == '+')
2037 c++;
2038
2039 if (!strchr("0123456789", *c) || *c == 0)
2040 return -EINVAL;
2041
2042 do {
2043 exponent = 10.0 * exponent + (*c - '0');
2044 c++;
2045 } while (strchr("0123456789", *c) && *c != 0);
2046 }
2047
2048 *p = c;
2049
2050 if (is_real) {
2051 ret->real = ((negative ? -1.0 : 1.0) * (x + (y / shift))) * exp10l((exponent_negative ? -1.0 : 1.0) * exponent);
2052 return JSON_TOKEN_REAL;
2053 } else if (negative) {
2054 ret->integer = i;
2055 return JSON_TOKEN_INTEGER;
2056 } else {
2057 ret->unsig = u;
2058 return JSON_TOKEN_UNSIGNED;
2059 }
2060 }
2061
2062 int json_tokenize(
2063 const char **p,
2064 char **ret_string,
2065 JsonValue *ret_value,
2066 unsigned *ret_line, /* 'ret_line' returns the line at the beginning of this token */
2067 unsigned *ret_column,
2068 void **state,
2069 unsigned *line, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2070 unsigned *column) {
2071
2072 unsigned start_line, start_column;
2073 const char *start, *c;
2074 size_t n;
2075 int t, r;
2076
2077 enum {
2078 STATE_NULL,
2079 STATE_VALUE,
2080 STATE_VALUE_POST,
2081 };
2082
2083 assert(p);
2084 assert(*p);
2085 assert(ret_string);
2086 assert(ret_value);
2087 assert(ret_line);
2088 assert(ret_column);
2089 assert(line);
2090 assert(column);
2091 assert(state);
2092
2093 t = PTR_TO_INT(*state);
2094 if (t == STATE_NULL) {
2095 *line = 1;
2096 *column = 1;
2097 t = STATE_VALUE;
2098 }
2099
2100 /* Skip over the whitespace */
2101 n = strspn(*p, WHITESPACE);
2102 inc_lines_columns(line, column, *p, n);
2103 c = *p + n;
2104
2105 /* Remember where we started processing this token */
2106 start = c;
2107 start_line = *line;
2108 start_column = *column;
2109
2110 if (*c == 0) {
2111 *ret_string = NULL;
2112 *ret_value = JSON_VALUE_NULL;
2113 r = JSON_TOKEN_END;
2114 goto finish;
2115 }
2116
2117 switch (t) {
2118
2119 case STATE_VALUE:
2120
2121 if (*c == '{') {
2122 c++;
2123 *state = INT_TO_PTR(STATE_VALUE);
2124 r = JSON_TOKEN_OBJECT_OPEN;
2125 goto null_return;
2126
2127 } else if (*c == '}') {
2128 c++;
2129 *state = INT_TO_PTR(STATE_VALUE_POST);
2130 r = JSON_TOKEN_OBJECT_CLOSE;
2131 goto null_return;
2132
2133 } else if (*c == '[') {
2134 c++;
2135 *state = INT_TO_PTR(STATE_VALUE);
2136 r = JSON_TOKEN_ARRAY_OPEN;
2137 goto null_return;
2138
2139 } else if (*c == ']') {
2140 c++;
2141 *state = INT_TO_PTR(STATE_VALUE_POST);
2142 r = JSON_TOKEN_ARRAY_CLOSE;
2143 goto null_return;
2144
2145 } else if (*c == '"') {
2146
2147 r = json_parse_string(&c, ret_string);
2148 if (r < 0)
2149 return r;
2150
2151 *ret_value = JSON_VALUE_NULL;
2152 *state = INT_TO_PTR(STATE_VALUE_POST);
2153 goto finish;
2154
2155 } else if (strchr("-0123456789", *c)) {
2156
2157 r = json_parse_number(&c, ret_value);
2158 if (r < 0)
2159 return r;
2160
2161 *ret_string = NULL;
2162 *state = INT_TO_PTR(STATE_VALUE_POST);
2163 goto finish;
2164
2165 } else if (startswith(c, "true")) {
2166 *ret_string = NULL;
2167 ret_value->boolean = true;
2168 c += 4;
2169 *state = INT_TO_PTR(STATE_VALUE_POST);
2170 r = JSON_TOKEN_BOOLEAN;
2171 goto finish;
2172
2173 } else if (startswith(c, "false")) {
2174 *ret_string = NULL;
2175 ret_value->boolean = false;
2176 c += 5;
2177 *state = INT_TO_PTR(STATE_VALUE_POST);
2178 r = JSON_TOKEN_BOOLEAN;
2179 goto finish;
2180
2181 } else if (startswith(c, "null")) {
2182 *ret_string = NULL;
2183 *ret_value = JSON_VALUE_NULL;
2184 c += 4;
2185 *state = INT_TO_PTR(STATE_VALUE_POST);
2186 r = JSON_TOKEN_NULL;
2187 goto finish;
2188
2189 }
2190
2191 return -EINVAL;
2192
2193 case STATE_VALUE_POST:
2194
2195 if (*c == ':') {
2196 c++;
2197 *state = INT_TO_PTR(STATE_VALUE);
2198 r = JSON_TOKEN_COLON;
2199 goto null_return;
2200
2201 } else if (*c == ',') {
2202 c++;
2203 *state = INT_TO_PTR(STATE_VALUE);
2204 r = JSON_TOKEN_COMMA;
2205 goto null_return;
2206
2207 } else if (*c == '}') {
2208 c++;
2209 *state = INT_TO_PTR(STATE_VALUE_POST);
2210 r = JSON_TOKEN_OBJECT_CLOSE;
2211 goto null_return;
2212
2213 } else if (*c == ']') {
2214 c++;
2215 *state = INT_TO_PTR(STATE_VALUE_POST);
2216 r = JSON_TOKEN_ARRAY_CLOSE;
2217 goto null_return;
2218 }
2219
2220 return -EINVAL;
2221
2222 default:
2223 assert_not_reached("Unexpected tokenizer state");
2224 }
2225
2226 null_return:
2227 *ret_string = NULL;
2228 *ret_value = JSON_VALUE_NULL;
2229
2230 finish:
2231 inc_lines_columns(line, column, start, c - start);
2232 *p = c;
2233
2234 *ret_line = start_line;
2235 *ret_column = start_column;
2236
2237 return r;
2238 }
2239
2240 typedef enum JsonExpect {
2241 /* The following values are used by json_parse() */
2242 EXPECT_TOPLEVEL,
2243 EXPECT_END,
2244 EXPECT_OBJECT_FIRST_KEY,
2245 EXPECT_OBJECT_NEXT_KEY,
2246 EXPECT_OBJECT_COLON,
2247 EXPECT_OBJECT_VALUE,
2248 EXPECT_OBJECT_COMMA,
2249 EXPECT_ARRAY_FIRST_ELEMENT,
2250 EXPECT_ARRAY_NEXT_ELEMENT,
2251 EXPECT_ARRAY_COMMA,
2252
2253 /* And these are used by json_build() */
2254 EXPECT_ARRAY_ELEMENT,
2255 EXPECT_OBJECT_KEY,
2256 } JsonExpect;
2257
2258 typedef struct JsonStack {
2259 JsonExpect expect;
2260 JsonVariant **elements;
2261 size_t n_elements, n_elements_allocated;
2262 unsigned line_before;
2263 unsigned column_before;
2264 size_t n_suppress; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2265 } JsonStack;
2266
2267 static void json_stack_release(JsonStack *s) {
2268 assert(s);
2269
2270 json_variant_unref_many(s->elements, s->n_elements);
2271 s->elements = mfree(s->elements);
2272 }
2273
2274 static int json_parse_internal(
2275 const char **input,
2276 JsonSource *source,
2277 JsonVariant **ret,
2278 unsigned *line,
2279 unsigned *column,
2280 bool continue_end) {
2281
2282 size_t n_stack = 1, n_stack_allocated = 0, i;
2283 unsigned line_buffer = 0, column_buffer = 0;
2284 void *tokenizer_state = NULL;
2285 JsonStack *stack = NULL;
2286 const char *p;
2287 int r;
2288
2289 assert_return(input, -EINVAL);
2290 assert_return(ret, -EINVAL);
2291
2292 p = *input;
2293
2294 if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack))
2295 return -ENOMEM;
2296
2297 stack[0] = (JsonStack) {
2298 .expect = EXPECT_TOPLEVEL,
2299 };
2300
2301 if (!line)
2302 line = &line_buffer;
2303 if (!column)
2304 column = &column_buffer;
2305
2306 for (;;) {
2307 _cleanup_(json_variant_unrefp) JsonVariant *add = NULL;
2308 _cleanup_free_ char *string = NULL;
2309 unsigned line_token, column_token;
2310 JsonStack *current;
2311 JsonValue value;
2312 int token;
2313
2314 assert(n_stack > 0);
2315 current = stack + n_stack - 1;
2316
2317 if (continue_end && current->expect == EXPECT_END)
2318 goto done;
2319
2320 token = json_tokenize(&p, &string, &value, &line_token, &column_token, &tokenizer_state, line, column);
2321 if (token < 0) {
2322 r = token;
2323 goto finish;
2324 }
2325
2326 switch (token) {
2327
2328 case JSON_TOKEN_END:
2329 if (current->expect != EXPECT_END) {
2330 r = -EINVAL;
2331 goto finish;
2332 }
2333
2334 assert(current->n_elements == 1);
2335 assert(n_stack == 1);
2336 goto done;
2337
2338 case JSON_TOKEN_COLON:
2339
2340 if (current->expect != EXPECT_OBJECT_COLON) {
2341 r = -EINVAL;
2342 goto finish;
2343 }
2344
2345 current->expect = EXPECT_OBJECT_VALUE;
2346 break;
2347
2348 case JSON_TOKEN_COMMA:
2349
2350 if (current->expect == EXPECT_OBJECT_COMMA)
2351 current->expect = EXPECT_OBJECT_NEXT_KEY;
2352 else if (current->expect == EXPECT_ARRAY_COMMA)
2353 current->expect = EXPECT_ARRAY_NEXT_ELEMENT;
2354 else {
2355 r = -EINVAL;
2356 goto finish;
2357 }
2358
2359 break;
2360
2361 case JSON_TOKEN_OBJECT_OPEN:
2362
2363 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2364 r = -EINVAL;
2365 goto finish;
2366 }
2367
2368 if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) {
2369 r = -ENOMEM;
2370 goto finish;
2371 }
2372 current = stack + n_stack - 1;
2373
2374 /* Prepare the expect for when we return from the child */
2375 if (current->expect == EXPECT_TOPLEVEL)
2376 current->expect = EXPECT_END;
2377 else if (current->expect == EXPECT_OBJECT_VALUE)
2378 current->expect = EXPECT_OBJECT_COMMA;
2379 else {
2380 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2381 current->expect = EXPECT_ARRAY_COMMA;
2382 }
2383
2384 stack[n_stack++] = (JsonStack) {
2385 .expect = EXPECT_OBJECT_FIRST_KEY,
2386 .line_before = line_token,
2387 .column_before = column_token,
2388 };
2389
2390 current = stack + n_stack - 1;
2391 break;
2392
2393 case JSON_TOKEN_OBJECT_CLOSE:
2394 if (!IN_SET(current->expect, EXPECT_OBJECT_FIRST_KEY, EXPECT_OBJECT_COMMA)) {
2395 r = -EINVAL;
2396 goto finish;
2397 }
2398
2399 assert(n_stack > 1);
2400
2401 r = json_variant_new_object(&add, current->elements, current->n_elements);
2402 if (r < 0)
2403 goto finish;
2404
2405 line_token = current->line_before;
2406 column_token = current->column_before;
2407
2408 json_stack_release(current);
2409 n_stack--, current--;
2410
2411 break;
2412
2413 case JSON_TOKEN_ARRAY_OPEN:
2414 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2415 r = -EINVAL;
2416 goto finish;
2417 }
2418
2419 if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) {
2420 r = -ENOMEM;
2421 goto finish;
2422 }
2423 current = stack + n_stack - 1;
2424
2425 /* Prepare the expect for when we return from the child */
2426 if (current->expect == EXPECT_TOPLEVEL)
2427 current->expect = EXPECT_END;
2428 else if (current->expect == EXPECT_OBJECT_VALUE)
2429 current->expect = EXPECT_OBJECT_COMMA;
2430 else {
2431 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2432 current->expect = EXPECT_ARRAY_COMMA;
2433 }
2434
2435 stack[n_stack++] = (JsonStack) {
2436 .expect = EXPECT_ARRAY_FIRST_ELEMENT,
2437 .line_before = line_token,
2438 .column_before = column_token,
2439 };
2440
2441 break;
2442
2443 case JSON_TOKEN_ARRAY_CLOSE:
2444 if (!IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_COMMA)) {
2445 r = -EINVAL;
2446 goto finish;
2447 }
2448
2449 assert(n_stack > 1);
2450
2451 r = json_variant_new_array(&add, current->elements, current->n_elements);
2452 if (r < 0)
2453 goto finish;
2454
2455 line_token = current->line_before;
2456 column_token = current->column_before;
2457
2458 json_stack_release(current);
2459 n_stack--, current--;
2460 break;
2461
2462 case JSON_TOKEN_STRING:
2463 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_FIRST_KEY, EXPECT_OBJECT_NEXT_KEY, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2464 r = -EINVAL;
2465 goto finish;
2466 }
2467
2468 r = json_variant_new_string(&add, string);
2469 if (r < 0)
2470 goto finish;
2471
2472 if (current->expect == EXPECT_TOPLEVEL)
2473 current->expect = EXPECT_END;
2474 else if (IN_SET(current->expect, EXPECT_OBJECT_FIRST_KEY, EXPECT_OBJECT_NEXT_KEY))
2475 current->expect = EXPECT_OBJECT_COLON;
2476 else if (current->expect == EXPECT_OBJECT_VALUE)
2477 current->expect = EXPECT_OBJECT_COMMA;
2478 else {
2479 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2480 current->expect = EXPECT_ARRAY_COMMA;
2481 }
2482
2483 break;
2484
2485 case JSON_TOKEN_REAL:
2486 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2487 r = -EINVAL;
2488 goto finish;
2489 }
2490
2491 r = json_variant_new_real(&add, value.real);
2492 if (r < 0)
2493 goto finish;
2494
2495 if (current->expect == EXPECT_TOPLEVEL)
2496 current->expect = EXPECT_END;
2497 else if (current->expect == EXPECT_OBJECT_VALUE)
2498 current->expect = EXPECT_OBJECT_COMMA;
2499 else {
2500 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2501 current->expect = EXPECT_ARRAY_COMMA;
2502 }
2503
2504 break;
2505
2506 case JSON_TOKEN_INTEGER:
2507 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2508 r = -EINVAL;
2509 goto finish;
2510 }
2511
2512 r = json_variant_new_integer(&add, value.integer);
2513 if (r < 0)
2514 goto finish;
2515
2516 if (current->expect == EXPECT_TOPLEVEL)
2517 current->expect = EXPECT_END;
2518 else if (current->expect == EXPECT_OBJECT_VALUE)
2519 current->expect = EXPECT_OBJECT_COMMA;
2520 else {
2521 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2522 current->expect = EXPECT_ARRAY_COMMA;
2523 }
2524
2525 break;
2526
2527 case JSON_TOKEN_UNSIGNED:
2528 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2529 r = -EINVAL;
2530 goto finish;
2531 }
2532
2533 r = json_variant_new_unsigned(&add, value.unsig);
2534 if (r < 0)
2535 goto finish;
2536
2537 if (current->expect == EXPECT_TOPLEVEL)
2538 current->expect = EXPECT_END;
2539 else if (current->expect == EXPECT_OBJECT_VALUE)
2540 current->expect = EXPECT_OBJECT_COMMA;
2541 else {
2542 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2543 current->expect = EXPECT_ARRAY_COMMA;
2544 }
2545
2546 break;
2547
2548 case JSON_TOKEN_BOOLEAN:
2549 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2550 r = -EINVAL;
2551 goto finish;
2552 }
2553
2554 r = json_variant_new_boolean(&add, value.boolean);
2555 if (r < 0)
2556 goto finish;
2557
2558 if (current->expect == EXPECT_TOPLEVEL)
2559 current->expect = EXPECT_END;
2560 else if (current->expect == EXPECT_OBJECT_VALUE)
2561 current->expect = EXPECT_OBJECT_COMMA;
2562 else {
2563 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2564 current->expect = EXPECT_ARRAY_COMMA;
2565 }
2566
2567 break;
2568
2569 case JSON_TOKEN_NULL:
2570 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
2571 r = -EINVAL;
2572 goto finish;
2573 }
2574
2575 r = json_variant_new_null(&add);
2576 if (r < 0)
2577 goto finish;
2578
2579 if (current->expect == EXPECT_TOPLEVEL)
2580 current->expect = EXPECT_END;
2581 else if (current->expect == EXPECT_OBJECT_VALUE)
2582 current->expect = EXPECT_OBJECT_COMMA;
2583 else {
2584 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
2585 current->expect = EXPECT_ARRAY_COMMA;
2586 }
2587
2588 break;
2589
2590 default:
2591 assert_not_reached("Unexpected token");
2592 }
2593
2594 if (add) {
2595 (void) json_variant_set_source(&add, source, line_token, column_token);
2596
2597 if (!GREEDY_REALLOC(current->elements, current->n_elements_allocated, current->n_elements + 1)) {
2598 r = -ENOMEM;
2599 goto finish;
2600 }
2601
2602 current->elements[current->n_elements++] = TAKE_PTR(add);
2603 }
2604 }
2605
2606 done:
2607 assert(n_stack == 1);
2608 assert(stack[0].n_elements == 1);
2609
2610 *ret = json_variant_ref(stack[0].elements[0]);
2611 *input = p;
2612 r = 0;
2613
2614 finish:
2615 for (i = 0; i < n_stack; i++)
2616 json_stack_release(stack + i);
2617
2618 free(stack);
2619
2620 return r;
2621 }
2622
2623 int json_parse(const char *input, JsonVariant **ret, unsigned *ret_line, unsigned *ret_column) {
2624 return json_parse_internal(&input, NULL, ret, ret_line, ret_column, false);
2625 }
2626
2627 int json_parse_continue(const char **p, JsonVariant **ret, unsigned *ret_line, unsigned *ret_column) {
2628 return json_parse_internal(p, NULL, ret, ret_line, ret_column, true);
2629 }
2630
2631 int json_parse_file(FILE *f, const char *path, JsonVariant **ret, unsigned *ret_line, unsigned *ret_column) {
2632 _cleanup_(json_source_unrefp) JsonSource *source = NULL;
2633 _cleanup_free_ char *text = NULL;
2634 const char *p;
2635 int r;
2636
2637 if (f)
2638 r = read_full_stream(f, &text, NULL);
2639 else if (path)
2640 r = read_full_file(path, &text, NULL);
2641 else
2642 return -EINVAL;
2643 if (r < 0)
2644 return r;
2645
2646 if (path) {
2647 source = json_source_new(path);
2648 if (!source)
2649 return -ENOMEM;
2650 }
2651
2652 p = text;
2653 return json_parse_internal(&p, source, ret, ret_line, ret_column, false);
2654 }
2655
2656 int json_buildv(JsonVariant **ret, va_list ap) {
2657 JsonStack *stack = NULL;
2658 size_t n_stack = 1, n_stack_allocated = 0, i;
2659 int r;
2660
2661 assert_return(ret, -EINVAL);
2662
2663 if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack))
2664 return -ENOMEM;
2665
2666 stack[0] = (JsonStack) {
2667 .expect = EXPECT_TOPLEVEL,
2668 };
2669
2670 for (;;) {
2671 _cleanup_(json_variant_unrefp) JsonVariant *add = NULL;
2672 size_t n_subtract = 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
2673 * have been added to the current variant */
2674 JsonStack *current;
2675 int command;
2676
2677 assert(n_stack > 0);
2678 current = stack + n_stack - 1;
2679
2680 if (current->expect == EXPECT_END)
2681 goto done;
2682
2683 command = va_arg(ap, int);
2684
2685 switch (command) {
2686
2687 case _JSON_BUILD_STRING: {
2688 const char *p;
2689
2690 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2691 r = -EINVAL;
2692 goto finish;
2693 }
2694
2695 p = va_arg(ap, const char *);
2696
2697 if (current->n_suppress == 0) {
2698 r = json_variant_new_string(&add, p);
2699 if (r < 0)
2700 goto finish;
2701 }
2702
2703 n_subtract = 1;
2704
2705 if (current->expect == EXPECT_TOPLEVEL)
2706 current->expect = EXPECT_END;
2707 else if (current->expect == EXPECT_OBJECT_VALUE)
2708 current->expect = EXPECT_OBJECT_KEY;
2709 else
2710 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2711
2712 break;
2713 }
2714
2715 case _JSON_BUILD_INTEGER: {
2716 intmax_t j;
2717
2718 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2719 r = -EINVAL;
2720 goto finish;
2721 }
2722
2723 j = va_arg(ap, intmax_t);
2724
2725 if (current->n_suppress == 0) {
2726 r = json_variant_new_integer(&add, j);
2727 if (r < 0)
2728 goto finish;
2729 }
2730
2731 n_subtract = 1;
2732
2733 if (current->expect == EXPECT_TOPLEVEL)
2734 current->expect = EXPECT_END;
2735 else if (current->expect == EXPECT_OBJECT_VALUE)
2736 current->expect = EXPECT_OBJECT_KEY;
2737 else
2738 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2739
2740 break;
2741 }
2742
2743 case _JSON_BUILD_UNSIGNED: {
2744 uintmax_t j;
2745
2746 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2747 r = -EINVAL;
2748 goto finish;
2749 }
2750
2751 j = va_arg(ap, uintmax_t);
2752
2753 if (current->n_suppress == 0) {
2754 r = json_variant_new_unsigned(&add, j);
2755 if (r < 0)
2756 goto finish;
2757 }
2758
2759 n_subtract = 1;
2760
2761 if (current->expect == EXPECT_TOPLEVEL)
2762 current->expect = EXPECT_END;
2763 else if (current->expect == EXPECT_OBJECT_VALUE)
2764 current->expect = EXPECT_OBJECT_KEY;
2765 else
2766 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2767
2768 break;
2769 }
2770
2771 case _JSON_BUILD_REAL: {
2772 long double d;
2773
2774 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2775 r = -EINVAL;
2776 goto finish;
2777 }
2778
2779 d = va_arg(ap, long double);
2780
2781 if (current->n_suppress == 0) {
2782 r = json_variant_new_real(&add, d);
2783 if (r < 0)
2784 goto finish;
2785 }
2786
2787 n_subtract = 1;
2788
2789 if (current->expect == EXPECT_TOPLEVEL)
2790 current->expect = EXPECT_END;
2791 else if (current->expect == EXPECT_OBJECT_VALUE)
2792 current->expect = EXPECT_OBJECT_KEY;
2793 else
2794 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2795
2796 break;
2797 }
2798
2799 case _JSON_BUILD_BOOLEAN: {
2800 bool b;
2801
2802 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2803 r = -EINVAL;
2804 goto finish;
2805 }
2806
2807 b = va_arg(ap, int);
2808
2809 if (current->n_suppress == 0) {
2810 r = json_variant_new_boolean(&add, b);
2811 if (r < 0)
2812 goto finish;
2813 }
2814
2815 n_subtract = 1;
2816
2817 if (current->expect == EXPECT_TOPLEVEL)
2818 current->expect = EXPECT_END;
2819 else if (current->expect == EXPECT_OBJECT_VALUE)
2820 current->expect = EXPECT_OBJECT_KEY;
2821 else
2822 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2823
2824 break;
2825 }
2826
2827 case _JSON_BUILD_NULL:
2828
2829 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2830 r = -EINVAL;
2831 goto finish;
2832 }
2833
2834 if (current->n_suppress == 0) {
2835 r = json_variant_new_null(&add);
2836 if (r < 0)
2837 goto finish;
2838 }
2839
2840 n_subtract = 1;
2841
2842 if (current->expect == EXPECT_TOPLEVEL)
2843 current->expect = EXPECT_END;
2844 else if (current->expect == EXPECT_OBJECT_VALUE)
2845 current->expect = EXPECT_OBJECT_KEY;
2846 else
2847 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2848
2849 break;
2850
2851 case _JSON_BUILD_VARIANT:
2852
2853 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2854 r = -EINVAL;
2855 goto finish;
2856 }
2857
2858 /* Note that we don't care for current->n_suppress here, after all the variant is already
2859 * allocated anyway... */
2860 add = va_arg(ap, JsonVariant*);
2861 if (!add)
2862 add = JSON_VARIANT_MAGIC_NULL;
2863 else
2864 json_variant_ref(add);
2865
2866 n_subtract = 1;
2867
2868 if (current->expect == EXPECT_TOPLEVEL)
2869 current->expect = EXPECT_END;
2870 else if (current->expect == EXPECT_OBJECT_VALUE)
2871 current->expect = EXPECT_OBJECT_KEY;
2872 else
2873 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2874
2875 break;
2876
2877 case _JSON_BUILD_LITERAL: {
2878 const char *l;
2879
2880 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2881 r = -EINVAL;
2882 goto finish;
2883 }
2884
2885 l = va_arg(ap, const char *);
2886
2887 if (l) {
2888 /* Note that we don't care for current->n_suppress here, we should generate parsing
2889 * errors even in suppressed object properties */
2890
2891 r = json_parse(l, &add, NULL, NULL);
2892 if (r < 0)
2893 goto finish;
2894 } else
2895 add = JSON_VARIANT_MAGIC_NULL;
2896
2897 n_subtract = 1;
2898
2899 if (current->expect == EXPECT_TOPLEVEL)
2900 current->expect = EXPECT_END;
2901 else if (current->expect == EXPECT_OBJECT_VALUE)
2902 current->expect = EXPECT_OBJECT_KEY;
2903 else
2904 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2905
2906 break;
2907 }
2908
2909 case _JSON_BUILD_ARRAY_BEGIN:
2910
2911 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2912 r = -EINVAL;
2913 goto finish;
2914 }
2915
2916 if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) {
2917 r = -ENOMEM;
2918 goto finish;
2919 }
2920 current = stack + n_stack - 1;
2921
2922 if (current->expect == EXPECT_TOPLEVEL)
2923 current->expect = EXPECT_END;
2924 else if (current->expect == EXPECT_OBJECT_VALUE)
2925 current->expect = EXPECT_OBJECT_KEY;
2926 else
2927 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2928
2929 stack[n_stack++] = (JsonStack) {
2930 .expect = EXPECT_ARRAY_ELEMENT,
2931 .n_suppress = current->n_suppress != 0 ? (size_t) -1 : 0, /* if we shall suppress the
2932 * new array, then we should
2933 * also suppress all array
2934 * members */
2935 };
2936
2937 break;
2938
2939 case _JSON_BUILD_ARRAY_END:
2940 if (current->expect != EXPECT_ARRAY_ELEMENT) {
2941 r = -EINVAL;
2942 goto finish;
2943 }
2944
2945 assert(n_stack > 1);
2946
2947 if (current->n_suppress == 0) {
2948 r = json_variant_new_array(&add, current->elements, current->n_elements);
2949 if (r < 0)
2950 goto finish;
2951 }
2952
2953 n_subtract = 1;
2954
2955 json_stack_release(current);
2956 n_stack--, current--;
2957
2958 break;
2959
2960 case _JSON_BUILD_STRV: {
2961 char **l;
2962
2963 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2964 r = -EINVAL;
2965 goto finish;
2966 }
2967
2968 l = va_arg(ap, char **);
2969
2970 if (current->n_suppress == 0) {
2971 r = json_variant_new_array_strv(&add, l);
2972 if (r < 0)
2973 goto finish;
2974 }
2975
2976 n_subtract = 1;
2977
2978 if (current->expect == EXPECT_TOPLEVEL)
2979 current->expect = EXPECT_END;
2980 else if (current->expect == EXPECT_OBJECT_VALUE)
2981 current->expect = EXPECT_OBJECT_KEY;
2982 else
2983 assert(current->expect == EXPECT_ARRAY_ELEMENT);
2984
2985 break;
2986 }
2987
2988 case _JSON_BUILD_OBJECT_BEGIN:
2989
2990 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
2991 r = -EINVAL;
2992 goto finish;
2993 }
2994
2995 if (!GREEDY_REALLOC(stack, n_stack_allocated, n_stack+1)) {
2996 r = -ENOMEM;
2997 goto finish;
2998 }
2999 current = stack + n_stack - 1;
3000
3001 if (current->expect == EXPECT_TOPLEVEL)
3002 current->expect = EXPECT_END;
3003 else if (current->expect == EXPECT_OBJECT_VALUE)
3004 current->expect = EXPECT_OBJECT_KEY;
3005 else
3006 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3007
3008 stack[n_stack++] = (JsonStack) {
3009 .expect = EXPECT_OBJECT_KEY,
3010 .n_suppress = current->n_suppress != 0 ? (size_t) -1 : 0, /* if we shall suppress the
3011 * new object, then we should
3012 * also suppress all object
3013 * members */
3014 };
3015
3016 break;
3017
3018 case _JSON_BUILD_OBJECT_END:
3019
3020 if (current->expect != EXPECT_OBJECT_KEY) {
3021 r = -EINVAL;
3022 goto finish;
3023 }
3024
3025 assert(n_stack > 1);
3026
3027 if (current->n_suppress == 0) {
3028 r = json_variant_new_object(&add, current->elements, current->n_elements);
3029 if (r < 0)
3030 goto finish;
3031 }
3032
3033 n_subtract = 1;
3034
3035 json_stack_release(current);
3036 n_stack--, current--;
3037
3038 break;
3039
3040 case _JSON_BUILD_PAIR: {
3041 const char *n;
3042
3043 if (current->expect != EXPECT_OBJECT_KEY) {
3044 r = -EINVAL;
3045 goto finish;
3046 }
3047
3048 n = va_arg(ap, const char *);
3049
3050 if (current->n_suppress == 0) {
3051 r = json_variant_new_string(&add, n);
3052 if (r < 0)
3053 goto finish;
3054 }
3055
3056 n_subtract = 1;
3057
3058 current->expect = EXPECT_OBJECT_VALUE;
3059 break;
3060 }
3061
3062 case _JSON_BUILD_PAIR_CONDITION: {
3063 const char *n;
3064 bool b;
3065
3066 if (current->expect != EXPECT_OBJECT_KEY) {
3067 r = -EINVAL;
3068 goto finish;
3069 }
3070
3071 b = va_arg(ap, int);
3072 n = va_arg(ap, const char *);
3073
3074 if (b && current->n_suppress == 0) {
3075 r = json_variant_new_string(&add, n);
3076 if (r < 0)
3077 goto finish;
3078 }
3079
3080 n_subtract = 1; /* we generated one item */
3081
3082 if (!b && current->n_suppress != (size_t) -1)
3083 current->n_suppress += 2; /* Suppress this one and the next item */
3084
3085 current->expect = EXPECT_OBJECT_VALUE;
3086 break;
3087 }}
3088
3089 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3090 if (add && current->n_suppress == 0) {
3091 if (!GREEDY_REALLOC(current->elements, current->n_elements_allocated, current->n_elements + 1)) {
3092 r = -ENOMEM;
3093 goto finish;
3094 }
3095
3096 current->elements[current->n_elements++] = TAKE_PTR(add);
3097 }
3098
3099 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3100 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3101 * on this stack level */
3102 if (current->n_suppress != (size_t) -1) {
3103 if (current->n_suppress <= n_subtract) /* Saturated */
3104 current->n_suppress = 0;
3105 else
3106 current->n_suppress -= n_subtract;
3107 }
3108 }
3109
3110 done:
3111 assert(n_stack == 1);
3112 assert(stack[0].n_elements == 1);
3113
3114 *ret = json_variant_ref(stack[0].elements[0]);
3115 r = 0;
3116
3117 finish:
3118 for (i = 0; i < n_stack; i++)
3119 json_stack_release(stack + i);
3120
3121 free(stack);
3122
3123 return r;
3124 }
3125
3126 int json_build(JsonVariant **ret, ...) {
3127 va_list ap;
3128 int r;
3129
3130 va_start(ap, ret);
3131 r = json_buildv(ret, ap);
3132 va_end(ap);
3133
3134 return r;
3135 }
3136
3137 int json_log_internal(
3138 JsonVariant *variant,
3139 int level,
3140 int error,
3141 const char *file,
3142 int line,
3143 const char *func,
3144 const char *format, ...) {
3145
3146 PROTECT_ERRNO;
3147
3148 unsigned source_line, source_column;
3149 char buffer[LINE_MAX];
3150 const char *source;
3151 va_list ap;
3152 int r;
3153
3154 errno = ERRNO_VALUE(error);
3155
3156 va_start(ap, format);
3157 (void) vsnprintf(buffer, sizeof buffer, format, ap);
3158 va_end(ap);
3159
3160 if (variant) {
3161 r = json_variant_get_source(variant, &source, &source_line, &source_column);
3162 if (r < 0)
3163 return r;
3164 } else {
3165 source = NULL;
3166 source_line = 0;
3167 source_column = 0;
3168 }
3169
3170 if (source && source_line > 0 && source_column > 0)
3171 return log_struct_internal(
3172 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD, level),
3173 error,
3174 file, line, func,
3175 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
3176 "CONFIG_FILE=%s", source,
3177 "CONFIG_LINE=%u", source_line,
3178 "CONFIG_COLUMN=%u", source_column,
3179 LOG_MESSAGE("%s:%u:%u: %s", source, source_line, source_column, buffer),
3180 NULL);
3181 else
3182 return log_struct_internal(
3183 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD, level),
3184 error,
3185 file, line, func,
3186 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
3187 LOG_MESSAGE("%s", buffer),
3188 NULL);
3189 }
3190
3191 int json_dispatch(JsonVariant *v, const JsonDispatch table[], JsonDispatchCallback bad, JsonDispatchFlags flags, void *userdata) {
3192 const JsonDispatch *p;
3193 size_t i, n, m;
3194 int r, done = 0;
3195 bool *found;
3196
3197 if (!json_variant_is_object(v)) {
3198 json_log(v, flags, 0, "JSON variant is not an object.");
3199
3200 if (flags & JSON_PERMISSIVE)
3201 return 0;
3202
3203 return -EINVAL;
3204 }
3205
3206 for (p = table, m = 0; p->name; p++)
3207 m++;
3208
3209 found = newa0(bool, m);
3210
3211 n = json_variant_elements(v);
3212 for (i = 0; i < n; i += 2) {
3213 JsonVariant *key, *value;
3214
3215 assert_se(key = json_variant_by_index(v, i));
3216 assert_se(value = json_variant_by_index(v, i+1));
3217
3218 for (p = table; p->name; p++)
3219 if (p->name == (const char*) -1 ||
3220 streq_ptr(json_variant_string(key), p->name))
3221 break;
3222
3223 if (p->name) { /* Found a matching entry! :-) */
3224 JsonDispatchFlags merged_flags;
3225
3226 merged_flags = flags | p->flags;
3227
3228 if (p->type != _JSON_VARIANT_TYPE_INVALID &&
3229 !json_variant_has_type(value, p->type)) {
3230
3231 json_log(value, merged_flags, 0,
3232 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key),
3233 json_variant_type_to_string(json_variant_type(value)), json_variant_type_to_string(p->type));
3234
3235 if (merged_flags & JSON_PERMISSIVE)
3236 continue;
3237
3238 return -EINVAL;
3239 }
3240
3241 if (found[p-table]) {
3242 json_log(value, merged_flags, 0, "Duplicate object field '%s'.", json_variant_string(key));
3243
3244 if (merged_flags & JSON_PERMISSIVE)
3245 continue;
3246
3247 return -ENOTUNIQ;
3248 }
3249
3250 found[p-table] = true;
3251
3252 if (p->callback) {
3253 r = p->callback(json_variant_string(key), value, merged_flags, (uint8_t*) userdata + p->offset);
3254 if (r < 0) {
3255 if (merged_flags & JSON_PERMISSIVE)
3256 continue;
3257
3258 return r;
3259 }
3260 }
3261
3262 done ++;
3263
3264 } else { /* Didn't find a matching entry! :-( */
3265
3266 if (bad) {
3267 r = bad(json_variant_string(key), value, flags, userdata);
3268 if (r < 0) {
3269 if (flags & JSON_PERMISSIVE)
3270 continue;
3271
3272 return r;
3273 } else
3274 done ++;
3275
3276 } else {
3277 json_log(value, flags, 0, "Unexpected object field '%s'.", json_variant_string(key));
3278
3279 if (flags & JSON_PERMISSIVE)
3280 continue;
3281
3282 return -EADDRNOTAVAIL;
3283 }
3284 }
3285 }
3286
3287 for (p = table; p->name; p++) {
3288 JsonDispatchFlags merged_flags = p->flags | flags;
3289
3290 if ((merged_flags & JSON_MANDATORY) && !found[p-table]) {
3291 json_log(v, merged_flags, 0, "Missing object field '%s'.", p->name);
3292
3293 if ((merged_flags & JSON_PERMISSIVE))
3294 continue;
3295
3296 return -ENXIO;
3297 }
3298 }
3299
3300 return done;
3301 }
3302
3303 int json_dispatch_boolean(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3304 bool *b = userdata;
3305
3306 assert(variant);
3307 assert(b);
3308
3309 if (!json_variant_is_boolean(variant))
3310 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a boolean.", strna(name));
3311
3312 *b = json_variant_boolean(variant);
3313 return 0;
3314 }
3315
3316 int json_dispatch_tristate(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3317 int *b = userdata;
3318
3319 assert(variant);
3320 assert(b);
3321
3322 if (!json_variant_is_boolean(variant))
3323 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a boolean.", strna(name));
3324
3325 *b = json_variant_boolean(variant);
3326 return 0;
3327 }
3328
3329 int json_dispatch_integer(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3330 intmax_t *i = userdata;
3331
3332 assert(variant);
3333 assert(i);
3334
3335 if (!json_variant_is_integer(variant))
3336 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an integer.", strna(name));
3337
3338 *i = json_variant_integer(variant);
3339 return 0;
3340 }
3341
3342 int json_dispatch_unsigned(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3343 uintmax_t *u = userdata;
3344
3345 assert(variant);
3346 assert(u);
3347
3348 if (!json_variant_is_unsigned(variant))
3349 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an unsigned integer.", strna(name));
3350
3351 *u = json_variant_unsigned(variant);
3352 return 0;
3353 }
3354
3355 int json_dispatch_uint32(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3356 uint32_t *u = userdata;
3357
3358 assert(variant);
3359 assert(u);
3360
3361 if (!json_variant_is_unsigned(variant))
3362 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an unsigned integer.", strna(name));
3363
3364 if (json_variant_unsigned(variant) > UINT32_MAX)
3365 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
3366
3367 *u = (uint32_t) json_variant_unsigned(variant);
3368 return 0;
3369 }
3370
3371 int json_dispatch_int32(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3372 int32_t *i = userdata;
3373
3374 assert(variant);
3375 assert(i);
3376
3377 if (!json_variant_is_integer(variant))
3378 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an integer.", strna(name));
3379
3380 if (json_variant_integer(variant) < INT32_MIN || json_variant_integer(variant) > INT32_MAX)
3381 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
3382
3383 *i = (int32_t) json_variant_integer(variant);
3384 return 0;
3385 }
3386
3387 int json_dispatch_string(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3388 char **s = userdata;
3389 int r;
3390
3391 assert(variant);
3392 assert(s);
3393
3394 if (json_variant_is_null(variant)) {
3395 *s = mfree(*s);
3396 return 0;
3397 }
3398
3399 if (!json_variant_is_string(variant))
3400 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a string.", strna(name));
3401
3402 r = free_and_strdup(s, json_variant_string(variant));
3403 if (r < 0)
3404 return json_log(variant, flags, r, "Failed to allocate string: %m");
3405
3406 return 0;
3407 }
3408
3409 int json_dispatch_strv(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3410 _cleanup_strv_free_ char **l = NULL;
3411 char ***s = userdata;
3412 JsonVariant *e;
3413 int r;
3414
3415 assert(variant);
3416 assert(s);
3417
3418 if (json_variant_is_null(variant)) {
3419 *s = strv_free(*s);
3420 return 0;
3421 }
3422
3423 if (!json_variant_is_array(variant))
3424 return json_log(variant, SYNTHETIC_ERRNO(EINVAL), flags, "JSON field '%s' is not an array.", strna(name));
3425
3426 JSON_VARIANT_ARRAY_FOREACH(e, variant) {
3427 if (!json_variant_is_string(e))
3428 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "JSON array element is not a string.");
3429
3430 r = strv_extend(&l, json_variant_string(e));
3431 if (r < 0)
3432 return json_log(e, flags, r, "Failed to append array element: %m");
3433 }
3434
3435 strv_free_and_replace(*s, l);
3436 return 0;
3437 }
3438
3439 int json_dispatch_variant(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) {
3440 JsonVariant **p = userdata;
3441
3442 assert(variant);
3443 assert(p);
3444
3445 json_variant_unref(*p);
3446 *p = json_variant_ref(variant);
3447
3448 return 0;
3449 }
3450
3451 static const char* const json_variant_type_table[_JSON_VARIANT_TYPE_MAX] = {
3452 [JSON_VARIANT_STRING] = "string",
3453 [JSON_VARIANT_INTEGER] = "integer",
3454 [JSON_VARIANT_UNSIGNED] = "unsigned",
3455 [JSON_VARIANT_REAL] = "real",
3456 [JSON_VARIANT_NUMBER] = "number",
3457 [JSON_VARIANT_BOOLEAN] = "boolean",
3458 [JSON_VARIANT_ARRAY] = "array",
3459 [JSON_VARIANT_OBJECT] = "object",
3460 [JSON_VARIANT_NULL] = "null",
3461 };
3462
3463 DEFINE_STRING_TABLE_LOOKUP(json_variant_type, JsonVariantType);