1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include "sd-messages.h"
13 #include "alloc-util.h"
17 #include "hexdecoct.h"
18 #include "json-internal.h"
21 #include "string-table.h"
22 #include "string-util.h"
24 #include "terminal-util.h"
27 /* Refuse putting together variants with a larger depth than 4K by default (as a protection against overflowing stacks
28 * if code processes JSON objects recursively. Note that we store the depth in an uint16_t, hence make sure this
30 * The value was 16k, but it was discovered to be too high on llvm/x86-64. See also the issue #10738. */
31 #define DEPTH_MAX (4U*1024U)
32 assert_cc(DEPTH_MAX
<= UINT16_MAX
);
34 typedef struct JsonSource
{
35 /* When we parse from a file or similar, encodes the filename, to indicate the source of a json variant */
42 /* On x86-64 this whole structure should have a size of 6 * 64 bit = 48 bytes */
45 /* We either maintain a reference counter for this variant itself, or we are embedded into an
46 * array/object, in which case only that surrounding object is ref-counted. (If 'embedded' is false,
50 /* If this JsonVariant is part of an array/object, then this field points to the surrounding
51 * JSON_VARIANT_ARRAY/JSON_VARIANT_OBJECT object. (If 'embedded' is true, see below.) */
55 /* If this was parsed from some file or buffer, this stores where from, as well as the source line/column */
57 unsigned line
, column
;
59 JsonVariantType type
:5;
61 /* A marker whether this variant is embedded into in array/object or not. If true, the 'parent' pointer above
62 * is valid. If false, the 'n_ref' field above is valid instead. */
65 /* In some conditions (for example, if this object is part of an array of strings or objects), we don't store
66 * any data inline, but instead simply reference an external object and act as surrogate of it. In that case
67 * this bool is set, and the external object is referenced through the .reference field below. */
70 /* While comparing two arrays, we use this for marking what we already have seen */
73 /* The current 'depth' of the JsonVariant, i.e. how many levels of member variants this has */
77 /* For simple types we store the value in-line. */
80 /* For objects and arrays we store the number of elements immediately following */
83 /* If is_reference as indicated above is set, this is where the reference object is actually stored. */
84 JsonVariant
*reference
;
86 /* Strings are placed immediately after the structure. Note that when this is a JsonVariant embedded
87 * into an array we might encode strings up to INLINE_STRING_LENGTH characters directly inside the
88 * element, while longer strings are stored as references. When this object is not embedded into an
89 * array, but stand-alone we allocate the right size for the whole structure, i.e. the array might be
90 * much larger than INLINE_STRING_LENGTH.
92 * Note that because we want to allocate arrays of the JsonVariant structure we specify [0] here,
93 * rather than the prettier []. If we wouldn't, then this char array would have undefined size, and so
94 * would the union and then the struct this is included in. And of structures with undefined size we
95 * can't allocate arrays (at least not easily). */
100 /* Inside string arrays we have a series of JasonVariant structures one after the other. In this case, strings longer
101 * than INLINE_STRING_MAX are stored as references, and all shorter ones inline. (This means — on x86-64 — strings up
102 * to 15 chars are stored within the array elements, and all others in separate allocations) */
103 #define INLINE_STRING_MAX (sizeof(JsonVariant) - offsetof(JsonVariant, string) - 1U)
105 /* Let's make sure this structure isn't increased in size accidentally. This check is only for our most relevant arch
108 assert_cc(sizeof(JsonVariant
) == 48U);
109 assert_cc(INLINE_STRING_MAX
== 15U);
112 static JsonSource
* json_source_new(const char *name
) {
117 s
= malloc(offsetof(JsonSource
, name
) + strlen(name
) + 1);
124 strcpy(s
->name
, name
);
129 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(JsonSource
, json_source
, mfree
);
131 static bool json_source_equal(JsonSource
*a
, JsonSource
*b
) {
138 return streq(a
->name
, b
->name
);
141 DEFINE_TRIVIAL_CLEANUP_FUNC(JsonSource
*, json_source_unref
);
143 /* There are four kind of JsonVariant* pointers:
146 * 2. A 'regular' one, i.e. pointing to malloc() memory
147 * 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.
148 * 4. A 'const string' one, i.e. a pointer to a const string.
150 * The four kinds of pointers can be discerned like this:
152 * Detecting #1 is easy, just compare with NULL. Detecting #3 is similarly easy: all magic pointers are below
153 * _JSON_VARIANT_MAGIC_MAX (which is pretty low, within the first memory page, which is special on Linux and other
154 * 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,
155 * otherwise #4. This makes use of the fact that malloc() will return "maximum aligned" memory, which definitely
156 * means the pointer is even. This means we can use the uneven pointers to reference static strings, as long as we
157 * make sure that all static strings used like this are aligned to 2 (or higher), and that we mask the bit on
158 * access. The JSON_VARIANT_STRING_CONST() macro encodes strings as JsonVariant* pointers, with the bit set. */
160 static bool json_variant_is_magic(const JsonVariant
*v
) {
164 return v
< _JSON_VARIANT_MAGIC_MAX
;
167 static bool json_variant_is_const_string(const JsonVariant
*v
) {
169 if (v
< _JSON_VARIANT_MAGIC_MAX
)
172 /* A proper JsonVariant is aligned to whatever malloc() aligns things too, which is definitely not uneven. We
173 * hence use all uneven pointers as indicators for const strings. */
175 return (((uintptr_t) v
) & 1) != 0;
178 static bool json_variant_is_regular(const JsonVariant
*v
) {
180 if (v
< _JSON_VARIANT_MAGIC_MAX
)
183 return (((uintptr_t) v
) & 1) == 0;
186 static JsonVariant
*json_variant_dereference(JsonVariant
*v
) {
188 /* Recursively dereference variants that are references to other variants */
193 if (!json_variant_is_regular(v
))
196 if (!v
->is_reference
)
199 return json_variant_dereference(v
->reference
);
202 static uint16_t json_variant_depth(JsonVariant
*v
) {
204 v
= json_variant_dereference(v
);
208 if (!json_variant_is_regular(v
))
214 static JsonVariant
*json_variant_normalize(JsonVariant
*v
) {
216 /* Converts json variants to their normalized form, i.e. fully dereferenced and wherever possible converted to
217 * the "magic" version if there is one */
222 v
= json_variant_dereference(v
);
224 switch (json_variant_type(v
)) {
226 case JSON_VARIANT_BOOLEAN
:
227 return json_variant_boolean(v
) ? JSON_VARIANT_MAGIC_TRUE
: JSON_VARIANT_MAGIC_FALSE
;
229 case JSON_VARIANT_NULL
:
230 return JSON_VARIANT_MAGIC_NULL
;
232 case JSON_VARIANT_INTEGER
:
233 return json_variant_integer(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_INTEGER
: v
;
235 case JSON_VARIANT_UNSIGNED
:
236 return json_variant_unsigned(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_UNSIGNED
: v
;
238 case JSON_VARIANT_REAL
:
239 #pragma GCC diagnostic push
240 #pragma GCC diagnostic ignored "-Wfloat-equal"
241 return json_variant_real(v
) == 0.0 ? JSON_VARIANT_MAGIC_ZERO_REAL
: v
;
242 #pragma GCC diagnostic pop
244 case JSON_VARIANT_STRING
:
245 return isempty(json_variant_string(v
)) ? JSON_VARIANT_MAGIC_EMPTY_STRING
: v
;
247 case JSON_VARIANT_ARRAY
:
248 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_ARRAY
: v
;
250 case JSON_VARIANT_OBJECT
:
251 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_OBJECT
: v
;
258 static JsonVariant
*json_variant_conservative_normalize(JsonVariant
*v
) {
260 /* Much like json_variant_normalize(), but won't simplify if the variant has a source/line location attached to
261 * it, in order not to lose context */
266 if (!json_variant_is_regular(v
))
269 if (v
->source
|| v
->line
> 0 || v
->column
> 0)
272 return json_variant_normalize(v
);
275 static int json_variant_new(JsonVariant
**ret
, JsonVariantType type
, size_t space
) {
278 assert_return(ret
, -EINVAL
);
280 v
= malloc0(offsetof(JsonVariant
, value
) + space
);
291 int json_variant_new_integer(JsonVariant
**ret
, intmax_t i
) {
295 assert_return(ret
, -EINVAL
);
298 *ret
= JSON_VARIANT_MAGIC_ZERO_INTEGER
;
302 r
= json_variant_new(&v
, JSON_VARIANT_INTEGER
, sizeof(i
));
306 v
->value
.integer
= i
;
312 int json_variant_new_unsigned(JsonVariant
**ret
, uintmax_t u
) {
316 assert_return(ret
, -EINVAL
);
318 *ret
= JSON_VARIANT_MAGIC_ZERO_UNSIGNED
;
322 r
= json_variant_new(&v
, JSON_VARIANT_UNSIGNED
, sizeof(u
));
332 int json_variant_new_real(JsonVariant
**ret
, long double d
) {
336 assert_return(ret
, -EINVAL
);
338 #pragma GCC diagnostic push
339 #pragma GCC diagnostic ignored "-Wfloat-equal"
341 #pragma GCC diagnostic pop
342 *ret
= JSON_VARIANT_MAGIC_ZERO_REAL
;
346 r
= json_variant_new(&v
, JSON_VARIANT_REAL
, sizeof(d
));
356 int json_variant_new_boolean(JsonVariant
**ret
, bool b
) {
357 assert_return(ret
, -EINVAL
);
360 *ret
= JSON_VARIANT_MAGIC_TRUE
;
362 *ret
= JSON_VARIANT_MAGIC_FALSE
;
367 int json_variant_new_null(JsonVariant
**ret
) {
368 assert_return(ret
, -EINVAL
);
370 *ret
= JSON_VARIANT_MAGIC_NULL
;
374 int json_variant_new_stringn(JsonVariant
**ret
, const char *s
, size_t n
) {
378 assert_return(ret
, -EINVAL
);
380 assert_return(n
== 0, -EINVAL
);
381 return json_variant_new_null(ret
);
384 *ret
= JSON_VARIANT_MAGIC_EMPTY_STRING
;
388 r
= json_variant_new(&v
, JSON_VARIANT_STRING
, n
+ 1);
392 memcpy(v
->string
, s
, n
);
399 static void json_variant_set(JsonVariant
*a
, JsonVariant
*b
) {
402 b
= json_variant_dereference(b
);
404 a
->type
= JSON_VARIANT_NULL
;
408 a
->type
= json_variant_type(b
);
411 case JSON_VARIANT_INTEGER
:
412 a
->value
.integer
= json_variant_integer(b
);
415 case JSON_VARIANT_UNSIGNED
:
416 a
->value
.unsig
= json_variant_unsigned(b
);
419 case JSON_VARIANT_REAL
:
420 a
->value
.real
= json_variant_real(b
);
423 case JSON_VARIANT_BOOLEAN
:
424 a
->value
.boolean
= json_variant_boolean(b
);
427 case JSON_VARIANT_STRING
: {
430 assert_se(s
= json_variant_string(b
));
432 /* Short strings we can store inline */
433 if (strnlen(s
, INLINE_STRING_MAX
+1) <= INLINE_STRING_MAX
) {
434 strcpy(a
->string
, s
);
438 /* For longer strings, use a reference… */
442 case JSON_VARIANT_ARRAY
:
443 case JSON_VARIANT_OBJECT
:
444 a
->is_reference
= true;
445 a
->reference
= json_variant_ref(json_variant_conservative_normalize(b
));
448 case JSON_VARIANT_NULL
:
452 assert_not_reached("Unexpected variant type");
456 static void json_variant_copy_source(JsonVariant
*v
, JsonVariant
*from
) {
460 if (!json_variant_is_regular(from
))
463 v
->line
= from
->line
;
464 v
->column
= from
->column
;
465 v
->source
= json_source_ref(from
->source
);
468 int json_variant_new_array(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
469 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
471 assert_return(ret
, -EINVAL
);
473 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
476 assert_return(array
, -EINVAL
);
478 v
= new(JsonVariant
, n
+ 1);
484 .type
= JSON_VARIANT_ARRAY
,
487 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
488 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
489 *c
= array
[v
->n_elements
];
492 d
= json_variant_depth(c
);
493 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
503 json_variant_set(w
, c
);
504 json_variant_copy_source(w
, c
);
511 int json_variant_new_array_bytes(JsonVariant
**ret
, const void *p
, size_t n
) {
515 assert_return(ret
, -EINVAL
);
517 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
520 assert_return(p
, -EINVAL
);
522 v
= new(JsonVariant
, n
+ 1);
528 .type
= JSON_VARIANT_ARRAY
,
533 for (i
= 0; i
< n
; i
++) {
534 JsonVariant
*w
= v
+ 1 + i
;
539 .type
= JSON_VARIANT_UNSIGNED
,
540 .value
.unsig
= ((const uint8_t*) p
)[i
],
548 int json_variant_new_array_strv(JsonVariant
**ret
, char **l
) {
549 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
557 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
561 v
= new(JsonVariant
, n
+ 1);
567 .type
= JSON_VARIANT_ARRAY
,
571 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
572 JsonVariant
*w
= v
+ 1 + v
->n_elements
;
578 .type
= JSON_VARIANT_STRING
,
581 k
= strlen(l
[v
->n_elements
]);
583 if (k
> INLINE_STRING_MAX
) {
584 /* If string is too long, store it as reference. */
586 r
= json_variant_new_stringn(&w
->reference
, l
[v
->n_elements
], k
);
590 w
->is_reference
= true;
592 memcpy(w
->string
, l
[v
->n_elements
], k
+1);
599 int json_variant_new_object(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
600 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
602 assert_return(ret
, -EINVAL
);
604 *ret
= JSON_VARIANT_MAGIC_EMPTY_OBJECT
;
607 assert_return(array
, -EINVAL
);
608 assert_return(n
% 2 == 0, -EINVAL
);
610 v
= new(JsonVariant
, n
+ 1);
616 .type
= JSON_VARIANT_OBJECT
,
619 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
620 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
621 *c
= array
[v
->n_elements
];
624 if ((v
->n_elements
& 1) == 0 &&
625 !json_variant_is_string(c
))
626 return -EINVAL
; /* Every second one needs to be a string, as it is the key name */
628 d
= json_variant_depth(c
);
629 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
639 json_variant_set(w
, c
);
640 json_variant_copy_source(w
, c
);
647 static void json_variant_free_inner(JsonVariant
*v
) {
650 if (!json_variant_is_regular(v
))
653 json_source_unref(v
->source
);
655 if (v
->is_reference
) {
656 json_variant_unref(v
->reference
);
660 if (IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
)) {
663 for (i
= 0; i
< v
->n_elements
; i
++)
664 json_variant_free_inner(v
+ 1 + i
);
668 JsonVariant
*json_variant_ref(JsonVariant
*v
) {
671 if (!json_variant_is_regular(v
))
675 json_variant_ref(v
->parent
); /* ref the compounding variant instead */
677 assert(v
->n_ref
> 0);
684 JsonVariant
*json_variant_unref(JsonVariant
*v
) {
687 if (!json_variant_is_regular(v
))
691 json_variant_unref(v
->parent
);
693 assert(v
->n_ref
> 0);
697 json_variant_free_inner(v
);
705 void json_variant_unref_many(JsonVariant
**array
, size_t n
) {
708 assert(array
|| n
== 0);
710 for (i
= 0; i
< n
; i
++)
711 json_variant_unref(array
[i
]);
714 const char *json_variant_string(JsonVariant
*v
) {
717 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
719 if (json_variant_is_magic(v
))
721 if (json_variant_is_const_string(v
)) {
722 uintptr_t p
= (uintptr_t) v
;
724 assert((p
& 1) != 0);
725 return (const char*) (p
^ 1U);
729 return json_variant_string(v
->reference
);
730 if (v
->type
!= JSON_VARIANT_STRING
)
736 log_debug("Non-string JSON variant requested as string, returning NULL.");
740 bool json_variant_boolean(JsonVariant
*v
) {
743 if (v
== JSON_VARIANT_MAGIC_TRUE
)
745 if (v
== JSON_VARIANT_MAGIC_FALSE
)
747 if (!json_variant_is_regular(v
))
749 if (v
->type
!= JSON_VARIANT_BOOLEAN
)
752 return json_variant_boolean(v
->reference
);
754 return v
->value
.boolean
;
757 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
761 intmax_t json_variant_integer(JsonVariant
*v
) {
764 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
765 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
766 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
768 if (!json_variant_is_regular(v
))
771 return json_variant_integer(v
->reference
);
775 case JSON_VARIANT_INTEGER
:
776 return v
->value
.integer
;
778 case JSON_VARIANT_UNSIGNED
:
779 if (v
->value
.unsig
<= INTMAX_MAX
)
780 return (intmax_t) v
->value
.unsig
;
782 log_debug("Unsigned integer %ju requested as signed integer and out of range, returning 0.", v
->value
.unsig
);
785 case JSON_VARIANT_REAL
: {
788 converted
= (intmax_t) v
->value
.real
;
790 #pragma GCC diagnostic push
791 #pragma GCC diagnostic ignored "-Wfloat-equal"
792 if ((long double) converted
== v
->value
.real
)
793 #pragma GCC diagnostic pop
796 log_debug("Real %Lg requested as integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
805 log_debug("Non-integer JSON variant requested as integer, returning 0.");
809 uintmax_t json_variant_unsigned(JsonVariant
*v
) {
812 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
813 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
814 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
816 if (!json_variant_is_regular(v
))
819 return json_variant_integer(v
->reference
);
823 case JSON_VARIANT_INTEGER
:
824 if (v
->value
.integer
>= 0)
825 return (uintmax_t) v
->value
.integer
;
827 log_debug("Signed integer %ju requested as unsigned integer and out of range, returning 0.", v
->value
.integer
);
830 case JSON_VARIANT_UNSIGNED
:
831 return v
->value
.unsig
;
833 case JSON_VARIANT_REAL
: {
836 converted
= (uintmax_t) v
->value
.real
;
838 #pragma GCC diagnostic push
839 #pragma GCC diagnostic ignored "-Wfloat-equal"
840 if ((long double) converted
== v
->value
.real
)
841 #pragma GCC diagnostic pop
844 log_debug("Real %Lg requested as unsigned integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
853 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
857 long double json_variant_real(JsonVariant
*v
) {
860 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
861 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
862 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
864 if (!json_variant_is_regular(v
))
867 return json_variant_real(v
->reference
);
871 case JSON_VARIANT_REAL
:
872 return v
->value
.real
;
874 case JSON_VARIANT_INTEGER
: {
875 long double converted
;
877 converted
= (long double) v
->value
.integer
;
879 if ((intmax_t) converted
== v
->value
.integer
)
882 log_debug("Signed integer %ji requested as real, and cannot be converted losslessly, returning 0.", v
->value
.integer
);
886 case JSON_VARIANT_UNSIGNED
: {
887 long double converted
;
889 converted
= (long double) v
->value
.unsig
;
891 if ((uintmax_t) converted
== v
->value
.unsig
)
894 log_debug("Unsigned integer %ju requested as real, and cannot be converted losslessly, returning 0.", v
->value
.unsig
);
903 log_debug("Non-integer JSON variant requested as integer, returning 0.");
907 bool json_variant_is_negative(JsonVariant
*v
) {
910 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
911 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
912 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
914 if (!json_variant_is_regular(v
))
917 return json_variant_is_negative(v
->reference
);
919 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
920 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
925 case JSON_VARIANT_REAL
:
926 return v
->value
.real
< 0;
928 case JSON_VARIANT_INTEGER
:
929 return v
->value
.integer
< 0;
931 case JSON_VARIANT_UNSIGNED
:
939 log_debug("Non-integer JSON variant tested for negativity, returning false.");
943 JsonVariantType
json_variant_type(JsonVariant
*v
) {
946 return _JSON_VARIANT_TYPE_INVALID
;
948 if (json_variant_is_const_string(v
))
949 return JSON_VARIANT_STRING
;
951 if (v
== JSON_VARIANT_MAGIC_TRUE
|| v
== JSON_VARIANT_MAGIC_FALSE
)
952 return JSON_VARIANT_BOOLEAN
;
954 if (v
== JSON_VARIANT_MAGIC_NULL
)
955 return JSON_VARIANT_NULL
;
957 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
)
958 return JSON_VARIANT_INTEGER
;
960 if (v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
)
961 return JSON_VARIANT_UNSIGNED
;
963 if (v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
964 return JSON_VARIANT_REAL
;
966 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
967 return JSON_VARIANT_STRING
;
969 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
)
970 return JSON_VARIANT_ARRAY
;
972 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
973 return JSON_VARIANT_OBJECT
;
978 bool json_variant_has_type(JsonVariant
*v
, JsonVariantType type
) {
981 v
= json_variant_dereference(v
);
985 rt
= json_variant_type(v
);
989 /* If it's a const string, then it only can be a string, and if it is not, it's not */
990 if (json_variant_is_const_string(v
))
993 /* All three magic zeroes qualify as integer, unsigned and as real */
994 if ((v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
|| v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
|| v
== JSON_VARIANT_MAGIC_ZERO_REAL
) &&
995 IN_SET(type
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
, JSON_VARIANT_NUMBER
))
998 /* All other magic variant types are only equal to themselves */
999 if (json_variant_is_magic(v
))
1002 /* Handle the "number" pseudo type */
1003 if (type
== JSON_VARIANT_NUMBER
)
1004 return IN_SET(rt
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
);
1006 /* Integer conversions are OK in many cases */
1007 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_UNSIGNED
)
1008 return v
->value
.integer
>= 0;
1009 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_INTEGER
)
1010 return v
->value
.unsig
<= INTMAX_MAX
;
1012 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1013 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_REAL
)
1014 return (intmax_t) (long double) v
->value
.integer
== v
->value
.integer
;
1015 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_REAL
)
1016 return (uintmax_t) (long double) v
->value
.unsig
== v
->value
.unsig
;
1018 #pragma GCC diagnostic push
1019 #pragma GCC diagnostic ignored "-Wfloat-equal"
1020 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1021 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_INTEGER
)
1022 return (long double) (intmax_t) v
->value
.real
== v
->value
.real
;
1023 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_UNSIGNED
)
1024 return (long double) (uintmax_t) v
->value
.real
== v
->value
.real
;
1025 #pragma GCC diagnostic pop
1030 size_t json_variant_elements(JsonVariant
*v
) {
1033 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1034 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1036 if (!json_variant_is_regular(v
))
1038 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1040 if (v
->is_reference
)
1041 return json_variant_elements(v
->reference
);
1043 return v
->n_elements
;
1046 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1050 JsonVariant
*json_variant_by_index(JsonVariant
*v
, size_t idx
) {
1053 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1054 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1056 if (!json_variant_is_regular(v
))
1058 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1060 if (v
->is_reference
)
1061 return json_variant_by_index(v
->reference
, idx
);
1062 if (idx
>= v
->n_elements
)
1065 return json_variant_conservative_normalize(v
+ 1 + idx
);
1068 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1072 JsonVariant
*json_variant_by_key_full(JsonVariant
*v
, const char *key
, JsonVariant
**ret_key
) {
1079 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1081 if (!json_variant_is_regular(v
))
1083 if (v
->type
!= JSON_VARIANT_OBJECT
)
1085 if (v
->is_reference
)
1086 return json_variant_by_key(v
->reference
, key
);
1088 for (i
= 0; i
< v
->n_elements
; i
+= 2) {
1091 p
= json_variant_dereference(v
+ 1 + i
);
1093 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1096 if (streq(json_variant_string(p
), key
)) {
1099 *ret_key
= json_variant_conservative_normalize(v
+ 1 + i
);
1101 return json_variant_conservative_normalize(v
+ 1 + i
+ 1);
1112 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1119 JsonVariant
*json_variant_by_key(JsonVariant
*v
, const char *key
) {
1120 return json_variant_by_key_full(v
, key
, NULL
);
1123 bool json_variant_equal(JsonVariant
*a
, JsonVariant
*b
) {
1126 a
= json_variant_normalize(a
);
1127 b
= json_variant_normalize(b
);
1132 t
= json_variant_type(a
);
1133 if (!json_variant_has_type(b
, t
))
1138 case JSON_VARIANT_STRING
:
1139 return streq(json_variant_string(a
), json_variant_string(b
));
1141 case JSON_VARIANT_INTEGER
:
1142 return json_variant_integer(a
) == json_variant_integer(b
);
1144 case JSON_VARIANT_UNSIGNED
:
1145 return json_variant_unsigned(a
) == json_variant_unsigned(b
);
1147 case JSON_VARIANT_REAL
:
1148 #pragma GCC diagnostic push
1149 #pragma GCC diagnostic ignored "-Wfloat-equal"
1150 return json_variant_real(a
) == json_variant_real(b
);
1151 #pragma GCC diagnostic pop
1153 case JSON_VARIANT_BOOLEAN
:
1154 return json_variant_boolean(a
) == json_variant_boolean(b
);
1156 case JSON_VARIANT_NULL
:
1159 case JSON_VARIANT_ARRAY
: {
1162 n
= json_variant_elements(a
);
1163 if (n
!= json_variant_elements(b
))
1166 for (i
= 0; i
< n
; i
++) {
1167 if (!json_variant_equal(json_variant_by_index(a
, i
), json_variant_by_index(b
, i
)))
1174 case JSON_VARIANT_OBJECT
: {
1177 n
= json_variant_elements(a
);
1178 if (n
!= json_variant_elements(b
))
1181 /* Iterate through all keys in 'a' */
1182 for (i
= 0; i
< n
; i
+= 2) {
1186 /* Match them against all keys in 'b' */
1187 for (j
= 0; j
< n
; j
+= 2) {
1190 key_b
= json_variant_by_index(b
, j
);
1192 /* During the first iteration unmark everything */
1194 key_b
->is_marked
= false;
1195 else if (key_b
->is_marked
) /* In later iterations if we already marked something, don't bother with it again */
1201 if (json_variant_equal(json_variant_by_index(a
, i
), key_b
) &&
1202 json_variant_equal(json_variant_by_index(a
, i
+1), json_variant_by_index(b
, j
+1))) {
1203 /* Key and values match! */
1204 key_b
->is_marked
= found
= true;
1206 /* In the first iteration we continue the inner loop since we want to mark
1207 * everything, otherwise exit the loop quickly after we found what we were
1222 assert_not_reached("Unknown variant type.");
1226 int json_variant_get_source(JsonVariant
*v
, const char **ret_source
, unsigned *ret_line
, unsigned *ret_column
) {
1227 assert_return(v
, -EINVAL
);
1230 *ret_source
= json_variant_is_regular(v
) && v
->source
? v
->source
->name
: NULL
;
1233 *ret_line
= json_variant_is_regular(v
) ? v
->line
: 0;
1236 *ret_column
= json_variant_is_regular(v
) ? v
->column
: 0;
1241 static int print_source(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, bool whitespace
) {
1244 if (!FLAGS_SET(flags
, JSON_FORMAT_SOURCE
|JSON_FORMAT_PRETTY
))
1247 if (!json_variant_is_regular(v
))
1250 if (!v
->source
&& v
->line
== 0 && v
->column
== 0)
1253 /* The max width we need to format the line numbers for this source file */
1254 w
= (v
->source
&& v
->source
->max_line
> 0) ?
1255 DECIMAL_STR_WIDTH(v
->source
->max_line
) :
1256 DECIMAL_STR_MAX(unsigned)-1;
1257 k
= (v
->source
&& v
->source
->max_column
> 0) ?
1258 DECIMAL_STR_WIDTH(v
->source
->max_column
) :
1259 DECIMAL_STR_MAX(unsigned) -1;
1264 n
= 1 + (v
->source
? strlen(v
->source
->name
) : 0) +
1265 ((v
->source
&& (v
->line
> 0 || v
->column
> 0)) ? 1 : 0) +
1266 (v
->line
> 0 ? w
: 0) +
1267 (((v
->source
|| v
->line
> 0) && v
->column
> 0) ? 1 : 0) +
1268 (v
->column
> 0 ? k
: 0) +
1271 for (i
= 0; i
< n
; i
++)
1277 fputs(v
->source
->name
, f
);
1278 if (v
->source
&& (v
->line
> 0 || v
->column
> 0))
1281 fprintf(f
, "%*u", (int) w
, v
->line
);
1282 if ((v
->source
|| v
->line
> 0) || v
->column
> 0)
1285 fprintf(f
, "%*u", (int) k
, v
->column
);
1294 static int json_format(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, const char *prefix
) {
1300 switch (json_variant_type(v
)) {
1302 case JSON_VARIANT_REAL
: {
1305 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
1306 if (loc
== (locale_t
) 0)
1309 if (flags
& JSON_FORMAT_COLOR
)
1310 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1312 fprintf(f
, "%.*Le", DECIMAL_DIG
, json_variant_real(v
));
1314 if (flags
& JSON_FORMAT_COLOR
)
1315 fputs(ANSI_NORMAL
, f
);
1321 case JSON_VARIANT_INTEGER
:
1322 if (flags
& JSON_FORMAT_COLOR
)
1323 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1325 fprintf(f
, "%" PRIdMAX
, json_variant_integer(v
));
1327 if (flags
& JSON_FORMAT_COLOR
)
1328 fputs(ANSI_NORMAL
, f
);
1331 case JSON_VARIANT_UNSIGNED
:
1332 if (flags
& JSON_FORMAT_COLOR
)
1333 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1335 fprintf(f
, "%" PRIuMAX
, json_variant_unsigned(v
));
1337 if (flags
& JSON_FORMAT_COLOR
)
1338 fputs(ANSI_NORMAL
, f
);
1341 case JSON_VARIANT_BOOLEAN
:
1343 if (flags
& JSON_FORMAT_COLOR
)
1344 fputs(ANSI_HIGHLIGHT
, f
);
1346 if (json_variant_boolean(v
))
1351 if (flags
& JSON_FORMAT_COLOR
)
1352 fputs(ANSI_NORMAL
, f
);
1356 case JSON_VARIANT_NULL
:
1357 if (flags
& JSON_FORMAT_COLOR
)
1358 fputs(ANSI_HIGHLIGHT
, f
);
1362 if (flags
& JSON_FORMAT_COLOR
)
1363 fputs(ANSI_NORMAL
, f
);
1366 case JSON_VARIANT_STRING
: {
1371 if (flags
& JSON_FORMAT_COLOR
)
1372 fputs(ANSI_GREEN
, f
);
1374 for (q
= json_variant_string(v
); *q
; q
++) {
1407 if ((signed char) *q
>= 0 && *q
< ' ')
1408 fprintf(f
, "\\u%04x", *q
);
1415 if (flags
& JSON_FORMAT_COLOR
)
1416 fputs(ANSI_NORMAL
, f
);
1422 case JSON_VARIANT_ARRAY
: {
1425 n
= json_variant_elements(v
);
1430 _cleanup_free_
char *joined
= NULL
;
1431 const char *prefix2
;
1433 if (flags
& JSON_FORMAT_PRETTY
) {
1434 joined
= strjoin(strempty(prefix
), "\t");
1441 prefix2
= strempty(prefix
);
1445 for (i
= 0; i
< n
; i
++) {
1448 assert_se(e
= json_variant_by_index(v
, i
));
1451 if (flags
& JSON_FORMAT_PRETTY
)
1457 if (flags
& JSON_FORMAT_PRETTY
) {
1458 print_source(f
, e
, flags
, false);
1462 r
= json_format(f
, e
, flags
, prefix2
);
1467 if (flags
& JSON_FORMAT_PRETTY
) {
1469 print_source(f
, v
, flags
, true);
1470 fputs(strempty(prefix
), f
);
1478 case JSON_VARIANT_OBJECT
: {
1481 n
= json_variant_elements(v
);
1486 _cleanup_free_
char *joined
= NULL
;
1487 const char *prefix2
;
1489 if (flags
& JSON_FORMAT_PRETTY
) {
1490 joined
= strjoin(strempty(prefix
), "\t");
1497 prefix2
= strempty(prefix
);
1501 for (i
= 0; i
< n
; i
+= 2) {
1504 e
= json_variant_by_index(v
, i
);
1507 if (flags
& JSON_FORMAT_PRETTY
)
1513 if (flags
& JSON_FORMAT_PRETTY
) {
1514 print_source(f
, e
, flags
, false);
1518 r
= json_format(f
, e
, flags
, prefix2
);
1522 fputs(flags
& JSON_FORMAT_PRETTY
? " : " : ":", f
);
1524 r
= json_format(f
, json_variant_by_index(v
, i
+1), flags
, prefix2
);
1529 if (flags
& JSON_FORMAT_PRETTY
) {
1531 print_source(f
, v
, flags
, true);
1532 fputs(strempty(prefix
), f
);
1541 assert_not_reached("Unexpected variant type.");
1547 int json_variant_format(JsonVariant
*v
, JsonFormatFlags flags
, char **ret
) {
1548 _cleanup_free_
char *s
= NULL
;
1552 assert_return(v
, -EINVAL
);
1553 assert_return(ret
, -EINVAL
);
1556 _cleanup_fclose_
FILE *f
= NULL
;
1558 f
= open_memstream(&s
, &sz
);
1562 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
1564 json_variant_dump(v
, flags
, f
, NULL
);
1566 r
= fflush_and_check(f
);
1577 void json_variant_dump(JsonVariant
*v
, JsonFormatFlags flags
, FILE *f
, const char *prefix
) {
1584 print_source(f
, v
, flags
, false);
1586 if (((flags
& (JSON_FORMAT_COLOR_AUTO
|JSON_FORMAT_COLOR
)) == JSON_FORMAT_COLOR_AUTO
) && colors_enabled())
1587 flags
|= JSON_FORMAT_COLOR
;
1589 if (flags
& JSON_FORMAT_SSE
)
1591 if (flags
& JSON_FORMAT_SEQ
)
1592 fputc('\x1e', f
); /* ASCII Record Separator */
1594 json_format(f
, v
, flags
, prefix
);
1596 if (flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_SEQ
|JSON_FORMAT_SSE
|JSON_FORMAT_NEWLINE
))
1598 if (flags
& JSON_FORMAT_SSE
)
1599 fputc('\n', f
); /* In case of SSE add a second newline */
1602 static int json_variant_copy(JsonVariant
**nv
, JsonVariant
*v
) {
1612 /* Let's copy the simple types literally, and the larger types by references */
1613 t
= json_variant_type(v
);
1615 case JSON_VARIANT_INTEGER
:
1616 k
= sizeof(intmax_t);
1617 value
.integer
= json_variant_integer(v
);
1621 case JSON_VARIANT_UNSIGNED
:
1622 k
= sizeof(uintmax_t);
1623 value
.unsig
= json_variant_unsigned(v
);
1627 case JSON_VARIANT_REAL
:
1628 k
= sizeof(long double);
1629 value
.real
= json_variant_real(v
);
1633 case JSON_VARIANT_BOOLEAN
:
1635 value
.boolean
= json_variant_boolean(v
);
1639 case JSON_VARIANT_NULL
:
1644 case JSON_VARIANT_STRING
:
1645 source
= json_variant_string(v
);
1646 k
= strnlen(source
, INLINE_STRING_MAX
+ 1);
1647 if (k
<= INLINE_STRING_MAX
) {
1655 /* Everything else copy by reference */
1657 c
= malloc0(offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*));
1663 c
->is_reference
= true;
1664 c
->reference
= json_variant_ref(json_variant_normalize(v
));
1670 c
= malloc0(offsetof(JsonVariant
, value
) + k
);
1677 memcpy_safe(&c
->value
, source
, k
);
1683 static bool json_single_ref(JsonVariant
*v
) {
1685 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
1687 if (!json_variant_is_regular(v
))
1691 return json_single_ref(v
->parent
);
1693 assert(v
->n_ref
> 0);
1694 return v
->n_ref
== 1;
1697 static int json_variant_set_source(JsonVariant
**v
, JsonSource
*source
, unsigned line
, unsigned column
) {
1703 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole referencer of
1704 * the object. If not, allocates a new object, possibly a surrogate for the original one */
1709 if (source
&& line
> source
->max_line
)
1710 source
->max_line
= line
;
1711 if (source
&& column
> source
->max_column
)
1712 source
->max_column
= column
;
1714 if (!json_variant_is_regular(*v
)) {
1716 if (!source
&& line
== 0 && column
== 0)
1720 if (json_source_equal((*v
)->source
, source
) &&
1721 (*v
)->line
== line
&&
1722 (*v
)->column
== column
)
1725 if (json_single_ref(*v
)) { /* Sole reference? */
1726 json_source_unref((*v
)->source
);
1727 (*v
)->source
= json_source_ref(source
);
1729 (*v
)->column
= column
;
1734 r
= json_variant_copy(&w
, *v
);
1738 assert(json_variant_is_regular(w
));
1739 assert(!w
->is_embedded
);
1740 assert(w
->n_ref
== 1);
1743 w
->source
= json_source_ref(source
);
1747 json_variant_unref(*v
);
1753 static void inc_lines_columns(unsigned *line
, unsigned *column
, const char *s
, size_t n
) {
1756 assert(s
|| n
== 0);
1763 } else if ((signed char) *s
>= 0 && *s
< 127) /* Process ASCII chars quickly */
1768 w
= utf8_encoded_valid_unichar(s
);
1769 if (w
< 0) /* count invalid unichars as normal characters */
1771 else if ((size_t) w
> n
) /* never read more than the specified number of characters */
1786 static int unhex_ucs2(const char *c
, uint16_t *ret
) {
1793 aa
= unhexchar(c
[0]);
1797 bb
= unhexchar(c
[1]);
1801 cc
= unhexchar(c
[2]);
1805 dd
= unhexchar(c
[3]);
1809 x
= ((uint16_t) aa
<< 12) |
1810 ((uint16_t) bb
<< 8) |
1811 ((uint16_t) cc
<< 4) |
1822 static int json_parse_string(const char **p
, char **ret
) {
1823 _cleanup_free_
char *s
= NULL
;
1824 size_t n
= 0, allocated
= 0;
1845 /* Check for control characters 0x00..0x1f */
1846 if (*c
> 0 && *c
< ' ')
1849 /* Check for control character 0x7f */
1864 return JSON_TOKEN_STRING
;
1874 if (IN_SET(*c
, '"', '\\', '/'))
1886 else if (*c
== 'u') {
1890 r
= unhex_ucs2(c
+ 1, &x
);
1896 if (!GREEDY_REALLOC(s
, allocated
, n
+ 5))
1899 if (!utf16_is_surrogate(x
))
1900 n
+= utf8_encode_unichar(s
+ n
, (char32_t
) x
);
1901 else if (utf16_is_trailing_surrogate(x
))
1906 if (c
[0] != '\\' || c
[1] != 'u')
1909 r
= unhex_ucs2(c
+ 2, &y
);
1915 if (!utf16_is_trailing_surrogate(y
))
1918 n
+= utf8_encode_unichar(s
+ n
, utf16_surrogate_pair_to_unichar(x
, y
));
1925 if (!GREEDY_REALLOC(s
, allocated
, n
+ 2))
1933 len
= utf8_encoded_valid_unichar(c
);
1937 if (!GREEDY_REALLOC(s
, allocated
, n
+ len
+ 1))
1940 memcpy(s
+ n
, c
, len
);
1946 static int json_parse_number(const char **p
, JsonValue
*ret
) {
1947 bool negative
= false, exponent_negative
= false, is_real
= false;
1948 long double x
= 0.0, y
= 0.0, exponent
= 0.0, shift
= 1.0;
1967 if (!strchr("123456789", *c
) || *c
== 0)
1974 if (i
< INTMAX_MIN
/ 10) /* overflow */
1977 intmax_t t
= 10 * i
;
1979 if (t
< INTMAX_MIN
+ (*c
- '0')) /* overflow */
1985 if (u
> UINTMAX_MAX
/ 10) /* overflow */
1988 uintmax_t t
= 10 * u
;
1990 if (t
> UINTMAX_MAX
- (*c
- '0')) /* overflow */
1998 x
= 10.0 * x
+ (*c
- '0');
2001 } while (strchr("0123456789", *c
) && *c
!= 0);
2008 if (!strchr("0123456789", *c
) || *c
== 0)
2012 y
= 10.0 * y
+ (*c
- '0');
2013 shift
= 10.0 * shift
;
2015 } while (strchr("0123456789", *c
) && *c
!= 0);
2018 if (IN_SET(*c
, 'e', 'E')) {
2023 exponent_negative
= true;
2025 } else if (*c
== '+')
2028 if (!strchr("0123456789", *c
) || *c
== 0)
2032 exponent
= 10.0 * exponent
+ (*c
- '0');
2034 } while (strchr("0123456789", *c
) && *c
!= 0);
2040 ret
->real
= ((negative
? -1.0 : 1.0) * (x
+ (y
/ shift
))) * exp10l((exponent_negative
? -1.0 : 1.0) * exponent
);
2041 return JSON_TOKEN_REAL
;
2042 } else if (negative
) {
2044 return JSON_TOKEN_INTEGER
;
2047 return JSON_TOKEN_UNSIGNED
;
2054 JsonValue
*ret_value
,
2055 unsigned *ret_line
, /* 'ret_line' returns the line at the beginning of this token */
2056 unsigned *ret_column
,
2058 unsigned *line
, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2061 unsigned start_line
, start_column
;
2062 const char *start
, *c
;
2082 t
= PTR_TO_INT(*state
);
2083 if (t
== STATE_NULL
) {
2089 /* Skip over the whitespace */
2090 n
= strspn(*p
, WHITESPACE
);
2091 inc_lines_columns(line
, column
, *p
, n
);
2094 /* Remember where we started processing this token */
2097 start_column
= *column
;
2101 *ret_value
= JSON_VALUE_NULL
;
2112 *state
= INT_TO_PTR(STATE_VALUE
);
2113 r
= JSON_TOKEN_OBJECT_OPEN
;
2116 } else if (*c
== '}') {
2118 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2119 r
= JSON_TOKEN_OBJECT_CLOSE
;
2122 } else if (*c
== '[') {
2124 *state
= INT_TO_PTR(STATE_VALUE
);
2125 r
= JSON_TOKEN_ARRAY_OPEN
;
2128 } else if (*c
== ']') {
2130 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2131 r
= JSON_TOKEN_ARRAY_CLOSE
;
2134 } else if (*c
== '"') {
2136 r
= json_parse_string(&c
, ret_string
);
2140 *ret_value
= JSON_VALUE_NULL
;
2141 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2144 } else if (strchr("-0123456789", *c
)) {
2146 r
= json_parse_number(&c
, ret_value
);
2151 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2154 } else if (startswith(c
, "true")) {
2156 ret_value
->boolean
= true;
2158 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2159 r
= JSON_TOKEN_BOOLEAN
;
2162 } else if (startswith(c
, "false")) {
2164 ret_value
->boolean
= false;
2166 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2167 r
= JSON_TOKEN_BOOLEAN
;
2170 } else if (startswith(c
, "null")) {
2172 *ret_value
= JSON_VALUE_NULL
;
2174 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2175 r
= JSON_TOKEN_NULL
;
2182 case STATE_VALUE_POST
:
2186 *state
= INT_TO_PTR(STATE_VALUE
);
2187 r
= JSON_TOKEN_COLON
;
2190 } else if (*c
== ',') {
2192 *state
= INT_TO_PTR(STATE_VALUE
);
2193 r
= JSON_TOKEN_COMMA
;
2196 } else if (*c
== '}') {
2198 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2199 r
= JSON_TOKEN_OBJECT_CLOSE
;
2202 } else if (*c
== ']') {
2204 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2205 r
= JSON_TOKEN_ARRAY_CLOSE
;
2212 assert_not_reached("Unexpected tokenizer state");
2217 *ret_value
= JSON_VALUE_NULL
;
2220 inc_lines_columns(line
, column
, start
, c
- start
);
2223 *ret_line
= start_line
;
2224 *ret_column
= start_column
;
2229 typedef enum JsonExpect
{
2230 /* The following values are used by json_parse() */
2233 EXPECT_OBJECT_FIRST_KEY
,
2234 EXPECT_OBJECT_NEXT_KEY
,
2235 EXPECT_OBJECT_COLON
,
2236 EXPECT_OBJECT_VALUE
,
2237 EXPECT_OBJECT_COMMA
,
2238 EXPECT_ARRAY_FIRST_ELEMENT
,
2239 EXPECT_ARRAY_NEXT_ELEMENT
,
2242 /* And these are used by json_build() */
2243 EXPECT_ARRAY_ELEMENT
,
2247 typedef struct JsonStack
{
2249 JsonVariant
**elements
;
2250 size_t n_elements
, n_elements_allocated
;
2251 unsigned line_before
;
2252 unsigned column_before
;
2253 size_t n_suppress
; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2256 static void json_stack_release(JsonStack
*s
) {
2259 json_variant_unref_many(s
->elements
, s
->n_elements
);
2260 s
->elements
= mfree(s
->elements
);
2263 static int json_parse_internal(
2269 bool continue_end
) {
2271 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2272 unsigned line_buffer
= 0, column_buffer
= 0;
2273 void *tokenizer_state
= NULL
;
2274 JsonStack
*stack
= NULL
;
2278 assert_return(input
, -EINVAL
);
2279 assert_return(ret
, -EINVAL
);
2283 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2286 stack
[0] = (JsonStack
) {
2287 .expect
= EXPECT_TOPLEVEL
,
2291 line
= &line_buffer
;
2293 column
= &column_buffer
;
2296 _cleanup_free_
char *string
= NULL
;
2297 unsigned line_token
, column_token
;
2298 JsonVariant
*add
= NULL
;
2303 assert(n_stack
> 0);
2304 current
= stack
+ n_stack
- 1;
2306 if (continue_end
&& current
->expect
== EXPECT_END
)
2309 token
= json_tokenize(&p
, &string
, &value
, &line_token
, &column_token
, &tokenizer_state
, line
, column
);
2317 case JSON_TOKEN_END
:
2318 if (current
->expect
!= EXPECT_END
) {
2323 assert(current
->n_elements
== 1);
2324 assert(n_stack
== 1);
2327 case JSON_TOKEN_COLON
:
2329 if (current
->expect
!= EXPECT_OBJECT_COLON
) {
2334 current
->expect
= EXPECT_OBJECT_VALUE
;
2337 case JSON_TOKEN_COMMA
:
2339 if (current
->expect
== EXPECT_OBJECT_COMMA
)
2340 current
->expect
= EXPECT_OBJECT_NEXT_KEY
;
2341 else if (current
->expect
== EXPECT_ARRAY_COMMA
)
2342 current
->expect
= EXPECT_ARRAY_NEXT_ELEMENT
;
2350 case JSON_TOKEN_OBJECT_OPEN
:
2352 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2357 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2361 current
= stack
+ n_stack
- 1;
2363 /* Prepare the expect for when we return from the child */
2364 if (current
->expect
== EXPECT_TOPLEVEL
)
2365 current
->expect
= EXPECT_END
;
2366 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2367 current
->expect
= EXPECT_OBJECT_COMMA
;
2369 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2370 current
->expect
= EXPECT_ARRAY_COMMA
;
2373 stack
[n_stack
++] = (JsonStack
) {
2374 .expect
= EXPECT_OBJECT_FIRST_KEY
,
2375 .line_before
= line_token
,
2376 .column_before
= column_token
,
2379 current
= stack
+ n_stack
- 1;
2382 case JSON_TOKEN_OBJECT_CLOSE
:
2383 if (!IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_COMMA
)) {
2388 assert(n_stack
> 1);
2390 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
2394 line_token
= current
->line_before
;
2395 column_token
= current
->column_before
;
2397 json_stack_release(current
);
2398 n_stack
--, current
--;
2402 case JSON_TOKEN_ARRAY_OPEN
:
2403 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2408 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2412 current
= stack
+ n_stack
- 1;
2414 /* Prepare the expect for when we return from the child */
2415 if (current
->expect
== EXPECT_TOPLEVEL
)
2416 current
->expect
= EXPECT_END
;
2417 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2418 current
->expect
= EXPECT_OBJECT_COMMA
;
2420 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2421 current
->expect
= EXPECT_ARRAY_COMMA
;
2424 stack
[n_stack
++] = (JsonStack
) {
2425 .expect
= EXPECT_ARRAY_FIRST_ELEMENT
,
2426 .line_before
= line_token
,
2427 .column_before
= column_token
,
2432 case JSON_TOKEN_ARRAY_CLOSE
:
2433 if (!IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_COMMA
)) {
2438 assert(n_stack
> 1);
2440 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2444 line_token
= current
->line_before
;
2445 column_token
= current
->column_before
;
2447 json_stack_release(current
);
2448 n_stack
--, current
--;
2451 case JSON_TOKEN_STRING
:
2452 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
)) {
2457 r
= json_variant_new_string(&add
, string
);
2461 if (current
->expect
== EXPECT_TOPLEVEL
)
2462 current
->expect
= EXPECT_END
;
2463 else if (IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_NEXT_KEY
))
2464 current
->expect
= EXPECT_OBJECT_COLON
;
2465 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2466 current
->expect
= EXPECT_OBJECT_COMMA
;
2468 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2469 current
->expect
= EXPECT_ARRAY_COMMA
;
2474 case JSON_TOKEN_REAL
:
2475 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2480 r
= json_variant_new_real(&add
, value
.real
);
2484 if (current
->expect
== EXPECT_TOPLEVEL
)
2485 current
->expect
= EXPECT_END
;
2486 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2487 current
->expect
= EXPECT_OBJECT_COMMA
;
2489 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2490 current
->expect
= EXPECT_ARRAY_COMMA
;
2495 case JSON_TOKEN_INTEGER
:
2496 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2501 r
= json_variant_new_integer(&add
, value
.integer
);
2505 if (current
->expect
== EXPECT_TOPLEVEL
)
2506 current
->expect
= EXPECT_END
;
2507 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2508 current
->expect
= EXPECT_OBJECT_COMMA
;
2510 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2511 current
->expect
= EXPECT_ARRAY_COMMA
;
2516 case JSON_TOKEN_UNSIGNED
:
2517 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2522 r
= json_variant_new_unsigned(&add
, value
.unsig
);
2526 if (current
->expect
== EXPECT_TOPLEVEL
)
2527 current
->expect
= EXPECT_END
;
2528 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2529 current
->expect
= EXPECT_OBJECT_COMMA
;
2531 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2532 current
->expect
= EXPECT_ARRAY_COMMA
;
2537 case JSON_TOKEN_BOOLEAN
:
2538 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2543 r
= json_variant_new_boolean(&add
, value
.boolean
);
2547 if (current
->expect
== EXPECT_TOPLEVEL
)
2548 current
->expect
= EXPECT_END
;
2549 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2550 current
->expect
= EXPECT_OBJECT_COMMA
;
2552 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2553 current
->expect
= EXPECT_ARRAY_COMMA
;
2558 case JSON_TOKEN_NULL
:
2559 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2564 r
= json_variant_new_null(&add
);
2568 if (current
->expect
== EXPECT_TOPLEVEL
)
2569 current
->expect
= EXPECT_END
;
2570 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2571 current
->expect
= EXPECT_OBJECT_COMMA
;
2573 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2574 current
->expect
= EXPECT_ARRAY_COMMA
;
2580 assert_not_reached("Unexpected token");
2584 (void) json_variant_set_source(&add
, source
, line_token
, column_token
);
2586 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
2591 current
->elements
[current
->n_elements
++] = add
;
2596 assert(n_stack
== 1);
2597 assert(stack
[0].n_elements
== 1);
2599 *ret
= json_variant_ref(stack
[0].elements
[0]);
2604 for (i
= 0; i
< n_stack
; i
++)
2605 json_stack_release(stack
+ i
);
2612 int json_parse(const char *input
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2613 return json_parse_internal(&input
, NULL
, ret
, ret_line
, ret_column
, false);
2616 int json_parse_continue(const char **p
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2617 return json_parse_internal(p
, NULL
, ret
, ret_line
, ret_column
, true);
2620 int json_parse_file(FILE *f
, const char *path
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2621 _cleanup_(json_source_unrefp
) JsonSource
*source
= NULL
;
2622 _cleanup_free_
char *text
= NULL
;
2627 r
= read_full_stream(f
, &text
, NULL
);
2629 r
= read_full_file(path
, &text
, NULL
);
2636 source
= json_source_new(path
);
2642 return json_parse_internal(&p
, source
, ret
, ret_line
, ret_column
, false);
2645 int json_buildv(JsonVariant
**ret
, va_list ap
) {
2646 JsonStack
*stack
= NULL
;
2647 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2650 assert_return(ret
, -EINVAL
);
2652 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2655 stack
[0] = (JsonStack
) {
2656 .expect
= EXPECT_TOPLEVEL
,
2660 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
2661 size_t n_subtract
= 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
2662 * have been added to the current variant */
2666 assert(n_stack
> 0);
2667 current
= stack
+ n_stack
- 1;
2669 if (current
->expect
== EXPECT_END
)
2672 command
= va_arg(ap
, int);
2676 case _JSON_BUILD_STRING
: {
2679 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2684 p
= va_arg(ap
, const char *);
2686 if (current
->n_suppress
== 0) {
2687 r
= json_variant_new_string(&add
, p
);
2694 if (current
->expect
== EXPECT_TOPLEVEL
)
2695 current
->expect
= EXPECT_END
;
2696 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2697 current
->expect
= EXPECT_OBJECT_KEY
;
2699 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2704 case _JSON_BUILD_INTEGER
: {
2707 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2712 j
= va_arg(ap
, intmax_t);
2714 if (current
->n_suppress
== 0) {
2715 r
= json_variant_new_integer(&add
, j
);
2722 if (current
->expect
== EXPECT_TOPLEVEL
)
2723 current
->expect
= EXPECT_END
;
2724 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2725 current
->expect
= EXPECT_OBJECT_KEY
;
2727 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2732 case _JSON_BUILD_UNSIGNED
: {
2735 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2740 j
= va_arg(ap
, uintmax_t);
2742 if (current
->n_suppress
== 0) {
2743 r
= json_variant_new_unsigned(&add
, j
);
2750 if (current
->expect
== EXPECT_TOPLEVEL
)
2751 current
->expect
= EXPECT_END
;
2752 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2753 current
->expect
= EXPECT_OBJECT_KEY
;
2755 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2760 case _JSON_BUILD_REAL
: {
2763 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2768 d
= va_arg(ap
, long double);
2770 if (current
->n_suppress
== 0) {
2771 r
= json_variant_new_real(&add
, d
);
2778 if (current
->expect
== EXPECT_TOPLEVEL
)
2779 current
->expect
= EXPECT_END
;
2780 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2781 current
->expect
= EXPECT_OBJECT_KEY
;
2783 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2788 case _JSON_BUILD_BOOLEAN
: {
2791 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2796 b
= va_arg(ap
, int);
2798 if (current
->n_suppress
== 0) {
2799 r
= json_variant_new_boolean(&add
, b
);
2806 if (current
->expect
== EXPECT_TOPLEVEL
)
2807 current
->expect
= EXPECT_END
;
2808 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2809 current
->expect
= EXPECT_OBJECT_KEY
;
2811 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2816 case _JSON_BUILD_NULL
:
2818 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2823 if (current
->n_suppress
== 0) {
2824 r
= json_variant_new_null(&add
);
2831 if (current
->expect
== EXPECT_TOPLEVEL
)
2832 current
->expect
= EXPECT_END
;
2833 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2834 current
->expect
= EXPECT_OBJECT_KEY
;
2836 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2840 case _JSON_BUILD_VARIANT
:
2842 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2847 /* Note that we don't care for current->n_suppress here, after all the variant is already
2848 * allocated anyway... */
2849 add
= va_arg(ap
, JsonVariant
*);
2851 add
= JSON_VARIANT_MAGIC_NULL
;
2853 json_variant_ref(add
);
2857 if (current
->expect
== EXPECT_TOPLEVEL
)
2858 current
->expect
= EXPECT_END
;
2859 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2860 current
->expect
= EXPECT_OBJECT_KEY
;
2862 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2866 case _JSON_BUILD_LITERAL
: {
2869 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2874 l
= va_arg(ap
, const char *);
2877 /* Note that we don't care for current->n_suppress here, we should generate parsing
2878 * errors even in suppressed object properties */
2880 r
= json_parse(l
, &add
, NULL
, NULL
);
2884 add
= JSON_VARIANT_MAGIC_NULL
;
2888 if (current
->expect
== EXPECT_TOPLEVEL
)
2889 current
->expect
= EXPECT_END
;
2890 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2891 current
->expect
= EXPECT_OBJECT_KEY
;
2893 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2898 case _JSON_BUILD_ARRAY_BEGIN
:
2900 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2905 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2909 current
= stack
+ n_stack
- 1;
2911 if (current
->expect
== EXPECT_TOPLEVEL
)
2912 current
->expect
= EXPECT_END
;
2913 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2914 current
->expect
= EXPECT_OBJECT_KEY
;
2916 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2918 stack
[n_stack
++] = (JsonStack
) {
2919 .expect
= EXPECT_ARRAY_ELEMENT
,
2920 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
2921 * new array, then we should
2922 * also suppress all array
2928 case _JSON_BUILD_ARRAY_END
:
2929 if (current
->expect
!= EXPECT_ARRAY_ELEMENT
) {
2934 assert(n_stack
> 1);
2936 if (current
->n_suppress
== 0) {
2937 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2944 json_stack_release(current
);
2945 n_stack
--, current
--;
2949 case _JSON_BUILD_STRV
: {
2952 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2957 l
= va_arg(ap
, char **);
2959 if (current
->n_suppress
== 0) {
2960 r
= json_variant_new_array_strv(&add
, l
);
2967 if (current
->expect
== EXPECT_TOPLEVEL
)
2968 current
->expect
= EXPECT_END
;
2969 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2970 current
->expect
= EXPECT_OBJECT_KEY
;
2972 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2977 case _JSON_BUILD_OBJECT_BEGIN
:
2979 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2984 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2988 current
= stack
+ n_stack
- 1;
2990 if (current
->expect
== EXPECT_TOPLEVEL
)
2991 current
->expect
= EXPECT_END
;
2992 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2993 current
->expect
= EXPECT_OBJECT_KEY
;
2995 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2997 stack
[n_stack
++] = (JsonStack
) {
2998 .expect
= EXPECT_OBJECT_KEY
,
2999 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3000 * new object, then we should
3001 * also suppress all object
3007 case _JSON_BUILD_OBJECT_END
:
3009 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3014 assert(n_stack
> 1);
3016 if (current
->n_suppress
== 0) {
3017 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
3024 json_stack_release(current
);
3025 n_stack
--, current
--;
3029 case _JSON_BUILD_PAIR
: {
3032 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3037 n
= va_arg(ap
, const char *);
3039 if (current
->n_suppress
== 0) {
3040 r
= json_variant_new_string(&add
, n
);
3047 current
->expect
= EXPECT_OBJECT_VALUE
;
3051 case _JSON_BUILD_PAIR_CONDITION
: {
3055 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3060 b
= va_arg(ap
, int);
3061 n
= va_arg(ap
, const char *);
3063 if (b
&& current
->n_suppress
== 0) {
3064 r
= json_variant_new_string(&add
, n
);
3069 n_subtract
= 1; /* we generated one item */
3071 if (!b
&& current
->n_suppress
!= (size_t) -1)
3072 current
->n_suppress
+= 2; /* Suppress this one and the next item */
3074 current
->expect
= EXPECT_OBJECT_VALUE
;
3078 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3079 if (add
&& current
->n_suppress
== 0) {
3080 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3085 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3088 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3089 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3090 * on this stack level */
3091 if (current
->n_suppress
!= (size_t) -1) {
3092 if (current
->n_suppress
<= n_subtract
) /* Saturated */
3093 current
->n_suppress
= 0;
3095 current
->n_suppress
-= n_subtract
;
3100 assert(n_stack
== 1);
3101 assert(stack
[0].n_elements
== 1);
3103 *ret
= json_variant_ref(stack
[0].elements
[0]);
3107 for (i
= 0; i
< n_stack
; i
++)
3108 json_stack_release(stack
+ i
);
3117 int json_build(JsonVariant
**ret
, ...) {
3122 r
= json_buildv(ret
, ap
);
3128 int json_log_internal(
3129 JsonVariant
*variant
,
3135 const char *format
, ...) {
3139 unsigned source_line
, source_column
;
3140 char buffer
[LINE_MAX
];
3145 errno
= ERRNO_VALUE(error
);
3147 va_start(ap
, format
);
3148 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
3152 r
= json_variant_get_source(variant
, &source
, &source_line
, &source_column
);
3161 if (source
&& source_line
> 0 && source_column
> 0)
3162 return log_struct_internal(
3163 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3166 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3167 "CONFIG_FILE=%s", source
,
3168 "CONFIG_LINE=%u", source_line
,
3169 "CONFIG_COLUMN=%u", source_column
,
3170 LOG_MESSAGE("%s:%u: %s", source
, line
, buffer
),
3173 return log_struct_internal(
3174 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3177 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3178 LOG_MESSAGE("%s", buffer
),
3182 int json_dispatch(JsonVariant
*v
, const JsonDispatch table
[], JsonDispatchCallback bad
, JsonDispatchFlags flags
, void *userdata
) {
3183 const JsonDispatch
*p
;
3188 if (!json_variant_is_object(v
)) {
3189 json_log(v
, flags
, 0, "JSON variant is not an object.");
3191 if (flags
& JSON_PERMISSIVE
)
3197 for (p
= table
, m
= 0; p
->name
; p
++)
3200 found
= newa0(bool, m
);
3202 n
= json_variant_elements(v
);
3203 for (i
= 0; i
< n
; i
+= 2) {
3204 JsonVariant
*key
, *value
;
3206 assert_se(key
= json_variant_by_index(v
, i
));
3207 assert_se(value
= json_variant_by_index(v
, i
+1));
3209 for (p
= table
; p
->name
; p
++)
3210 if (p
->name
== (const char*) -1 ||
3211 streq_ptr(json_variant_string(key
), p
->name
))
3214 if (p
->name
) { /* Found a matching entry! :-) */
3215 JsonDispatchFlags merged_flags
;
3217 merged_flags
= flags
| p
->flags
;
3219 if (p
->type
!= _JSON_VARIANT_TYPE_INVALID
&&
3220 !json_variant_has_type(value
, p
->type
)) {
3222 json_log(value
, merged_flags
, 0,
3223 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key
),
3224 json_variant_type_to_string(json_variant_type(value
)), json_variant_type_to_string(p
->type
));
3226 if (merged_flags
& JSON_PERMISSIVE
)
3232 if (found
[p
-table
]) {
3233 json_log(value
, merged_flags
, 0, "Duplicate object field '%s'.", json_variant_string(key
));
3235 if (merged_flags
& JSON_PERMISSIVE
)
3241 found
[p
-table
] = true;
3244 r
= p
->callback(json_variant_string(key
), value
, merged_flags
, (uint8_t*) userdata
+ p
->offset
);
3246 if (merged_flags
& JSON_PERMISSIVE
)
3255 } else { /* Didn't find a matching entry! :-( */
3258 r
= bad(json_variant_string(key
), value
, flags
, userdata
);
3260 if (flags
& JSON_PERMISSIVE
)
3268 json_log(value
, flags
, 0, "Unexpected object field '%s'.", json_variant_string(key
));
3270 if (flags
& JSON_PERMISSIVE
)
3273 return -EADDRNOTAVAIL
;
3278 for (p
= table
; p
->name
; p
++) {
3279 JsonDispatchFlags merged_flags
= p
->flags
| flags
;
3281 if ((merged_flags
& JSON_MANDATORY
) && !found
[p
-table
]) {
3282 json_log(v
, merged_flags
, 0, "Missing object field '%s'.", p
->name
);
3284 if ((merged_flags
& JSON_PERMISSIVE
))
3294 int json_dispatch_boolean(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3300 if (!json_variant_is_boolean(variant
)) {
3301 json_log(variant
, flags
, 0, "JSON field '%s' is not a boolean.", strna(name
));
3305 *b
= json_variant_boolean(variant
);
3309 int json_dispatch_tristate(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3315 if (!json_variant_is_boolean(variant
)) {
3316 json_log(variant
, flags
, 0, "JSON field '%s' is not a boolean.", strna(name
));
3320 *b
= json_variant_boolean(variant
);
3324 int json_dispatch_integer(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3325 intmax_t *i
= userdata
;
3330 if (!json_variant_is_integer(variant
)) {
3331 json_log(variant
, flags
, 0, "JSON field '%s' is not an integer.", strna(name
));
3335 *i
= json_variant_integer(variant
);
3339 int json_dispatch_unsigned(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3340 uintmax_t *u
= userdata
;
3345 if (!json_variant_is_unsigned(variant
)) {
3346 json_log(variant
, flags
, 0, "JSON field '%s' is not an unsigned integer.", strna(name
));
3350 *u
= json_variant_unsigned(variant
);
3354 int json_dispatch_uint32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3355 uint32_t *u
= userdata
;
3360 if (!json_variant_is_unsigned(variant
)) {
3361 json_log(variant
, flags
, 0, "JSON field '%s' is not an unsigned integer.", strna(name
));
3365 if (json_variant_unsigned(variant
) > UINT32_MAX
) {
3366 json_log(variant
, flags
, 0, "JSON field '%s' out of bounds.", strna(name
));
3370 *u
= (uint32_t) json_variant_unsigned(variant
);
3374 int json_dispatch_int32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3375 int32_t *i
= userdata
;
3380 if (!json_variant_is_integer(variant
)) {
3381 json_log(variant
, flags
, 0, "JSON field '%s' is not an integer.", strna(name
));
3385 if (json_variant_integer(variant
) < INT32_MIN
|| json_variant_integer(variant
) > INT32_MAX
) {
3386 json_log(variant
, flags
, 0, "JSON field '%s' out of bounds.", strna(name
));
3390 *i
= (int32_t) json_variant_integer(variant
);
3394 int json_dispatch_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3395 char **s
= userdata
;
3401 if (json_variant_is_null(variant
)) {
3406 if (!json_variant_is_string(variant
)) {
3407 json_log(variant
, flags
, 0, "JSON field '%s' is not a string.", strna(name
));
3411 r
= free_and_strdup(s
, json_variant_string(variant
));
3413 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
3418 int json_dispatch_strv(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3419 _cleanup_strv_free_
char **l
= NULL
;
3420 char ***s
= userdata
;
3427 if (json_variant_is_null(variant
)) {
3432 if (!json_variant_is_array(variant
)) {
3433 json_log(variant
, 0, flags
, "JSON field '%s' is not an array.", strna(name
));
3437 for (i
= 0; i
< json_variant_elements(variant
); i
++) {
3440 assert_se(e
= json_variant_by_index(variant
, i
));
3442 if (!json_variant_is_string(e
)) {
3443 json_log(e
, 0, flags
, "JSON array element is not a string.");
3447 r
= strv_extend(&l
, json_variant_string(e
));
3449 return json_log(variant
, flags
, r
, "Failed to append array element: %m");
3452 strv_free_and_replace(*s
, l
);
3456 int json_dispatch_variant(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3457 JsonVariant
**p
= userdata
;
3462 json_variant_unref(*p
);
3463 *p
= json_variant_ref(variant
);
3468 static const char* const json_variant_type_table
[_JSON_VARIANT_TYPE_MAX
] = {
3469 [JSON_VARIANT_STRING
] = "string",
3470 [JSON_VARIANT_INTEGER
] = "integer",
3471 [JSON_VARIANT_UNSIGNED
] = "unsigned",
3472 [JSON_VARIANT_REAL
] = "real",
3473 [JSON_VARIANT_NUMBER
] = "number",
3474 [JSON_VARIANT_BOOLEAN
] = "boolean",
3475 [JSON_VARIANT_ARRAY
] = "array",
3476 [JSON_VARIANT_OBJECT
] = "object",
3477 [JSON_VARIANT_NULL
] = "null",
3480 DEFINE_STRING_TABLE_LOOKUP(json_variant_type
, JsonVariantType
);