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(&s
, &sz
);
1564 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
1566 json_variant_dump(v
, flags
, f
, NULL
);
1568 r
= fflush_and_check(f
);
1579 void json_variant_dump(JsonVariant
*v
, JsonFormatFlags flags
, FILE *f
, const char *prefix
) {
1586 print_source(f
, v
, flags
, false);
1588 if (((flags
& (JSON_FORMAT_COLOR_AUTO
|JSON_FORMAT_COLOR
)) == JSON_FORMAT_COLOR_AUTO
) && colors_enabled())
1589 flags
|= JSON_FORMAT_COLOR
;
1591 if (flags
& JSON_FORMAT_SSE
)
1593 if (flags
& JSON_FORMAT_SEQ
)
1594 fputc('\x1e', f
); /* ASCII Record Separator */
1596 json_format(f
, v
, flags
, prefix
);
1598 if (flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_SEQ
|JSON_FORMAT_SSE
|JSON_FORMAT_NEWLINE
))
1600 if (flags
& JSON_FORMAT_SSE
)
1601 fputc('\n', f
); /* In case of SSE add a second newline */
1604 static int json_variant_copy(JsonVariant
**nv
, JsonVariant
*v
) {
1614 /* Let's copy the simple types literally, and the larger types by references */
1615 t
= json_variant_type(v
);
1617 case JSON_VARIANT_INTEGER
:
1618 k
= sizeof(intmax_t);
1619 value
.integer
= json_variant_integer(v
);
1623 case JSON_VARIANT_UNSIGNED
:
1624 k
= sizeof(uintmax_t);
1625 value
.unsig
= json_variant_unsigned(v
);
1629 case JSON_VARIANT_REAL
:
1630 k
= sizeof(long double);
1631 value
.real
= json_variant_real(v
);
1635 case JSON_VARIANT_BOOLEAN
:
1637 value
.boolean
= json_variant_boolean(v
);
1641 case JSON_VARIANT_NULL
:
1646 case JSON_VARIANT_STRING
:
1647 source
= json_variant_string(v
);
1648 k
= strnlen(source
, INLINE_STRING_MAX
+ 1);
1649 if (k
<= INLINE_STRING_MAX
) {
1657 /* Everything else copy by reference */
1659 c
= malloc0(offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*));
1665 c
->is_reference
= true;
1666 c
->reference
= json_variant_ref(json_variant_normalize(v
));
1672 c
= malloc0(offsetof(JsonVariant
, value
) + k
);
1679 memcpy_safe(&c
->value
, source
, k
);
1685 static bool json_single_ref(JsonVariant
*v
) {
1687 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
1689 if (!json_variant_is_regular(v
))
1693 return json_single_ref(v
->parent
);
1695 assert(v
->n_ref
> 0);
1696 return v
->n_ref
== 1;
1699 static int json_variant_set_source(JsonVariant
**v
, JsonSource
*source
, unsigned line
, unsigned column
) {
1705 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole referencer of
1706 * the object. If not, allocates a new object, possibly a surrogate for the original one */
1711 if (source
&& line
> source
->max_line
)
1712 source
->max_line
= line
;
1713 if (source
&& column
> source
->max_column
)
1714 source
->max_column
= column
;
1716 if (!json_variant_is_regular(*v
)) {
1718 if (!source
&& line
== 0 && column
== 0)
1722 if (json_source_equal((*v
)->source
, source
) &&
1723 (*v
)->line
== line
&&
1724 (*v
)->column
== column
)
1727 if (json_single_ref(*v
)) { /* Sole reference? */
1728 json_source_unref((*v
)->source
);
1729 (*v
)->source
= json_source_ref(source
);
1731 (*v
)->column
= column
;
1736 r
= json_variant_copy(&w
, *v
);
1740 assert(json_variant_is_regular(w
));
1741 assert(!w
->is_embedded
);
1742 assert(w
->n_ref
== 1);
1745 w
->source
= json_source_ref(source
);
1749 json_variant_unref(*v
);
1755 static void inc_lines_columns(unsigned *line
, unsigned *column
, const char *s
, size_t n
) {
1758 assert(s
|| n
== 0);
1764 } else if ((signed char) *s
>= 0 && *s
< 127) /* Process ASCII chars quickly */
1769 w
= utf8_encoded_valid_unichar(s
, n
);
1770 if (w
< 0) /* count invalid unichars as normal characters */
1772 else if ((size_t) w
> n
) /* never read more than the specified number of characters */
1787 static int unhex_ucs2(const char *c
, uint16_t *ret
) {
1794 aa
= unhexchar(c
[0]);
1798 bb
= unhexchar(c
[1]);
1802 cc
= unhexchar(c
[2]);
1806 dd
= unhexchar(c
[3]);
1810 x
= ((uint16_t) aa
<< 12) |
1811 ((uint16_t) bb
<< 8) |
1812 ((uint16_t) cc
<< 4) |
1823 static int json_parse_string(const char **p
, char **ret
) {
1824 _cleanup_free_
char *s
= NULL
;
1825 size_t n
= 0, allocated
= 0;
1846 /* Check for control characters 0x00..0x1f */
1847 if (*c
> 0 && *c
< ' ')
1850 /* Check for control character 0x7f */
1865 return JSON_TOKEN_STRING
;
1875 if (IN_SET(*c
, '"', '\\', '/'))
1887 else if (*c
== 'u') {
1891 r
= unhex_ucs2(c
+ 1, &x
);
1897 if (!GREEDY_REALLOC(s
, allocated
, n
+ 5))
1900 if (!utf16_is_surrogate(x
))
1901 n
+= utf8_encode_unichar(s
+ n
, (char32_t
) x
);
1902 else if (utf16_is_trailing_surrogate(x
))
1907 if (c
[0] != '\\' || c
[1] != 'u')
1910 r
= unhex_ucs2(c
+ 2, &y
);
1916 if (!utf16_is_trailing_surrogate(y
))
1919 n
+= utf8_encode_unichar(s
+ n
, utf16_surrogate_pair_to_unichar(x
, y
));
1926 if (!GREEDY_REALLOC(s
, allocated
, n
+ 2))
1934 len
= utf8_encoded_valid_unichar(c
, (size_t) -1);
1938 if (!GREEDY_REALLOC(s
, allocated
, n
+ len
+ 1))
1941 memcpy(s
+ n
, c
, len
);
1947 static int json_parse_number(const char **p
, JsonValue
*ret
) {
1948 bool negative
= false, exponent_negative
= false, is_real
= false;
1949 long double x
= 0.0, y
= 0.0, exponent
= 0.0, shift
= 1.0;
1968 if (!strchr("123456789", *c
) || *c
== 0)
1975 if (i
< INTMAX_MIN
/ 10) /* overflow */
1978 intmax_t t
= 10 * i
;
1980 if (t
< INTMAX_MIN
+ (*c
- '0')) /* overflow */
1986 if (u
> UINTMAX_MAX
/ 10) /* overflow */
1989 uintmax_t t
= 10 * u
;
1991 if (t
> UINTMAX_MAX
- (*c
- '0')) /* overflow */
1999 x
= 10.0 * x
+ (*c
- '0');
2002 } while (strchr("0123456789", *c
) && *c
!= 0);
2009 if (!strchr("0123456789", *c
) || *c
== 0)
2013 y
= 10.0 * y
+ (*c
- '0');
2014 shift
= 10.0 * shift
;
2016 } while (strchr("0123456789", *c
) && *c
!= 0);
2019 if (IN_SET(*c
, 'e', 'E')) {
2024 exponent_negative
= true;
2026 } else if (*c
== '+')
2029 if (!strchr("0123456789", *c
) || *c
== 0)
2033 exponent
= 10.0 * exponent
+ (*c
- '0');
2035 } while (strchr("0123456789", *c
) && *c
!= 0);
2041 ret
->real
= ((negative
? -1.0 : 1.0) * (x
+ (y
/ shift
))) * exp10l((exponent_negative
? -1.0 : 1.0) * exponent
);
2042 return JSON_TOKEN_REAL
;
2043 } else if (negative
) {
2045 return JSON_TOKEN_INTEGER
;
2048 return JSON_TOKEN_UNSIGNED
;
2055 JsonValue
*ret_value
,
2056 unsigned *ret_line
, /* 'ret_line' returns the line at the beginning of this token */
2057 unsigned *ret_column
,
2059 unsigned *line
, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2062 unsigned start_line
, start_column
;
2063 const char *start
, *c
;
2083 t
= PTR_TO_INT(*state
);
2084 if (t
== STATE_NULL
) {
2090 /* Skip over the whitespace */
2091 n
= strspn(*p
, WHITESPACE
);
2092 inc_lines_columns(line
, column
, *p
, n
);
2095 /* Remember where we started processing this token */
2098 start_column
= *column
;
2102 *ret_value
= JSON_VALUE_NULL
;
2113 *state
= INT_TO_PTR(STATE_VALUE
);
2114 r
= JSON_TOKEN_OBJECT_OPEN
;
2117 } else if (*c
== '}') {
2119 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2120 r
= JSON_TOKEN_OBJECT_CLOSE
;
2123 } else if (*c
== '[') {
2125 *state
= INT_TO_PTR(STATE_VALUE
);
2126 r
= JSON_TOKEN_ARRAY_OPEN
;
2129 } else if (*c
== ']') {
2131 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2132 r
= JSON_TOKEN_ARRAY_CLOSE
;
2135 } else if (*c
== '"') {
2137 r
= json_parse_string(&c
, ret_string
);
2141 *ret_value
= JSON_VALUE_NULL
;
2142 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2145 } else if (strchr("-0123456789", *c
)) {
2147 r
= json_parse_number(&c
, ret_value
);
2152 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2155 } else if (startswith(c
, "true")) {
2157 ret_value
->boolean
= true;
2159 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2160 r
= JSON_TOKEN_BOOLEAN
;
2163 } else if (startswith(c
, "false")) {
2165 ret_value
->boolean
= false;
2167 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2168 r
= JSON_TOKEN_BOOLEAN
;
2171 } else if (startswith(c
, "null")) {
2173 *ret_value
= JSON_VALUE_NULL
;
2175 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2176 r
= JSON_TOKEN_NULL
;
2183 case STATE_VALUE_POST
:
2187 *state
= INT_TO_PTR(STATE_VALUE
);
2188 r
= JSON_TOKEN_COLON
;
2191 } else if (*c
== ',') {
2193 *state
= INT_TO_PTR(STATE_VALUE
);
2194 r
= JSON_TOKEN_COMMA
;
2197 } else if (*c
== '}') {
2199 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2200 r
= JSON_TOKEN_OBJECT_CLOSE
;
2203 } else if (*c
== ']') {
2205 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2206 r
= JSON_TOKEN_ARRAY_CLOSE
;
2213 assert_not_reached("Unexpected tokenizer state");
2218 *ret_value
= JSON_VALUE_NULL
;
2221 inc_lines_columns(line
, column
, start
, c
- start
);
2224 *ret_line
= start_line
;
2225 *ret_column
= start_column
;
2230 typedef enum JsonExpect
{
2231 /* The following values are used by json_parse() */
2234 EXPECT_OBJECT_FIRST_KEY
,
2235 EXPECT_OBJECT_NEXT_KEY
,
2236 EXPECT_OBJECT_COLON
,
2237 EXPECT_OBJECT_VALUE
,
2238 EXPECT_OBJECT_COMMA
,
2239 EXPECT_ARRAY_FIRST_ELEMENT
,
2240 EXPECT_ARRAY_NEXT_ELEMENT
,
2243 /* And these are used by json_build() */
2244 EXPECT_ARRAY_ELEMENT
,
2248 typedef struct JsonStack
{
2250 JsonVariant
**elements
;
2251 size_t n_elements
, n_elements_allocated
;
2252 unsigned line_before
;
2253 unsigned column_before
;
2254 size_t n_suppress
; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2257 static void json_stack_release(JsonStack
*s
) {
2260 json_variant_unref_many(s
->elements
, s
->n_elements
);
2261 s
->elements
= mfree(s
->elements
);
2264 static int json_parse_internal(
2270 bool continue_end
) {
2272 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2273 unsigned line_buffer
= 0, column_buffer
= 0;
2274 void *tokenizer_state
= NULL
;
2275 JsonStack
*stack
= NULL
;
2279 assert_return(input
, -EINVAL
);
2280 assert_return(ret
, -EINVAL
);
2284 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2287 stack
[0] = (JsonStack
) {
2288 .expect
= EXPECT_TOPLEVEL
,
2292 line
= &line_buffer
;
2294 column
= &column_buffer
;
2297 _cleanup_free_
char *string
= NULL
;
2298 unsigned line_token
, column_token
;
2299 JsonVariant
*add
= NULL
;
2304 assert(n_stack
> 0);
2305 current
= stack
+ n_stack
- 1;
2307 if (continue_end
&& current
->expect
== EXPECT_END
)
2310 token
= json_tokenize(&p
, &string
, &value
, &line_token
, &column_token
, &tokenizer_state
, line
, column
);
2318 case JSON_TOKEN_END
:
2319 if (current
->expect
!= EXPECT_END
) {
2324 assert(current
->n_elements
== 1);
2325 assert(n_stack
== 1);
2328 case JSON_TOKEN_COLON
:
2330 if (current
->expect
!= EXPECT_OBJECT_COLON
) {
2335 current
->expect
= EXPECT_OBJECT_VALUE
;
2338 case JSON_TOKEN_COMMA
:
2340 if (current
->expect
== EXPECT_OBJECT_COMMA
)
2341 current
->expect
= EXPECT_OBJECT_NEXT_KEY
;
2342 else if (current
->expect
== EXPECT_ARRAY_COMMA
)
2343 current
->expect
= EXPECT_ARRAY_NEXT_ELEMENT
;
2351 case JSON_TOKEN_OBJECT_OPEN
:
2353 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2358 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2362 current
= stack
+ n_stack
- 1;
2364 /* Prepare the expect for when we return from the child */
2365 if (current
->expect
== EXPECT_TOPLEVEL
)
2366 current
->expect
= EXPECT_END
;
2367 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2368 current
->expect
= EXPECT_OBJECT_COMMA
;
2370 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2371 current
->expect
= EXPECT_ARRAY_COMMA
;
2374 stack
[n_stack
++] = (JsonStack
) {
2375 .expect
= EXPECT_OBJECT_FIRST_KEY
,
2376 .line_before
= line_token
,
2377 .column_before
= column_token
,
2380 current
= stack
+ n_stack
- 1;
2383 case JSON_TOKEN_OBJECT_CLOSE
:
2384 if (!IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_COMMA
)) {
2389 assert(n_stack
> 1);
2391 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
2395 line_token
= current
->line_before
;
2396 column_token
= current
->column_before
;
2398 json_stack_release(current
);
2399 n_stack
--, current
--;
2403 case JSON_TOKEN_ARRAY_OPEN
:
2404 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2409 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2413 current
= stack
+ n_stack
- 1;
2415 /* Prepare the expect for when we return from the child */
2416 if (current
->expect
== EXPECT_TOPLEVEL
)
2417 current
->expect
= EXPECT_END
;
2418 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2419 current
->expect
= EXPECT_OBJECT_COMMA
;
2421 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2422 current
->expect
= EXPECT_ARRAY_COMMA
;
2425 stack
[n_stack
++] = (JsonStack
) {
2426 .expect
= EXPECT_ARRAY_FIRST_ELEMENT
,
2427 .line_before
= line_token
,
2428 .column_before
= column_token
,
2433 case JSON_TOKEN_ARRAY_CLOSE
:
2434 if (!IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_COMMA
)) {
2439 assert(n_stack
> 1);
2441 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2445 line_token
= current
->line_before
;
2446 column_token
= current
->column_before
;
2448 json_stack_release(current
);
2449 n_stack
--, current
--;
2452 case JSON_TOKEN_STRING
:
2453 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
)) {
2458 r
= json_variant_new_string(&add
, string
);
2462 if (current
->expect
== EXPECT_TOPLEVEL
)
2463 current
->expect
= EXPECT_END
;
2464 else if (IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_NEXT_KEY
))
2465 current
->expect
= EXPECT_OBJECT_COLON
;
2466 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2467 current
->expect
= EXPECT_OBJECT_COMMA
;
2469 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2470 current
->expect
= EXPECT_ARRAY_COMMA
;
2475 case JSON_TOKEN_REAL
:
2476 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2481 r
= json_variant_new_real(&add
, value
.real
);
2485 if (current
->expect
== EXPECT_TOPLEVEL
)
2486 current
->expect
= EXPECT_END
;
2487 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2488 current
->expect
= EXPECT_OBJECT_COMMA
;
2490 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2491 current
->expect
= EXPECT_ARRAY_COMMA
;
2496 case JSON_TOKEN_INTEGER
:
2497 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2502 r
= json_variant_new_integer(&add
, value
.integer
);
2506 if (current
->expect
== EXPECT_TOPLEVEL
)
2507 current
->expect
= EXPECT_END
;
2508 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2509 current
->expect
= EXPECT_OBJECT_COMMA
;
2511 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2512 current
->expect
= EXPECT_ARRAY_COMMA
;
2517 case JSON_TOKEN_UNSIGNED
:
2518 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2523 r
= json_variant_new_unsigned(&add
, value
.unsig
);
2527 if (current
->expect
== EXPECT_TOPLEVEL
)
2528 current
->expect
= EXPECT_END
;
2529 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2530 current
->expect
= EXPECT_OBJECT_COMMA
;
2532 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2533 current
->expect
= EXPECT_ARRAY_COMMA
;
2538 case JSON_TOKEN_BOOLEAN
:
2539 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2544 r
= json_variant_new_boolean(&add
, value
.boolean
);
2548 if (current
->expect
== EXPECT_TOPLEVEL
)
2549 current
->expect
= EXPECT_END
;
2550 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2551 current
->expect
= EXPECT_OBJECT_COMMA
;
2553 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2554 current
->expect
= EXPECT_ARRAY_COMMA
;
2559 case JSON_TOKEN_NULL
:
2560 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2565 r
= json_variant_new_null(&add
);
2569 if (current
->expect
== EXPECT_TOPLEVEL
)
2570 current
->expect
= EXPECT_END
;
2571 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2572 current
->expect
= EXPECT_OBJECT_COMMA
;
2574 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2575 current
->expect
= EXPECT_ARRAY_COMMA
;
2581 assert_not_reached("Unexpected token");
2585 (void) json_variant_set_source(&add
, source
, line_token
, column_token
);
2587 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
2592 current
->elements
[current
->n_elements
++] = add
;
2597 assert(n_stack
== 1);
2598 assert(stack
[0].n_elements
== 1);
2600 *ret
= json_variant_ref(stack
[0].elements
[0]);
2605 for (i
= 0; i
< n_stack
; i
++)
2606 json_stack_release(stack
+ i
);
2613 int json_parse(const char *input
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2614 return json_parse_internal(&input
, NULL
, ret
, ret_line
, ret_column
, false);
2617 int json_parse_continue(const char **p
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2618 return json_parse_internal(p
, NULL
, ret
, ret_line
, ret_column
, true);
2621 int json_parse_file(FILE *f
, const char *path
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2622 _cleanup_(json_source_unrefp
) JsonSource
*source
= NULL
;
2623 _cleanup_free_
char *text
= NULL
;
2628 r
= read_full_stream(f
, &text
, NULL
);
2630 r
= read_full_file(path
, &text
, NULL
);
2637 source
= json_source_new(path
);
2643 return json_parse_internal(&p
, source
, ret
, ret_line
, ret_column
, false);
2646 int json_buildv(JsonVariant
**ret
, va_list ap
) {
2647 JsonStack
*stack
= NULL
;
2648 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2651 assert_return(ret
, -EINVAL
);
2653 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2656 stack
[0] = (JsonStack
) {
2657 .expect
= EXPECT_TOPLEVEL
,
2661 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
2662 size_t n_subtract
= 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
2663 * have been added to the current variant */
2667 assert(n_stack
> 0);
2668 current
= stack
+ n_stack
- 1;
2670 if (current
->expect
== EXPECT_END
)
2673 command
= va_arg(ap
, int);
2677 case _JSON_BUILD_STRING
: {
2680 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2685 p
= va_arg(ap
, const char *);
2687 if (current
->n_suppress
== 0) {
2688 r
= json_variant_new_string(&add
, p
);
2695 if (current
->expect
== EXPECT_TOPLEVEL
)
2696 current
->expect
= EXPECT_END
;
2697 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2698 current
->expect
= EXPECT_OBJECT_KEY
;
2700 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2705 case _JSON_BUILD_INTEGER
: {
2708 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2713 j
= va_arg(ap
, intmax_t);
2715 if (current
->n_suppress
== 0) {
2716 r
= json_variant_new_integer(&add
, j
);
2723 if (current
->expect
== EXPECT_TOPLEVEL
)
2724 current
->expect
= EXPECT_END
;
2725 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2726 current
->expect
= EXPECT_OBJECT_KEY
;
2728 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2733 case _JSON_BUILD_UNSIGNED
: {
2736 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2741 j
= va_arg(ap
, uintmax_t);
2743 if (current
->n_suppress
== 0) {
2744 r
= json_variant_new_unsigned(&add
, j
);
2751 if (current
->expect
== EXPECT_TOPLEVEL
)
2752 current
->expect
= EXPECT_END
;
2753 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2754 current
->expect
= EXPECT_OBJECT_KEY
;
2756 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2761 case _JSON_BUILD_REAL
: {
2764 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2769 d
= va_arg(ap
, long double);
2771 if (current
->n_suppress
== 0) {
2772 r
= json_variant_new_real(&add
, d
);
2779 if (current
->expect
== EXPECT_TOPLEVEL
)
2780 current
->expect
= EXPECT_END
;
2781 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2782 current
->expect
= EXPECT_OBJECT_KEY
;
2784 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2789 case _JSON_BUILD_BOOLEAN
: {
2792 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2797 b
= va_arg(ap
, int);
2799 if (current
->n_suppress
== 0) {
2800 r
= json_variant_new_boolean(&add
, b
);
2807 if (current
->expect
== EXPECT_TOPLEVEL
)
2808 current
->expect
= EXPECT_END
;
2809 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2810 current
->expect
= EXPECT_OBJECT_KEY
;
2812 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2817 case _JSON_BUILD_NULL
:
2819 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2824 if (current
->n_suppress
== 0) {
2825 r
= json_variant_new_null(&add
);
2832 if (current
->expect
== EXPECT_TOPLEVEL
)
2833 current
->expect
= EXPECT_END
;
2834 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2835 current
->expect
= EXPECT_OBJECT_KEY
;
2837 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2841 case _JSON_BUILD_VARIANT
:
2843 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2848 /* Note that we don't care for current->n_suppress here, after all the variant is already
2849 * allocated anyway... */
2850 add
= va_arg(ap
, JsonVariant
*);
2852 add
= JSON_VARIANT_MAGIC_NULL
;
2854 json_variant_ref(add
);
2858 if (current
->expect
== EXPECT_TOPLEVEL
)
2859 current
->expect
= EXPECT_END
;
2860 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2861 current
->expect
= EXPECT_OBJECT_KEY
;
2863 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2867 case _JSON_BUILD_LITERAL
: {
2870 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2875 l
= va_arg(ap
, const char *);
2878 /* Note that we don't care for current->n_suppress here, we should generate parsing
2879 * errors even in suppressed object properties */
2881 r
= json_parse(l
, &add
, NULL
, NULL
);
2885 add
= JSON_VARIANT_MAGIC_NULL
;
2889 if (current
->expect
== EXPECT_TOPLEVEL
)
2890 current
->expect
= EXPECT_END
;
2891 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2892 current
->expect
= EXPECT_OBJECT_KEY
;
2894 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2899 case _JSON_BUILD_ARRAY_BEGIN
:
2901 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2906 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2910 current
= stack
+ n_stack
- 1;
2912 if (current
->expect
== EXPECT_TOPLEVEL
)
2913 current
->expect
= EXPECT_END
;
2914 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2915 current
->expect
= EXPECT_OBJECT_KEY
;
2917 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2919 stack
[n_stack
++] = (JsonStack
) {
2920 .expect
= EXPECT_ARRAY_ELEMENT
,
2921 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
2922 * new array, then we should
2923 * also suppress all array
2929 case _JSON_BUILD_ARRAY_END
:
2930 if (current
->expect
!= EXPECT_ARRAY_ELEMENT
) {
2935 assert(n_stack
> 1);
2937 if (current
->n_suppress
== 0) {
2938 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2945 json_stack_release(current
);
2946 n_stack
--, current
--;
2950 case _JSON_BUILD_STRV
: {
2953 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2958 l
= va_arg(ap
, char **);
2960 if (current
->n_suppress
== 0) {
2961 r
= json_variant_new_array_strv(&add
, l
);
2968 if (current
->expect
== EXPECT_TOPLEVEL
)
2969 current
->expect
= EXPECT_END
;
2970 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2971 current
->expect
= EXPECT_OBJECT_KEY
;
2973 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2978 case _JSON_BUILD_OBJECT_BEGIN
:
2980 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2985 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2989 current
= stack
+ n_stack
- 1;
2991 if (current
->expect
== EXPECT_TOPLEVEL
)
2992 current
->expect
= EXPECT_END
;
2993 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2994 current
->expect
= EXPECT_OBJECT_KEY
;
2996 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2998 stack
[n_stack
++] = (JsonStack
) {
2999 .expect
= EXPECT_OBJECT_KEY
,
3000 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3001 * new object, then we should
3002 * also suppress all object
3008 case _JSON_BUILD_OBJECT_END
:
3010 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3015 assert(n_stack
> 1);
3017 if (current
->n_suppress
== 0) {
3018 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
3025 json_stack_release(current
);
3026 n_stack
--, current
--;
3030 case _JSON_BUILD_PAIR
: {
3033 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3038 n
= va_arg(ap
, const char *);
3040 if (current
->n_suppress
== 0) {
3041 r
= json_variant_new_string(&add
, n
);
3048 current
->expect
= EXPECT_OBJECT_VALUE
;
3052 case _JSON_BUILD_PAIR_CONDITION
: {
3056 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3061 b
= va_arg(ap
, int);
3062 n
= va_arg(ap
, const char *);
3064 if (b
&& current
->n_suppress
== 0) {
3065 r
= json_variant_new_string(&add
, n
);
3070 n_subtract
= 1; /* we generated one item */
3072 if (!b
&& current
->n_suppress
!= (size_t) -1)
3073 current
->n_suppress
+= 2; /* Suppress this one and the next item */
3075 current
->expect
= EXPECT_OBJECT_VALUE
;
3079 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3080 if (add
&& current
->n_suppress
== 0) {
3081 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3086 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3089 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3090 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3091 * on this stack level */
3092 if (current
->n_suppress
!= (size_t) -1) {
3093 if (current
->n_suppress
<= n_subtract
) /* Saturated */
3094 current
->n_suppress
= 0;
3096 current
->n_suppress
-= n_subtract
;
3101 assert(n_stack
== 1);
3102 assert(stack
[0].n_elements
== 1);
3104 *ret
= json_variant_ref(stack
[0].elements
[0]);
3108 for (i
= 0; i
< n_stack
; i
++)
3109 json_stack_release(stack
+ i
);
3116 int json_build(JsonVariant
**ret
, ...) {
3121 r
= json_buildv(ret
, ap
);
3127 int json_log_internal(
3128 JsonVariant
*variant
,
3134 const char *format
, ...) {
3138 unsigned source_line
, source_column
;
3139 char buffer
[LINE_MAX
];
3144 errno
= ERRNO_VALUE(error
);
3146 va_start(ap
, format
);
3147 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
3151 r
= json_variant_get_source(variant
, &source
, &source_line
, &source_column
);
3160 if (source
&& source_line
> 0 && source_column
> 0)
3161 return log_struct_internal(
3162 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3165 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3166 "CONFIG_FILE=%s", source
,
3167 "CONFIG_LINE=%u", source_line
,
3168 "CONFIG_COLUMN=%u", source_column
,
3169 LOG_MESSAGE("%s:%u:%u: %s", source
, source_line
, source_column
, buffer
),
3172 return log_struct_internal(
3173 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3176 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3177 LOG_MESSAGE("%s", buffer
),
3181 int json_dispatch(JsonVariant
*v
, const JsonDispatch table
[], JsonDispatchCallback bad
, JsonDispatchFlags flags
, void *userdata
) {
3182 const JsonDispatch
*p
;
3187 if (!json_variant_is_object(v
)) {
3188 json_log(v
, flags
, 0, "JSON variant is not an object.");
3190 if (flags
& JSON_PERMISSIVE
)
3196 for (p
= table
, m
= 0; p
->name
; p
++)
3199 found
= newa0(bool, m
);
3201 n
= json_variant_elements(v
);
3202 for (i
= 0; i
< n
; i
+= 2) {
3203 JsonVariant
*key
, *value
;
3205 assert_se(key
= json_variant_by_index(v
, i
));
3206 assert_se(value
= json_variant_by_index(v
, i
+1));
3208 for (p
= table
; p
->name
; p
++)
3209 if (p
->name
== (const char*) -1 ||
3210 streq_ptr(json_variant_string(key
), p
->name
))
3213 if (p
->name
) { /* Found a matching entry! :-) */
3214 JsonDispatchFlags merged_flags
;
3216 merged_flags
= flags
| p
->flags
;
3218 if (p
->type
!= _JSON_VARIANT_TYPE_INVALID
&&
3219 !json_variant_has_type(value
, p
->type
)) {
3221 json_log(value
, merged_flags
, 0,
3222 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key
),
3223 json_variant_type_to_string(json_variant_type(value
)), json_variant_type_to_string(p
->type
));
3225 if (merged_flags
& JSON_PERMISSIVE
)
3231 if (found
[p
-table
]) {
3232 json_log(value
, merged_flags
, 0, "Duplicate object field '%s'.", json_variant_string(key
));
3234 if (merged_flags
& JSON_PERMISSIVE
)
3240 found
[p
-table
] = true;
3243 r
= p
->callback(json_variant_string(key
), value
, merged_flags
, (uint8_t*) userdata
+ p
->offset
);
3245 if (merged_flags
& JSON_PERMISSIVE
)
3254 } else { /* Didn't find a matching entry! :-( */
3257 r
= bad(json_variant_string(key
), value
, flags
, userdata
);
3259 if (flags
& JSON_PERMISSIVE
)
3267 json_log(value
, flags
, 0, "Unexpected object field '%s'.", json_variant_string(key
));
3269 if (flags
& JSON_PERMISSIVE
)
3272 return -EADDRNOTAVAIL
;
3277 for (p
= table
; p
->name
; p
++) {
3278 JsonDispatchFlags merged_flags
= p
->flags
| flags
;
3280 if ((merged_flags
& JSON_MANDATORY
) && !found
[p
-table
]) {
3281 json_log(v
, merged_flags
, 0, "Missing object field '%s'.", p
->name
);
3283 if ((merged_flags
& JSON_PERMISSIVE
))
3293 int json_dispatch_boolean(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3299 if (!json_variant_is_boolean(variant
)) {
3300 json_log(variant
, flags
, 0, "JSON field '%s' is not a boolean.", strna(name
));
3304 *b
= json_variant_boolean(variant
);
3308 int json_dispatch_tristate(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3314 if (!json_variant_is_boolean(variant
)) {
3315 json_log(variant
, flags
, 0, "JSON field '%s' is not a boolean.", strna(name
));
3319 *b
= json_variant_boolean(variant
);
3323 int json_dispatch_integer(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3324 intmax_t *i
= userdata
;
3329 if (!json_variant_is_integer(variant
)) {
3330 json_log(variant
, flags
, 0, "JSON field '%s' is not an integer.", strna(name
));
3334 *i
= json_variant_integer(variant
);
3338 int json_dispatch_unsigned(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3339 uintmax_t *u
= userdata
;
3344 if (!json_variant_is_unsigned(variant
)) {
3345 json_log(variant
, flags
, 0, "JSON field '%s' is not an unsigned integer.", strna(name
));
3349 *u
= json_variant_unsigned(variant
);
3353 int json_dispatch_uint32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3354 uint32_t *u
= userdata
;
3359 if (!json_variant_is_unsigned(variant
)) {
3360 json_log(variant
, flags
, 0, "JSON field '%s' is not an unsigned integer.", strna(name
));
3364 if (json_variant_unsigned(variant
) > UINT32_MAX
) {
3365 json_log(variant
, flags
, 0, "JSON field '%s' out of bounds.", strna(name
));
3369 *u
= (uint32_t) json_variant_unsigned(variant
);
3373 int json_dispatch_int32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3374 int32_t *i
= userdata
;
3379 if (!json_variant_is_integer(variant
)) {
3380 json_log(variant
, flags
, 0, "JSON field '%s' is not an integer.", strna(name
));
3384 if (json_variant_integer(variant
) < INT32_MIN
|| json_variant_integer(variant
) > INT32_MAX
) {
3385 json_log(variant
, flags
, 0, "JSON field '%s' out of bounds.", strna(name
));
3389 *i
= (int32_t) json_variant_integer(variant
);
3393 int json_dispatch_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3394 char **s
= userdata
;
3400 if (json_variant_is_null(variant
)) {
3405 if (!json_variant_is_string(variant
)) {
3406 json_log(variant
, flags
, 0, "JSON field '%s' is not a string.", strna(name
));
3410 r
= free_and_strdup(s
, json_variant_string(variant
));
3412 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
3417 int json_dispatch_strv(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3418 _cleanup_strv_free_
char **l
= NULL
;
3419 char ***s
= userdata
;
3426 if (json_variant_is_null(variant
)) {
3431 if (!json_variant_is_array(variant
)) {
3432 json_log(variant
, 0, flags
, "JSON field '%s' is not an array.", strna(name
));
3436 for (i
= 0; i
< json_variant_elements(variant
); i
++) {
3439 assert_se(e
= json_variant_by_index(variant
, i
));
3441 if (!json_variant_is_string(e
)) {
3442 json_log(e
, 0, flags
, "JSON array element is not a string.");
3446 r
= strv_extend(&l
, json_variant_string(e
));
3448 return json_log(variant
, flags
, r
, "Failed to append array element: %m");
3451 strv_free_and_replace(*s
, l
);
3455 int json_dispatch_variant(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3456 JsonVariant
**p
= userdata
;
3461 json_variant_unref(*p
);
3462 *p
= json_variant_ref(variant
);
3467 static const char* const json_variant_type_table
[_JSON_VARIANT_TYPE_MAX
] = {
3468 [JSON_VARIANT_STRING
] = "string",
3469 [JSON_VARIANT_INTEGER
] = "integer",
3470 [JSON_VARIANT_UNSIGNED
] = "unsigned",
3471 [JSON_VARIANT_REAL
] = "real",
3472 [JSON_VARIANT_NUMBER
] = "number",
3473 [JSON_VARIANT_BOOLEAN
] = "boolean",
3474 [JSON_VARIANT_ARRAY
] = "array",
3475 [JSON_VARIANT_OBJECT
] = "object",
3476 [JSON_VARIANT_NULL
] = "null",
3479 DEFINE_STRING_TABLE_LOOKUP(json_variant_type
, JsonVariantType
);