1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include "sd-messages.h"
13 #include "alloc-util.h"
14 #include "errno-util.h"
18 #include "hexdecoct.h"
19 #include "json-internal.h"
22 #include "memory-util.h"
23 #include "string-table.h"
24 #include "string-util.h"
26 #include "terminal-util.h"
29 /* Refuse putting together variants with a larger depth than 4K by default (as a protection against overflowing stacks
30 * if code processes JSON objects recursively. Note that we store the depth in an uint16_t, hence make sure this
32 * The value was 16k, but it was discovered to be too high on llvm/x86-64. See also the issue #10738. */
33 #define DEPTH_MAX (4U*1024U)
34 assert_cc(DEPTH_MAX
<= UINT16_MAX
);
36 typedef struct JsonSource
{
37 /* When we parse from a file or similar, encodes the filename, to indicate the source of a json variant */
44 /* On x86-64 this whole structure should have a size of 6 * 64 bit = 48 bytes */
47 /* We either maintain a reference counter for this variant itself, or we are embedded into an
48 * array/object, in which case only that surrounding object is ref-counted. (If 'embedded' is false,
52 /* If this JsonVariant is part of an array/object, then this field points to the surrounding
53 * JSON_VARIANT_ARRAY/JSON_VARIANT_OBJECT object. (If 'embedded' is true, see below.) */
57 /* If this was parsed from some file or buffer, this stores where from, as well as the source line/column */
59 unsigned line
, column
;
61 JsonVariantType type
:5;
63 /* A marker whether this variant is embedded into in array/object or not. If true, the 'parent' pointer above
64 * is valid. If false, the 'n_ref' field above is valid instead. */
67 /* In some conditions (for example, if this object is part of an array of strings or objects), we don't store
68 * any data inline, but instead simply reference an external object and act as surrogate of it. In that case
69 * this bool is set, and the external object is referenced through the .reference field below. */
72 /* While comparing two arrays, we use this for marking what we already have seen */
75 /* The current 'depth' of the JsonVariant, i.e. how many levels of member variants this has */
79 /* For simple types we store the value in-line. */
82 /* For objects and arrays we store the number of elements immediately following */
85 /* If is_reference as indicated above is set, this is where the reference object is actually stored. */
86 JsonVariant
*reference
;
88 /* Strings are placed immediately after the structure. Note that when this is a JsonVariant embedded
89 * into an array we might encode strings up to INLINE_STRING_LENGTH characters directly inside the
90 * element, while longer strings are stored as references. When this object is not embedded into an
91 * array, but stand-alone we allocate the right size for the whole structure, i.e. the array might be
92 * much larger than INLINE_STRING_LENGTH.
94 * Note that because we want to allocate arrays of the JsonVariant structure we specify [0] here,
95 * rather than the prettier []. If we wouldn't, then this char array would have undefined size, and so
96 * would the union and then the struct this is included in. And of structures with undefined size we
97 * can't allocate arrays (at least not easily). */
102 /* Inside string arrays we have a series of JasonVariant structures one after the other. In this case, strings longer
103 * than INLINE_STRING_MAX are stored as references, and all shorter ones inline. (This means — on x86-64 — strings up
104 * to 15 chars are stored within the array elements, and all others in separate allocations) */
105 #define INLINE_STRING_MAX (sizeof(JsonVariant) - offsetof(JsonVariant, string) - 1U)
107 /* Let's make sure this structure isn't increased in size accidentally. This check is only for our most relevant arch
110 assert_cc(sizeof(JsonVariant
) == 48U);
111 assert_cc(INLINE_STRING_MAX
== 15U);
114 static JsonSource
* json_source_new(const char *name
) {
119 s
= malloc(offsetof(JsonSource
, name
) + strlen(name
) + 1);
126 strcpy(s
->name
, name
);
131 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(JsonSource
, json_source
, mfree
);
133 static bool json_source_equal(JsonSource
*a
, JsonSource
*b
) {
140 return streq(a
->name
, b
->name
);
143 DEFINE_TRIVIAL_CLEANUP_FUNC(JsonSource
*, json_source_unref
);
145 /* There are four kind of JsonVariant* pointers:
148 * 2. A 'regular' one, i.e. pointing to malloc() memory
149 * 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.
150 * 4. A 'const string' one, i.e. a pointer to a const string.
152 * The four kinds of pointers can be discerned like this:
154 * Detecting #1 is easy, just compare with NULL. Detecting #3 is similarly easy: all magic pointers are below
155 * _JSON_VARIANT_MAGIC_MAX (which is pretty low, within the first memory page, which is special on Linux and other
156 * 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,
157 * otherwise #4. This makes use of the fact that malloc() will return "maximum aligned" memory, which definitely
158 * means the pointer is even. This means we can use the uneven pointers to reference static strings, as long as we
159 * make sure that all static strings used like this are aligned to 2 (or higher), and that we mask the bit on
160 * access. The JSON_VARIANT_STRING_CONST() macro encodes strings as JsonVariant* pointers, with the bit set. */
162 static bool json_variant_is_magic(const JsonVariant
*v
) {
166 return v
< _JSON_VARIANT_MAGIC_MAX
;
169 static bool json_variant_is_const_string(const JsonVariant
*v
) {
171 if (v
< _JSON_VARIANT_MAGIC_MAX
)
174 /* A proper JsonVariant is aligned to whatever malloc() aligns things too, which is definitely not uneven. We
175 * hence use all uneven pointers as indicators for const strings. */
177 return (((uintptr_t) v
) & 1) != 0;
180 static bool json_variant_is_regular(const JsonVariant
*v
) {
182 if (v
< _JSON_VARIANT_MAGIC_MAX
)
185 return (((uintptr_t) v
) & 1) == 0;
188 static JsonVariant
*json_variant_dereference(JsonVariant
*v
) {
190 /* Recursively dereference variants that are references to other variants */
195 if (!json_variant_is_regular(v
))
198 if (!v
->is_reference
)
201 return json_variant_dereference(v
->reference
);
204 static uint16_t json_variant_depth(JsonVariant
*v
) {
206 v
= json_variant_dereference(v
);
210 if (!json_variant_is_regular(v
))
216 static JsonVariant
*json_variant_normalize(JsonVariant
*v
) {
218 /* Converts json variants to their normalized form, i.e. fully dereferenced and wherever possible converted to
219 * the "magic" version if there is one */
224 v
= json_variant_dereference(v
);
226 switch (json_variant_type(v
)) {
228 case JSON_VARIANT_BOOLEAN
:
229 return json_variant_boolean(v
) ? JSON_VARIANT_MAGIC_TRUE
: JSON_VARIANT_MAGIC_FALSE
;
231 case JSON_VARIANT_NULL
:
232 return JSON_VARIANT_MAGIC_NULL
;
234 case JSON_VARIANT_INTEGER
:
235 return json_variant_integer(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_INTEGER
: v
;
237 case JSON_VARIANT_UNSIGNED
:
238 return json_variant_unsigned(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_UNSIGNED
: v
;
240 case JSON_VARIANT_REAL
:
241 #pragma GCC diagnostic push
242 #pragma GCC diagnostic ignored "-Wfloat-equal"
243 return json_variant_real(v
) == 0.0 ? JSON_VARIANT_MAGIC_ZERO_REAL
: v
;
244 #pragma GCC diagnostic pop
246 case JSON_VARIANT_STRING
:
247 return isempty(json_variant_string(v
)) ? JSON_VARIANT_MAGIC_EMPTY_STRING
: v
;
249 case JSON_VARIANT_ARRAY
:
250 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_ARRAY
: v
;
252 case JSON_VARIANT_OBJECT
:
253 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_OBJECT
: v
;
260 static JsonVariant
*json_variant_conservative_normalize(JsonVariant
*v
) {
262 /* Much like json_variant_normalize(), but won't simplify if the variant has a source/line location attached to
263 * it, in order not to lose context */
268 if (!json_variant_is_regular(v
))
271 if (v
->source
|| v
->line
> 0 || v
->column
> 0)
274 return json_variant_normalize(v
);
277 static int json_variant_new(JsonVariant
**ret
, JsonVariantType type
, size_t space
) {
280 assert_return(ret
, -EINVAL
);
282 v
= malloc0(offsetof(JsonVariant
, value
) + space
);
293 int json_variant_new_integer(JsonVariant
**ret
, intmax_t i
) {
297 assert_return(ret
, -EINVAL
);
300 *ret
= JSON_VARIANT_MAGIC_ZERO_INTEGER
;
304 r
= json_variant_new(&v
, JSON_VARIANT_INTEGER
, sizeof(i
));
308 v
->value
.integer
= i
;
314 int json_variant_new_unsigned(JsonVariant
**ret
, uintmax_t u
) {
318 assert_return(ret
, -EINVAL
);
320 *ret
= JSON_VARIANT_MAGIC_ZERO_UNSIGNED
;
324 r
= json_variant_new(&v
, JSON_VARIANT_UNSIGNED
, sizeof(u
));
334 int json_variant_new_real(JsonVariant
**ret
, long double d
) {
338 assert_return(ret
, -EINVAL
);
340 #pragma GCC diagnostic push
341 #pragma GCC diagnostic ignored "-Wfloat-equal"
343 #pragma GCC diagnostic pop
344 *ret
= JSON_VARIANT_MAGIC_ZERO_REAL
;
348 r
= json_variant_new(&v
, JSON_VARIANT_REAL
, sizeof(d
));
358 int json_variant_new_boolean(JsonVariant
**ret
, bool b
) {
359 assert_return(ret
, -EINVAL
);
362 *ret
= JSON_VARIANT_MAGIC_TRUE
;
364 *ret
= JSON_VARIANT_MAGIC_FALSE
;
369 int json_variant_new_null(JsonVariant
**ret
) {
370 assert_return(ret
, -EINVAL
);
372 *ret
= JSON_VARIANT_MAGIC_NULL
;
376 int json_variant_new_stringn(JsonVariant
**ret
, const char *s
, size_t n
) {
380 assert_return(ret
, -EINVAL
);
382 assert_return(n
== 0, -EINVAL
);
383 return json_variant_new_null(ret
);
386 *ret
= JSON_VARIANT_MAGIC_EMPTY_STRING
;
390 r
= json_variant_new(&v
, JSON_VARIANT_STRING
, n
+ 1);
394 memcpy(v
->string
, s
, n
);
401 static void json_variant_set(JsonVariant
*a
, JsonVariant
*b
) {
404 b
= json_variant_dereference(b
);
406 a
->type
= JSON_VARIANT_NULL
;
410 a
->type
= json_variant_type(b
);
413 case JSON_VARIANT_INTEGER
:
414 a
->value
.integer
= json_variant_integer(b
);
417 case JSON_VARIANT_UNSIGNED
:
418 a
->value
.unsig
= json_variant_unsigned(b
);
421 case JSON_VARIANT_REAL
:
422 a
->value
.real
= json_variant_real(b
);
425 case JSON_VARIANT_BOOLEAN
:
426 a
->value
.boolean
= json_variant_boolean(b
);
429 case JSON_VARIANT_STRING
: {
432 assert_se(s
= json_variant_string(b
));
434 /* Short strings we can store inline */
435 if (strnlen(s
, INLINE_STRING_MAX
+1) <= INLINE_STRING_MAX
) {
436 strcpy(a
->string
, s
);
440 /* For longer strings, use a reference… */
444 case JSON_VARIANT_ARRAY
:
445 case JSON_VARIANT_OBJECT
:
446 a
->is_reference
= true;
447 a
->reference
= json_variant_ref(json_variant_conservative_normalize(b
));
450 case JSON_VARIANT_NULL
:
454 assert_not_reached("Unexpected variant type");
458 static void json_variant_copy_source(JsonVariant
*v
, JsonVariant
*from
) {
462 if (!json_variant_is_regular(from
))
465 v
->line
= from
->line
;
466 v
->column
= from
->column
;
467 v
->source
= json_source_ref(from
->source
);
470 int json_variant_new_array(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
471 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
473 assert_return(ret
, -EINVAL
);
475 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
478 assert_return(array
, -EINVAL
);
480 v
= new(JsonVariant
, n
+ 1);
486 .type
= JSON_VARIANT_ARRAY
,
489 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
490 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
491 *c
= array
[v
->n_elements
];
494 d
= json_variant_depth(c
);
495 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
505 json_variant_set(w
, c
);
506 json_variant_copy_source(w
, c
);
513 int json_variant_new_array_bytes(JsonVariant
**ret
, const void *p
, size_t n
) {
517 assert_return(ret
, -EINVAL
);
519 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
522 assert_return(p
, -EINVAL
);
524 v
= new(JsonVariant
, n
+ 1);
530 .type
= JSON_VARIANT_ARRAY
,
535 for (i
= 0; i
< n
; i
++) {
536 JsonVariant
*w
= v
+ 1 + i
;
541 .type
= JSON_VARIANT_UNSIGNED
,
542 .value
.unsig
= ((const uint8_t*) p
)[i
],
550 int json_variant_new_array_strv(JsonVariant
**ret
, char **l
) {
551 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
559 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
563 v
= new(JsonVariant
, n
+ 1);
569 .type
= JSON_VARIANT_ARRAY
,
573 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
574 JsonVariant
*w
= v
+ 1 + v
->n_elements
;
580 .type
= JSON_VARIANT_STRING
,
583 k
= strlen(l
[v
->n_elements
]);
585 if (k
> INLINE_STRING_MAX
) {
586 /* If string is too long, store it as reference. */
588 r
= json_variant_new_stringn(&w
->reference
, l
[v
->n_elements
], k
);
592 w
->is_reference
= true;
594 memcpy(w
->string
, l
[v
->n_elements
], k
+1);
601 int json_variant_new_object(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
602 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
604 assert_return(ret
, -EINVAL
);
606 *ret
= JSON_VARIANT_MAGIC_EMPTY_OBJECT
;
609 assert_return(array
, -EINVAL
);
610 assert_return(n
% 2 == 0, -EINVAL
);
612 v
= new(JsonVariant
, n
+ 1);
618 .type
= JSON_VARIANT_OBJECT
,
621 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
622 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
623 *c
= array
[v
->n_elements
];
626 if ((v
->n_elements
& 1) == 0 &&
627 !json_variant_is_string(c
))
628 return -EINVAL
; /* Every second one needs to be a string, as it is the key name */
630 d
= json_variant_depth(c
);
631 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
641 json_variant_set(w
, c
);
642 json_variant_copy_source(w
, c
);
649 static void json_variant_free_inner(JsonVariant
*v
) {
652 if (!json_variant_is_regular(v
))
655 json_source_unref(v
->source
);
657 if (v
->is_reference
) {
658 json_variant_unref(v
->reference
);
662 if (IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
)) {
665 for (i
= 0; i
< v
->n_elements
; i
++)
666 json_variant_free_inner(v
+ 1 + i
);
670 JsonVariant
*json_variant_ref(JsonVariant
*v
) {
673 if (!json_variant_is_regular(v
))
677 json_variant_ref(v
->parent
); /* ref the compounding variant instead */
679 assert(v
->n_ref
> 0);
686 JsonVariant
*json_variant_unref(JsonVariant
*v
) {
689 if (!json_variant_is_regular(v
))
693 json_variant_unref(v
->parent
);
695 assert(v
->n_ref
> 0);
699 json_variant_free_inner(v
);
707 void json_variant_unref_many(JsonVariant
**array
, size_t n
) {
710 assert(array
|| n
== 0);
712 for (i
= 0; i
< n
; i
++)
713 json_variant_unref(array
[i
]);
716 const char *json_variant_string(JsonVariant
*v
) {
719 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
721 if (json_variant_is_magic(v
))
723 if (json_variant_is_const_string(v
)) {
724 uintptr_t p
= (uintptr_t) v
;
726 assert((p
& 1) != 0);
727 return (const char*) (p
^ 1U);
731 return json_variant_string(v
->reference
);
732 if (v
->type
!= JSON_VARIANT_STRING
)
738 log_debug("Non-string JSON variant requested as string, returning NULL.");
742 bool json_variant_boolean(JsonVariant
*v
) {
745 if (v
== JSON_VARIANT_MAGIC_TRUE
)
747 if (v
== JSON_VARIANT_MAGIC_FALSE
)
749 if (!json_variant_is_regular(v
))
751 if (v
->type
!= JSON_VARIANT_BOOLEAN
)
754 return json_variant_boolean(v
->reference
);
756 return v
->value
.boolean
;
759 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
763 intmax_t json_variant_integer(JsonVariant
*v
) {
766 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
767 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
768 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
770 if (!json_variant_is_regular(v
))
773 return json_variant_integer(v
->reference
);
777 case JSON_VARIANT_INTEGER
:
778 return v
->value
.integer
;
780 case JSON_VARIANT_UNSIGNED
:
781 if (v
->value
.unsig
<= INTMAX_MAX
)
782 return (intmax_t) v
->value
.unsig
;
784 log_debug("Unsigned integer %ju requested as signed integer and out of range, returning 0.", v
->value
.unsig
);
787 case JSON_VARIANT_REAL
: {
790 converted
= (intmax_t) v
->value
.real
;
792 #pragma GCC diagnostic push
793 #pragma GCC diagnostic ignored "-Wfloat-equal"
794 if ((long double) converted
== v
->value
.real
)
795 #pragma GCC diagnostic pop
798 log_debug("Real %Lg requested as integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
807 log_debug("Non-integer JSON variant requested as integer, returning 0.");
811 uintmax_t json_variant_unsigned(JsonVariant
*v
) {
814 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
815 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
816 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
818 if (!json_variant_is_regular(v
))
821 return json_variant_integer(v
->reference
);
825 case JSON_VARIANT_INTEGER
:
826 if (v
->value
.integer
>= 0)
827 return (uintmax_t) v
->value
.integer
;
829 log_debug("Signed integer %ju requested as unsigned integer and out of range, returning 0.", v
->value
.integer
);
832 case JSON_VARIANT_UNSIGNED
:
833 return v
->value
.unsig
;
835 case JSON_VARIANT_REAL
: {
838 converted
= (uintmax_t) v
->value
.real
;
840 #pragma GCC diagnostic push
841 #pragma GCC diagnostic ignored "-Wfloat-equal"
842 if ((long double) converted
== v
->value
.real
)
843 #pragma GCC diagnostic pop
846 log_debug("Real %Lg requested as unsigned integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
855 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
859 long double json_variant_real(JsonVariant
*v
) {
862 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
863 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
864 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
866 if (!json_variant_is_regular(v
))
869 return json_variant_real(v
->reference
);
873 case JSON_VARIANT_REAL
:
874 return v
->value
.real
;
876 case JSON_VARIANT_INTEGER
: {
877 long double converted
;
879 converted
= (long double) v
->value
.integer
;
881 if ((intmax_t) converted
== v
->value
.integer
)
884 log_debug("Signed integer %ji requested as real, and cannot be converted losslessly, returning 0.", v
->value
.integer
);
888 case JSON_VARIANT_UNSIGNED
: {
889 long double converted
;
891 converted
= (long double) v
->value
.unsig
;
893 if ((uintmax_t) converted
== v
->value
.unsig
)
896 log_debug("Unsigned integer %ju requested as real, and cannot be converted losslessly, returning 0.", v
->value
.unsig
);
905 log_debug("Non-integer JSON variant requested as integer, returning 0.");
909 bool json_variant_is_negative(JsonVariant
*v
) {
912 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
913 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
914 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
916 if (!json_variant_is_regular(v
))
919 return json_variant_is_negative(v
->reference
);
921 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
922 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
927 case JSON_VARIANT_REAL
:
928 return v
->value
.real
< 0;
930 case JSON_VARIANT_INTEGER
:
931 return v
->value
.integer
< 0;
933 case JSON_VARIANT_UNSIGNED
:
941 log_debug("Non-integer JSON variant tested for negativity, returning false.");
945 JsonVariantType
json_variant_type(JsonVariant
*v
) {
948 return _JSON_VARIANT_TYPE_INVALID
;
950 if (json_variant_is_const_string(v
))
951 return JSON_VARIANT_STRING
;
953 if (v
== JSON_VARIANT_MAGIC_TRUE
|| v
== JSON_VARIANT_MAGIC_FALSE
)
954 return JSON_VARIANT_BOOLEAN
;
956 if (v
== JSON_VARIANT_MAGIC_NULL
)
957 return JSON_VARIANT_NULL
;
959 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
)
960 return JSON_VARIANT_INTEGER
;
962 if (v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
)
963 return JSON_VARIANT_UNSIGNED
;
965 if (v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
966 return JSON_VARIANT_REAL
;
968 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
969 return JSON_VARIANT_STRING
;
971 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
)
972 return JSON_VARIANT_ARRAY
;
974 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
975 return JSON_VARIANT_OBJECT
;
980 bool json_variant_has_type(JsonVariant
*v
, JsonVariantType type
) {
983 v
= json_variant_dereference(v
);
987 rt
= json_variant_type(v
);
991 /* If it's a const string, then it only can be a string, and if it is not, it's not */
992 if (json_variant_is_const_string(v
))
995 /* All three magic zeroes qualify as integer, unsigned and as real */
996 if ((v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
|| v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
|| v
== JSON_VARIANT_MAGIC_ZERO_REAL
) &&
997 IN_SET(type
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
, JSON_VARIANT_NUMBER
))
1000 /* All other magic variant types are only equal to themselves */
1001 if (json_variant_is_magic(v
))
1004 /* Handle the "number" pseudo type */
1005 if (type
== JSON_VARIANT_NUMBER
)
1006 return IN_SET(rt
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
);
1008 /* Integer conversions are OK in many cases */
1009 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_UNSIGNED
)
1010 return v
->value
.integer
>= 0;
1011 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_INTEGER
)
1012 return v
->value
.unsig
<= INTMAX_MAX
;
1014 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1015 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_REAL
)
1016 return (intmax_t) (long double) v
->value
.integer
== v
->value
.integer
;
1017 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_REAL
)
1018 return (uintmax_t) (long double) v
->value
.unsig
== v
->value
.unsig
;
1020 #pragma GCC diagnostic push
1021 #pragma GCC diagnostic ignored "-Wfloat-equal"
1022 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1023 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_INTEGER
)
1024 return (long double) (intmax_t) v
->value
.real
== v
->value
.real
;
1025 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_UNSIGNED
)
1026 return (long double) (uintmax_t) v
->value
.real
== v
->value
.real
;
1027 #pragma GCC diagnostic pop
1032 size_t json_variant_elements(JsonVariant
*v
) {
1035 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1036 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1038 if (!json_variant_is_regular(v
))
1040 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1042 if (v
->is_reference
)
1043 return json_variant_elements(v
->reference
);
1045 return v
->n_elements
;
1048 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1052 JsonVariant
*json_variant_by_index(JsonVariant
*v
, size_t idx
) {
1055 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1056 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1058 if (!json_variant_is_regular(v
))
1060 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1062 if (v
->is_reference
)
1063 return json_variant_by_index(v
->reference
, idx
);
1064 if (idx
>= v
->n_elements
)
1067 return json_variant_conservative_normalize(v
+ 1 + idx
);
1070 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1074 JsonVariant
*json_variant_by_key_full(JsonVariant
*v
, const char *key
, JsonVariant
**ret_key
) {
1081 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1083 if (!json_variant_is_regular(v
))
1085 if (v
->type
!= JSON_VARIANT_OBJECT
)
1087 if (v
->is_reference
)
1088 return json_variant_by_key(v
->reference
, key
);
1090 for (i
= 0; i
< v
->n_elements
; i
+= 2) {
1093 p
= json_variant_dereference(v
+ 1 + i
);
1095 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1098 if (streq(json_variant_string(p
), key
)) {
1101 *ret_key
= json_variant_conservative_normalize(v
+ 1 + i
);
1103 return json_variant_conservative_normalize(v
+ 1 + i
+ 1);
1114 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1121 JsonVariant
*json_variant_by_key(JsonVariant
*v
, const char *key
) {
1122 return json_variant_by_key_full(v
, key
, NULL
);
1125 bool json_variant_equal(JsonVariant
*a
, JsonVariant
*b
) {
1128 a
= json_variant_normalize(a
);
1129 b
= json_variant_normalize(b
);
1134 t
= json_variant_type(a
);
1135 if (!json_variant_has_type(b
, t
))
1140 case JSON_VARIANT_STRING
:
1141 return streq(json_variant_string(a
), json_variant_string(b
));
1143 case JSON_VARIANT_INTEGER
:
1144 return json_variant_integer(a
) == json_variant_integer(b
);
1146 case JSON_VARIANT_UNSIGNED
:
1147 return json_variant_unsigned(a
) == json_variant_unsigned(b
);
1149 case JSON_VARIANT_REAL
:
1150 #pragma GCC diagnostic push
1151 #pragma GCC diagnostic ignored "-Wfloat-equal"
1152 return json_variant_real(a
) == json_variant_real(b
);
1153 #pragma GCC diagnostic pop
1155 case JSON_VARIANT_BOOLEAN
:
1156 return json_variant_boolean(a
) == json_variant_boolean(b
);
1158 case JSON_VARIANT_NULL
:
1161 case JSON_VARIANT_ARRAY
: {
1164 n
= json_variant_elements(a
);
1165 if (n
!= json_variant_elements(b
))
1168 for (i
= 0; i
< n
; i
++) {
1169 if (!json_variant_equal(json_variant_by_index(a
, i
), json_variant_by_index(b
, i
)))
1176 case JSON_VARIANT_OBJECT
: {
1179 n
= json_variant_elements(a
);
1180 if (n
!= json_variant_elements(b
))
1183 /* Iterate through all keys in 'a' */
1184 for (i
= 0; i
< n
; i
+= 2) {
1188 /* Match them against all keys in 'b' */
1189 for (j
= 0; j
< n
; j
+= 2) {
1192 key_b
= json_variant_by_index(b
, j
);
1194 /* During the first iteration unmark everything */
1196 key_b
->is_marked
= false;
1197 else if (key_b
->is_marked
) /* In later iterations if we already marked something, don't bother with it again */
1203 if (json_variant_equal(json_variant_by_index(a
, i
), key_b
) &&
1204 json_variant_equal(json_variant_by_index(a
, i
+1), json_variant_by_index(b
, j
+1))) {
1205 /* Key and values match! */
1206 key_b
->is_marked
= found
= true;
1208 /* In the first iteration we continue the inner loop since we want to mark
1209 * everything, otherwise exit the loop quickly after we found what we were
1224 assert_not_reached("Unknown variant type.");
1228 int json_variant_get_source(JsonVariant
*v
, const char **ret_source
, unsigned *ret_line
, unsigned *ret_column
) {
1229 assert_return(v
, -EINVAL
);
1232 *ret_source
= json_variant_is_regular(v
) && v
->source
? v
->source
->name
: NULL
;
1235 *ret_line
= json_variant_is_regular(v
) ? v
->line
: 0;
1238 *ret_column
= json_variant_is_regular(v
) ? v
->column
: 0;
1243 static int print_source(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, bool whitespace
) {
1246 if (!FLAGS_SET(flags
, JSON_FORMAT_SOURCE
|JSON_FORMAT_PRETTY
))
1249 if (!json_variant_is_regular(v
))
1252 if (!v
->source
&& v
->line
== 0 && v
->column
== 0)
1255 /* The max width we need to format the line numbers for this source file */
1256 w
= (v
->source
&& v
->source
->max_line
> 0) ?
1257 DECIMAL_STR_WIDTH(v
->source
->max_line
) :
1258 DECIMAL_STR_MAX(unsigned)-1;
1259 k
= (v
->source
&& v
->source
->max_column
> 0) ?
1260 DECIMAL_STR_WIDTH(v
->source
->max_column
) :
1261 DECIMAL_STR_MAX(unsigned) -1;
1266 n
= 1 + (v
->source
? strlen(v
->source
->name
) : 0) +
1267 ((v
->source
&& (v
->line
> 0 || v
->column
> 0)) ? 1 : 0) +
1268 (v
->line
> 0 ? w
: 0) +
1269 (((v
->source
|| v
->line
> 0) && v
->column
> 0) ? 1 : 0) +
1270 (v
->column
> 0 ? k
: 0) +
1273 for (i
= 0; i
< n
; i
++)
1279 fputs(v
->source
->name
, f
);
1280 if (v
->source
&& (v
->line
> 0 || v
->column
> 0))
1283 fprintf(f
, "%*u", (int) w
, v
->line
);
1284 if ((v
->source
|| v
->line
> 0) || v
->column
> 0)
1287 fprintf(f
, "%*u", (int) k
, v
->column
);
1296 static int json_format(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, const char *prefix
) {
1302 switch (json_variant_type(v
)) {
1304 case JSON_VARIANT_REAL
: {
1307 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
1308 if (loc
== (locale_t
) 0)
1311 if (flags
& JSON_FORMAT_COLOR
)
1312 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1314 fprintf(f
, "%.*Le", DECIMAL_DIG
, json_variant_real(v
));
1316 if (flags
& JSON_FORMAT_COLOR
)
1317 fputs(ANSI_NORMAL
, f
);
1323 case JSON_VARIANT_INTEGER
:
1324 if (flags
& JSON_FORMAT_COLOR
)
1325 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1327 fprintf(f
, "%" PRIdMAX
, json_variant_integer(v
));
1329 if (flags
& JSON_FORMAT_COLOR
)
1330 fputs(ANSI_NORMAL
, f
);
1333 case JSON_VARIANT_UNSIGNED
:
1334 if (flags
& JSON_FORMAT_COLOR
)
1335 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1337 fprintf(f
, "%" PRIuMAX
, json_variant_unsigned(v
));
1339 if (flags
& JSON_FORMAT_COLOR
)
1340 fputs(ANSI_NORMAL
, f
);
1343 case JSON_VARIANT_BOOLEAN
:
1345 if (flags
& JSON_FORMAT_COLOR
)
1346 fputs(ANSI_HIGHLIGHT
, f
);
1348 if (json_variant_boolean(v
))
1353 if (flags
& JSON_FORMAT_COLOR
)
1354 fputs(ANSI_NORMAL
, f
);
1358 case JSON_VARIANT_NULL
:
1359 if (flags
& JSON_FORMAT_COLOR
)
1360 fputs(ANSI_HIGHLIGHT
, f
);
1364 if (flags
& JSON_FORMAT_COLOR
)
1365 fputs(ANSI_NORMAL
, f
);
1368 case JSON_VARIANT_STRING
: {
1373 if (flags
& JSON_FORMAT_COLOR
)
1374 fputs(ANSI_GREEN
, f
);
1376 for (q
= json_variant_string(v
); *q
; q
++) {
1409 if ((signed char) *q
>= 0 && *q
< ' ')
1410 fprintf(f
, "\\u%04x", *q
);
1417 if (flags
& JSON_FORMAT_COLOR
)
1418 fputs(ANSI_NORMAL
, f
);
1424 case JSON_VARIANT_ARRAY
: {
1427 n
= json_variant_elements(v
);
1432 _cleanup_free_
char *joined
= NULL
;
1433 const char *prefix2
;
1435 if (flags
& JSON_FORMAT_PRETTY
) {
1436 joined
= strjoin(strempty(prefix
), "\t");
1443 prefix2
= strempty(prefix
);
1447 for (i
= 0; i
< n
; i
++) {
1450 assert_se(e
= json_variant_by_index(v
, i
));
1453 if (flags
& JSON_FORMAT_PRETTY
)
1459 if (flags
& JSON_FORMAT_PRETTY
) {
1460 print_source(f
, e
, flags
, false);
1464 r
= json_format(f
, e
, flags
, prefix2
);
1469 if (flags
& JSON_FORMAT_PRETTY
) {
1471 print_source(f
, v
, flags
, true);
1472 fputs(strempty(prefix
), f
);
1480 case JSON_VARIANT_OBJECT
: {
1483 n
= json_variant_elements(v
);
1488 _cleanup_free_
char *joined
= NULL
;
1489 const char *prefix2
;
1491 if (flags
& JSON_FORMAT_PRETTY
) {
1492 joined
= strjoin(strempty(prefix
), "\t");
1499 prefix2
= strempty(prefix
);
1503 for (i
= 0; i
< n
; i
+= 2) {
1506 e
= json_variant_by_index(v
, i
);
1509 if (flags
& JSON_FORMAT_PRETTY
)
1515 if (flags
& JSON_FORMAT_PRETTY
) {
1516 print_source(f
, e
, flags
, false);
1520 r
= json_format(f
, e
, flags
, prefix2
);
1524 fputs(flags
& JSON_FORMAT_PRETTY
? " : " : ":", f
);
1526 r
= json_format(f
, json_variant_by_index(v
, i
+1), flags
, prefix2
);
1531 if (flags
& JSON_FORMAT_PRETTY
) {
1533 print_source(f
, v
, flags
, true);
1534 fputs(strempty(prefix
), f
);
1543 assert_not_reached("Unexpected variant type.");
1549 int json_variant_format(JsonVariant
*v
, JsonFormatFlags flags
, char **ret
) {
1550 _cleanup_free_
char *s
= NULL
;
1554 assert_return(v
, -EINVAL
);
1555 assert_return(ret
, -EINVAL
);
1558 _cleanup_fclose_
FILE *f
= NULL
;
1560 f
= open_memstream_unlocked(&s
, &sz
);
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);
1762 } else if ((signed char) *s
>= 0 && *s
< 127) /* Process ASCII chars quickly */
1767 w
= utf8_encoded_valid_unichar(s
, n
);
1768 if (w
< 0) /* count invalid unichars as normal characters */
1770 else if ((size_t) w
> n
) /* never read more than the specified number of characters */
1785 static int unhex_ucs2(const char *c
, uint16_t *ret
) {
1792 aa
= unhexchar(c
[0]);
1796 bb
= unhexchar(c
[1]);
1800 cc
= unhexchar(c
[2]);
1804 dd
= unhexchar(c
[3]);
1808 x
= ((uint16_t) aa
<< 12) |
1809 ((uint16_t) bb
<< 8) |
1810 ((uint16_t) cc
<< 4) |
1821 static int json_parse_string(const char **p
, char **ret
) {
1822 _cleanup_free_
char *s
= NULL
;
1823 size_t n
= 0, allocated
= 0;
1844 /* Check for control characters 0x00..0x1f */
1845 if (*c
> 0 && *c
< ' ')
1848 /* Check for control character 0x7f */
1863 return JSON_TOKEN_STRING
;
1873 if (IN_SET(*c
, '"', '\\', '/'))
1885 else if (*c
== 'u') {
1889 r
= unhex_ucs2(c
+ 1, &x
);
1895 if (!GREEDY_REALLOC(s
, allocated
, n
+ 5))
1898 if (!utf16_is_surrogate(x
))
1899 n
+= utf8_encode_unichar(s
+ n
, (char32_t
) x
);
1900 else if (utf16_is_trailing_surrogate(x
))
1905 if (c
[0] != '\\' || c
[1] != 'u')
1908 r
= unhex_ucs2(c
+ 2, &y
);
1914 if (!utf16_is_trailing_surrogate(y
))
1917 n
+= utf8_encode_unichar(s
+ n
, utf16_surrogate_pair_to_unichar(x
, y
));
1924 if (!GREEDY_REALLOC(s
, allocated
, n
+ 2))
1932 len
= utf8_encoded_valid_unichar(c
, (size_t) -1);
1936 if (!GREEDY_REALLOC(s
, allocated
, n
+ len
+ 1))
1939 memcpy(s
+ n
, c
, len
);
1945 static int json_parse_number(const char **p
, JsonValue
*ret
) {
1946 bool negative
= false, exponent_negative
= false, is_real
= false;
1947 long double x
= 0.0, y
= 0.0, exponent
= 0.0, shift
= 1.0;
1966 if (!strchr("123456789", *c
) || *c
== 0)
1973 if (i
< INTMAX_MIN
/ 10) /* overflow */
1976 intmax_t t
= 10 * i
;
1978 if (t
< INTMAX_MIN
+ (*c
- '0')) /* overflow */
1984 if (u
> UINTMAX_MAX
/ 10) /* overflow */
1987 uintmax_t t
= 10 * u
;
1989 if (t
> UINTMAX_MAX
- (*c
- '0')) /* overflow */
1997 x
= 10.0 * x
+ (*c
- '0');
2000 } while (strchr("0123456789", *c
) && *c
!= 0);
2007 if (!strchr("0123456789", *c
) || *c
== 0)
2011 y
= 10.0 * y
+ (*c
- '0');
2012 shift
= 10.0 * shift
;
2014 } while (strchr("0123456789", *c
) && *c
!= 0);
2017 if (IN_SET(*c
, 'e', 'E')) {
2022 exponent_negative
= true;
2024 } else if (*c
== '+')
2027 if (!strchr("0123456789", *c
) || *c
== 0)
2031 exponent
= 10.0 * exponent
+ (*c
- '0');
2033 } while (strchr("0123456789", *c
) && *c
!= 0);
2039 ret
->real
= ((negative
? -1.0 : 1.0) * (x
+ (y
/ shift
))) * exp10l((exponent_negative
? -1.0 : 1.0) * exponent
);
2040 return JSON_TOKEN_REAL
;
2041 } else if (negative
) {
2043 return JSON_TOKEN_INTEGER
;
2046 return JSON_TOKEN_UNSIGNED
;
2053 JsonValue
*ret_value
,
2054 unsigned *ret_line
, /* 'ret_line' returns the line at the beginning of this token */
2055 unsigned *ret_column
,
2057 unsigned *line
, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2060 unsigned start_line
, start_column
;
2061 const char *start
, *c
;
2081 t
= PTR_TO_INT(*state
);
2082 if (t
== STATE_NULL
) {
2088 /* Skip over the whitespace */
2089 n
= strspn(*p
, WHITESPACE
);
2090 inc_lines_columns(line
, column
, *p
, n
);
2093 /* Remember where we started processing this token */
2096 start_column
= *column
;
2100 *ret_value
= JSON_VALUE_NULL
;
2111 *state
= INT_TO_PTR(STATE_VALUE
);
2112 r
= JSON_TOKEN_OBJECT_OPEN
;
2115 } else if (*c
== '}') {
2117 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2118 r
= JSON_TOKEN_OBJECT_CLOSE
;
2121 } else if (*c
== '[') {
2123 *state
= INT_TO_PTR(STATE_VALUE
);
2124 r
= JSON_TOKEN_ARRAY_OPEN
;
2127 } else if (*c
== ']') {
2129 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2130 r
= JSON_TOKEN_ARRAY_CLOSE
;
2133 } else if (*c
== '"') {
2135 r
= json_parse_string(&c
, ret_string
);
2139 *ret_value
= JSON_VALUE_NULL
;
2140 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2143 } else if (strchr("-0123456789", *c
)) {
2145 r
= json_parse_number(&c
, ret_value
);
2150 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2153 } else if (startswith(c
, "true")) {
2155 ret_value
->boolean
= true;
2157 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2158 r
= JSON_TOKEN_BOOLEAN
;
2161 } else if (startswith(c
, "false")) {
2163 ret_value
->boolean
= false;
2165 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2166 r
= JSON_TOKEN_BOOLEAN
;
2169 } else if (startswith(c
, "null")) {
2171 *ret_value
= JSON_VALUE_NULL
;
2173 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2174 r
= JSON_TOKEN_NULL
;
2181 case STATE_VALUE_POST
:
2185 *state
= INT_TO_PTR(STATE_VALUE
);
2186 r
= JSON_TOKEN_COLON
;
2189 } else if (*c
== ',') {
2191 *state
= INT_TO_PTR(STATE_VALUE
);
2192 r
= JSON_TOKEN_COMMA
;
2195 } else if (*c
== '}') {
2197 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2198 r
= JSON_TOKEN_OBJECT_CLOSE
;
2201 } else if (*c
== ']') {
2203 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2204 r
= JSON_TOKEN_ARRAY_CLOSE
;
2211 assert_not_reached("Unexpected tokenizer state");
2216 *ret_value
= JSON_VALUE_NULL
;
2219 inc_lines_columns(line
, column
, start
, c
- start
);
2222 *ret_line
= start_line
;
2223 *ret_column
= start_column
;
2228 typedef enum JsonExpect
{
2229 /* The following values are used by json_parse() */
2232 EXPECT_OBJECT_FIRST_KEY
,
2233 EXPECT_OBJECT_NEXT_KEY
,
2234 EXPECT_OBJECT_COLON
,
2235 EXPECT_OBJECT_VALUE
,
2236 EXPECT_OBJECT_COMMA
,
2237 EXPECT_ARRAY_FIRST_ELEMENT
,
2238 EXPECT_ARRAY_NEXT_ELEMENT
,
2241 /* And these are used by json_build() */
2242 EXPECT_ARRAY_ELEMENT
,
2246 typedef struct JsonStack
{
2248 JsonVariant
**elements
;
2249 size_t n_elements
, n_elements_allocated
;
2250 unsigned line_before
;
2251 unsigned column_before
;
2252 size_t n_suppress
; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2255 static void json_stack_release(JsonStack
*s
) {
2258 json_variant_unref_many(s
->elements
, s
->n_elements
);
2259 s
->elements
= mfree(s
->elements
);
2262 static int json_parse_internal(
2268 bool continue_end
) {
2270 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2271 unsigned line_buffer
= 0, column_buffer
= 0;
2272 void *tokenizer_state
= NULL
;
2273 JsonStack
*stack
= NULL
;
2277 assert_return(input
, -EINVAL
);
2278 assert_return(ret
, -EINVAL
);
2282 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2285 stack
[0] = (JsonStack
) {
2286 .expect
= EXPECT_TOPLEVEL
,
2290 line
= &line_buffer
;
2292 column
= &column_buffer
;
2295 _cleanup_free_
char *string
= NULL
;
2296 unsigned line_token
, column_token
;
2297 JsonVariant
*add
= NULL
;
2302 assert(n_stack
> 0);
2303 current
= stack
+ n_stack
- 1;
2305 if (continue_end
&& current
->expect
== EXPECT_END
)
2308 token
= json_tokenize(&p
, &string
, &value
, &line_token
, &column_token
, &tokenizer_state
, line
, column
);
2316 case JSON_TOKEN_END
:
2317 if (current
->expect
!= EXPECT_END
) {
2322 assert(current
->n_elements
== 1);
2323 assert(n_stack
== 1);
2326 case JSON_TOKEN_COLON
:
2328 if (current
->expect
!= EXPECT_OBJECT_COLON
) {
2333 current
->expect
= EXPECT_OBJECT_VALUE
;
2336 case JSON_TOKEN_COMMA
:
2338 if (current
->expect
== EXPECT_OBJECT_COMMA
)
2339 current
->expect
= EXPECT_OBJECT_NEXT_KEY
;
2340 else if (current
->expect
== EXPECT_ARRAY_COMMA
)
2341 current
->expect
= EXPECT_ARRAY_NEXT_ELEMENT
;
2349 case JSON_TOKEN_OBJECT_OPEN
:
2351 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2356 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2360 current
= stack
+ n_stack
- 1;
2362 /* Prepare the expect for when we return from the child */
2363 if (current
->expect
== EXPECT_TOPLEVEL
)
2364 current
->expect
= EXPECT_END
;
2365 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2366 current
->expect
= EXPECT_OBJECT_COMMA
;
2368 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2369 current
->expect
= EXPECT_ARRAY_COMMA
;
2372 stack
[n_stack
++] = (JsonStack
) {
2373 .expect
= EXPECT_OBJECT_FIRST_KEY
,
2374 .line_before
= line_token
,
2375 .column_before
= column_token
,
2378 current
= stack
+ n_stack
- 1;
2381 case JSON_TOKEN_OBJECT_CLOSE
:
2382 if (!IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_COMMA
)) {
2387 assert(n_stack
> 1);
2389 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
2393 line_token
= current
->line_before
;
2394 column_token
= current
->column_before
;
2396 json_stack_release(current
);
2397 n_stack
--, current
--;
2401 case JSON_TOKEN_ARRAY_OPEN
:
2402 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2407 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2411 current
= stack
+ n_stack
- 1;
2413 /* Prepare the expect for when we return from the child */
2414 if (current
->expect
== EXPECT_TOPLEVEL
)
2415 current
->expect
= EXPECT_END
;
2416 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2417 current
->expect
= EXPECT_OBJECT_COMMA
;
2419 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2420 current
->expect
= EXPECT_ARRAY_COMMA
;
2423 stack
[n_stack
++] = (JsonStack
) {
2424 .expect
= EXPECT_ARRAY_FIRST_ELEMENT
,
2425 .line_before
= line_token
,
2426 .column_before
= column_token
,
2431 case JSON_TOKEN_ARRAY_CLOSE
:
2432 if (!IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_COMMA
)) {
2437 assert(n_stack
> 1);
2439 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2443 line_token
= current
->line_before
;
2444 column_token
= current
->column_before
;
2446 json_stack_release(current
);
2447 n_stack
--, current
--;
2450 case JSON_TOKEN_STRING
:
2451 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
)) {
2456 r
= json_variant_new_string(&add
, string
);
2460 if (current
->expect
== EXPECT_TOPLEVEL
)
2461 current
->expect
= EXPECT_END
;
2462 else if (IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_NEXT_KEY
))
2463 current
->expect
= EXPECT_OBJECT_COLON
;
2464 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2465 current
->expect
= EXPECT_OBJECT_COMMA
;
2467 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2468 current
->expect
= EXPECT_ARRAY_COMMA
;
2473 case JSON_TOKEN_REAL
:
2474 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2479 r
= json_variant_new_real(&add
, value
.real
);
2483 if (current
->expect
== EXPECT_TOPLEVEL
)
2484 current
->expect
= EXPECT_END
;
2485 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2486 current
->expect
= EXPECT_OBJECT_COMMA
;
2488 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2489 current
->expect
= EXPECT_ARRAY_COMMA
;
2494 case JSON_TOKEN_INTEGER
:
2495 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2500 r
= json_variant_new_integer(&add
, value
.integer
);
2504 if (current
->expect
== EXPECT_TOPLEVEL
)
2505 current
->expect
= EXPECT_END
;
2506 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2507 current
->expect
= EXPECT_OBJECT_COMMA
;
2509 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2510 current
->expect
= EXPECT_ARRAY_COMMA
;
2515 case JSON_TOKEN_UNSIGNED
:
2516 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2521 r
= json_variant_new_unsigned(&add
, value
.unsig
);
2525 if (current
->expect
== EXPECT_TOPLEVEL
)
2526 current
->expect
= EXPECT_END
;
2527 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2528 current
->expect
= EXPECT_OBJECT_COMMA
;
2530 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2531 current
->expect
= EXPECT_ARRAY_COMMA
;
2536 case JSON_TOKEN_BOOLEAN
:
2537 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2542 r
= json_variant_new_boolean(&add
, value
.boolean
);
2546 if (current
->expect
== EXPECT_TOPLEVEL
)
2547 current
->expect
= EXPECT_END
;
2548 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2549 current
->expect
= EXPECT_OBJECT_COMMA
;
2551 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2552 current
->expect
= EXPECT_ARRAY_COMMA
;
2557 case JSON_TOKEN_NULL
:
2558 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2563 r
= json_variant_new_null(&add
);
2567 if (current
->expect
== EXPECT_TOPLEVEL
)
2568 current
->expect
= EXPECT_END
;
2569 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2570 current
->expect
= EXPECT_OBJECT_COMMA
;
2572 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2573 current
->expect
= EXPECT_ARRAY_COMMA
;
2579 assert_not_reached("Unexpected token");
2583 (void) json_variant_set_source(&add
, source
, line_token
, column_token
);
2585 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
2590 current
->elements
[current
->n_elements
++] = add
;
2595 assert(n_stack
== 1);
2596 assert(stack
[0].n_elements
== 1);
2598 *ret
= json_variant_ref(stack
[0].elements
[0]);
2603 for (i
= 0; i
< n_stack
; i
++)
2604 json_stack_release(stack
+ i
);
2611 int json_parse(const char *input
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2612 return json_parse_internal(&input
, NULL
, ret
, ret_line
, ret_column
, false);
2615 int json_parse_continue(const char **p
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2616 return json_parse_internal(p
, NULL
, ret
, ret_line
, ret_column
, true);
2619 int json_parse_file(FILE *f
, const char *path
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2620 _cleanup_(json_source_unrefp
) JsonSource
*source
= NULL
;
2621 _cleanup_free_
char *text
= NULL
;
2626 r
= read_full_stream(f
, &text
, NULL
);
2628 r
= read_full_file(path
, &text
, NULL
);
2635 source
= json_source_new(path
);
2641 return json_parse_internal(&p
, source
, ret
, ret_line
, ret_column
, false);
2644 int json_buildv(JsonVariant
**ret
, va_list ap
) {
2645 JsonStack
*stack
= NULL
;
2646 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2649 assert_return(ret
, -EINVAL
);
2651 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2654 stack
[0] = (JsonStack
) {
2655 .expect
= EXPECT_TOPLEVEL
,
2659 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
2660 size_t n_subtract
= 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
2661 * have been added to the current variant */
2665 assert(n_stack
> 0);
2666 current
= stack
+ n_stack
- 1;
2668 if (current
->expect
== EXPECT_END
)
2671 command
= va_arg(ap
, int);
2675 case _JSON_BUILD_STRING
: {
2678 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2683 p
= va_arg(ap
, const char *);
2685 if (current
->n_suppress
== 0) {
2686 r
= json_variant_new_string(&add
, p
);
2693 if (current
->expect
== EXPECT_TOPLEVEL
)
2694 current
->expect
= EXPECT_END
;
2695 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2696 current
->expect
= EXPECT_OBJECT_KEY
;
2698 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2703 case _JSON_BUILD_INTEGER
: {
2706 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2711 j
= va_arg(ap
, intmax_t);
2713 if (current
->n_suppress
== 0) {
2714 r
= json_variant_new_integer(&add
, j
);
2721 if (current
->expect
== EXPECT_TOPLEVEL
)
2722 current
->expect
= EXPECT_END
;
2723 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2724 current
->expect
= EXPECT_OBJECT_KEY
;
2726 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2731 case _JSON_BUILD_UNSIGNED
: {
2734 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2739 j
= va_arg(ap
, uintmax_t);
2741 if (current
->n_suppress
== 0) {
2742 r
= json_variant_new_unsigned(&add
, j
);
2749 if (current
->expect
== EXPECT_TOPLEVEL
)
2750 current
->expect
= EXPECT_END
;
2751 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2752 current
->expect
= EXPECT_OBJECT_KEY
;
2754 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2759 case _JSON_BUILD_REAL
: {
2762 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2767 d
= va_arg(ap
, long double);
2769 if (current
->n_suppress
== 0) {
2770 r
= json_variant_new_real(&add
, d
);
2777 if (current
->expect
== EXPECT_TOPLEVEL
)
2778 current
->expect
= EXPECT_END
;
2779 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2780 current
->expect
= EXPECT_OBJECT_KEY
;
2782 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2787 case _JSON_BUILD_BOOLEAN
: {
2790 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2795 b
= va_arg(ap
, int);
2797 if (current
->n_suppress
== 0) {
2798 r
= json_variant_new_boolean(&add
, b
);
2805 if (current
->expect
== EXPECT_TOPLEVEL
)
2806 current
->expect
= EXPECT_END
;
2807 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2808 current
->expect
= EXPECT_OBJECT_KEY
;
2810 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2815 case _JSON_BUILD_NULL
:
2817 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2822 if (current
->n_suppress
== 0) {
2823 r
= json_variant_new_null(&add
);
2830 if (current
->expect
== EXPECT_TOPLEVEL
)
2831 current
->expect
= EXPECT_END
;
2832 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2833 current
->expect
= EXPECT_OBJECT_KEY
;
2835 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2839 case _JSON_BUILD_VARIANT
:
2841 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2846 /* Note that we don't care for current->n_suppress here, after all the variant is already
2847 * allocated anyway... */
2848 add
= va_arg(ap
, JsonVariant
*);
2850 add
= JSON_VARIANT_MAGIC_NULL
;
2852 json_variant_ref(add
);
2856 if (current
->expect
== EXPECT_TOPLEVEL
)
2857 current
->expect
= EXPECT_END
;
2858 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2859 current
->expect
= EXPECT_OBJECT_KEY
;
2861 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2865 case _JSON_BUILD_LITERAL
: {
2868 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2873 l
= va_arg(ap
, const char *);
2876 /* Note that we don't care for current->n_suppress here, we should generate parsing
2877 * errors even in suppressed object properties */
2879 r
= json_parse(l
, &add
, NULL
, NULL
);
2883 add
= JSON_VARIANT_MAGIC_NULL
;
2887 if (current
->expect
== EXPECT_TOPLEVEL
)
2888 current
->expect
= EXPECT_END
;
2889 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2890 current
->expect
= EXPECT_OBJECT_KEY
;
2892 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2897 case _JSON_BUILD_ARRAY_BEGIN
:
2899 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2904 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2908 current
= stack
+ n_stack
- 1;
2910 if (current
->expect
== EXPECT_TOPLEVEL
)
2911 current
->expect
= EXPECT_END
;
2912 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2913 current
->expect
= EXPECT_OBJECT_KEY
;
2915 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2917 stack
[n_stack
++] = (JsonStack
) {
2918 .expect
= EXPECT_ARRAY_ELEMENT
,
2919 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
2920 * new array, then we should
2921 * also suppress all array
2927 case _JSON_BUILD_ARRAY_END
:
2928 if (current
->expect
!= EXPECT_ARRAY_ELEMENT
) {
2933 assert(n_stack
> 1);
2935 if (current
->n_suppress
== 0) {
2936 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2943 json_stack_release(current
);
2944 n_stack
--, current
--;
2948 case _JSON_BUILD_STRV
: {
2951 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2956 l
= va_arg(ap
, char **);
2958 if (current
->n_suppress
== 0) {
2959 r
= json_variant_new_array_strv(&add
, l
);
2966 if (current
->expect
== EXPECT_TOPLEVEL
)
2967 current
->expect
= EXPECT_END
;
2968 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2969 current
->expect
= EXPECT_OBJECT_KEY
;
2971 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2976 case _JSON_BUILD_OBJECT_BEGIN
:
2978 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2983 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2987 current
= stack
+ n_stack
- 1;
2989 if (current
->expect
== EXPECT_TOPLEVEL
)
2990 current
->expect
= EXPECT_END
;
2991 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2992 current
->expect
= EXPECT_OBJECT_KEY
;
2994 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2996 stack
[n_stack
++] = (JsonStack
) {
2997 .expect
= EXPECT_OBJECT_KEY
,
2998 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
2999 * new object, then we should
3000 * also suppress all object
3006 case _JSON_BUILD_OBJECT_END
:
3008 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3013 assert(n_stack
> 1);
3015 if (current
->n_suppress
== 0) {
3016 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
3023 json_stack_release(current
);
3024 n_stack
--, current
--;
3028 case _JSON_BUILD_PAIR
: {
3031 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3036 n
= va_arg(ap
, const char *);
3038 if (current
->n_suppress
== 0) {
3039 r
= json_variant_new_string(&add
, n
);
3046 current
->expect
= EXPECT_OBJECT_VALUE
;
3050 case _JSON_BUILD_PAIR_CONDITION
: {
3054 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3059 b
= va_arg(ap
, int);
3060 n
= va_arg(ap
, const char *);
3062 if (b
&& current
->n_suppress
== 0) {
3063 r
= json_variant_new_string(&add
, n
);
3068 n_subtract
= 1; /* we generated one item */
3070 if (!b
&& current
->n_suppress
!= (size_t) -1)
3071 current
->n_suppress
+= 2; /* Suppress this one and the next item */
3073 current
->expect
= EXPECT_OBJECT_VALUE
;
3077 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3078 if (add
&& current
->n_suppress
== 0) {
3079 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3084 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3087 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3088 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3089 * on this stack level */
3090 if (current
->n_suppress
!= (size_t) -1) {
3091 if (current
->n_suppress
<= n_subtract
) /* Saturated */
3092 current
->n_suppress
= 0;
3094 current
->n_suppress
-= n_subtract
;
3099 assert(n_stack
== 1);
3100 assert(stack
[0].n_elements
== 1);
3102 *ret
= json_variant_ref(stack
[0].elements
[0]);
3106 for (i
= 0; i
< n_stack
; i
++)
3107 json_stack_release(stack
+ i
);
3114 int json_build(JsonVariant
**ret
, ...) {
3119 r
= json_buildv(ret
, ap
);
3125 int json_log_internal(
3126 JsonVariant
*variant
,
3132 const char *format
, ...) {
3136 unsigned source_line
, source_column
;
3137 char buffer
[LINE_MAX
];
3142 errno
= ERRNO_VALUE(error
);
3144 va_start(ap
, format
);
3145 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
3149 r
= json_variant_get_source(variant
, &source
, &source_line
, &source_column
);
3158 if (source
&& source_line
> 0 && source_column
> 0)
3159 return log_struct_internal(
3160 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3163 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3164 "CONFIG_FILE=%s", source
,
3165 "CONFIG_LINE=%u", source_line
,
3166 "CONFIG_COLUMN=%u", source_column
,
3167 LOG_MESSAGE("%s:%u:%u: %s", source
, source_line
, source_column
, buffer
),
3170 return log_struct_internal(
3171 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3174 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3175 LOG_MESSAGE("%s", buffer
),
3179 int json_dispatch(JsonVariant
*v
, const JsonDispatch table
[], JsonDispatchCallback bad
, JsonDispatchFlags flags
, void *userdata
) {
3180 const JsonDispatch
*p
;
3185 if (!json_variant_is_object(v
)) {
3186 json_log(v
, flags
, 0, "JSON variant is not an object.");
3188 if (flags
& JSON_PERMISSIVE
)
3194 for (p
= table
, m
= 0; p
->name
; p
++)
3197 found
= newa0(bool, m
);
3199 n
= json_variant_elements(v
);
3200 for (i
= 0; i
< n
; i
+= 2) {
3201 JsonVariant
*key
, *value
;
3203 assert_se(key
= json_variant_by_index(v
, i
));
3204 assert_se(value
= json_variant_by_index(v
, i
+1));
3206 for (p
= table
; p
->name
; p
++)
3207 if (p
->name
== (const char*) -1 ||
3208 streq_ptr(json_variant_string(key
), p
->name
))
3211 if (p
->name
) { /* Found a matching entry! :-) */
3212 JsonDispatchFlags merged_flags
;
3214 merged_flags
= flags
| p
->flags
;
3216 if (p
->type
!= _JSON_VARIANT_TYPE_INVALID
&&
3217 !json_variant_has_type(value
, p
->type
)) {
3219 json_log(value
, merged_flags
, 0,
3220 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key
),
3221 json_variant_type_to_string(json_variant_type(value
)), json_variant_type_to_string(p
->type
));
3223 if (merged_flags
& JSON_PERMISSIVE
)
3229 if (found
[p
-table
]) {
3230 json_log(value
, merged_flags
, 0, "Duplicate object field '%s'.", json_variant_string(key
));
3232 if (merged_flags
& JSON_PERMISSIVE
)
3238 found
[p
-table
] = true;
3241 r
= p
->callback(json_variant_string(key
), value
, merged_flags
, (uint8_t*) userdata
+ p
->offset
);
3243 if (merged_flags
& JSON_PERMISSIVE
)
3252 } else { /* Didn't find a matching entry! :-( */
3255 r
= bad(json_variant_string(key
), value
, flags
, userdata
);
3257 if (flags
& JSON_PERMISSIVE
)
3265 json_log(value
, flags
, 0, "Unexpected object field '%s'.", json_variant_string(key
));
3267 if (flags
& JSON_PERMISSIVE
)
3270 return -EADDRNOTAVAIL
;
3275 for (p
= table
; p
->name
; p
++) {
3276 JsonDispatchFlags merged_flags
= p
->flags
| flags
;
3278 if ((merged_flags
& JSON_MANDATORY
) && !found
[p
-table
]) {
3279 json_log(v
, merged_flags
, 0, "Missing object field '%s'.", p
->name
);
3281 if ((merged_flags
& JSON_PERMISSIVE
))
3291 int json_dispatch_boolean(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3297 if (!json_variant_is_boolean(variant
))
3298 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3300 *b
= json_variant_boolean(variant
);
3304 int json_dispatch_tristate(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3310 if (!json_variant_is_boolean(variant
))
3311 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3313 *b
= json_variant_boolean(variant
);
3317 int json_dispatch_integer(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3318 intmax_t *i
= userdata
;
3323 if (!json_variant_is_integer(variant
))
3324 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3326 *i
= json_variant_integer(variant
);
3330 int json_dispatch_unsigned(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3331 uintmax_t *u
= userdata
;
3336 if (!json_variant_is_unsigned(variant
))
3337 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3339 *u
= json_variant_unsigned(variant
);
3343 int json_dispatch_uint32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3344 uint32_t *u
= userdata
;
3349 if (!json_variant_is_unsigned(variant
))
3350 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3352 if (json_variant_unsigned(variant
) > UINT32_MAX
)
3353 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3355 *u
= (uint32_t) json_variant_unsigned(variant
);
3359 int json_dispatch_int32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3360 int32_t *i
= userdata
;
3365 if (!json_variant_is_integer(variant
))
3366 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3368 if (json_variant_integer(variant
) < INT32_MIN
|| json_variant_integer(variant
) > INT32_MAX
)
3369 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3371 *i
= (int32_t) json_variant_integer(variant
);
3375 int json_dispatch_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3376 char **s
= userdata
;
3382 if (json_variant_is_null(variant
)) {
3387 if (!json_variant_is_string(variant
))
3388 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
3390 r
= free_and_strdup(s
, json_variant_string(variant
));
3392 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
3397 int json_dispatch_strv(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3398 _cleanup_strv_free_
char **l
= NULL
;
3399 char ***s
= userdata
;
3406 if (json_variant_is_null(variant
)) {
3411 if (!json_variant_is_array(variant
))
3412 return json_log(variant
, SYNTHETIC_ERRNO(EINVAL
), flags
, "JSON field '%s' is not an array.", strna(name
));
3414 for (i
= 0; i
< json_variant_elements(variant
); i
++) {
3417 assert_se(e
= json_variant_by_index(variant
, i
));
3419 if (!json_variant_is_string(e
))
3420 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON array element is not a string.");
3422 r
= strv_extend(&l
, json_variant_string(e
));
3424 return json_log(variant
, flags
, r
, "Failed to append array element: %m");
3427 strv_free_and_replace(*s
, l
);
3431 int json_dispatch_variant(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3432 JsonVariant
**p
= userdata
;
3437 json_variant_unref(*p
);
3438 *p
= json_variant_ref(variant
);
3443 static const char* const json_variant_type_table
[_JSON_VARIANT_TYPE_MAX
] = {
3444 [JSON_VARIANT_STRING
] = "string",
3445 [JSON_VARIANT_INTEGER
] = "integer",
3446 [JSON_VARIANT_UNSIGNED
] = "unsigned",
3447 [JSON_VARIANT_REAL
] = "real",
3448 [JSON_VARIANT_NUMBER
] = "number",
3449 [JSON_VARIANT_BOOLEAN
] = "boolean",
3450 [JSON_VARIANT_ARRAY
] = "array",
3451 [JSON_VARIANT_OBJECT
] = "object",
3452 [JSON_VARIANT_NULL
] = "null",
3455 DEFINE_STRING_TABLE_LOOKUP(json_variant_type
, JsonVariantType
);