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(IN_SET(n
, 0, (size_t) -1), -EINVAL
);
383 return json_variant_new_null(ret
);
385 if (n
== (size_t) -1) /* determine length automatically */
387 else if (memchr(s
, 0, n
)) /* don't allow embedded NUL, as we can't express that in JSON */
390 *ret
= JSON_VARIANT_MAGIC_EMPTY_STRING
;
394 r
= json_variant_new(&v
, JSON_VARIANT_STRING
, n
+ 1);
398 memcpy(v
->string
, s
, n
);
405 static void json_variant_set(JsonVariant
*a
, JsonVariant
*b
) {
408 b
= json_variant_dereference(b
);
410 a
->type
= JSON_VARIANT_NULL
;
414 a
->type
= json_variant_type(b
);
417 case JSON_VARIANT_INTEGER
:
418 a
->value
.integer
= json_variant_integer(b
);
421 case JSON_VARIANT_UNSIGNED
:
422 a
->value
.unsig
= json_variant_unsigned(b
);
425 case JSON_VARIANT_REAL
:
426 a
->value
.real
= json_variant_real(b
);
429 case JSON_VARIANT_BOOLEAN
:
430 a
->value
.boolean
= json_variant_boolean(b
);
433 case JSON_VARIANT_STRING
: {
436 assert_se(s
= json_variant_string(b
));
438 /* Short strings we can store inline */
439 if (strnlen(s
, INLINE_STRING_MAX
+1) <= INLINE_STRING_MAX
) {
440 strcpy(a
->string
, s
);
444 /* For longer strings, use a reference… */
448 case JSON_VARIANT_ARRAY
:
449 case JSON_VARIANT_OBJECT
:
450 a
->is_reference
= true;
451 a
->reference
= json_variant_ref(json_variant_conservative_normalize(b
));
454 case JSON_VARIANT_NULL
:
458 assert_not_reached("Unexpected variant type");
462 static void json_variant_copy_source(JsonVariant
*v
, JsonVariant
*from
) {
466 if (!json_variant_is_regular(from
))
469 v
->line
= from
->line
;
470 v
->column
= from
->column
;
471 v
->source
= json_source_ref(from
->source
);
474 int json_variant_new_array(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
475 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
477 assert_return(ret
, -EINVAL
);
479 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
482 assert_return(array
, -EINVAL
);
484 v
= new(JsonVariant
, n
+ 1);
490 .type
= JSON_VARIANT_ARRAY
,
493 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
494 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
495 *c
= array
[v
->n_elements
];
498 d
= json_variant_depth(c
);
499 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
509 json_variant_set(w
, c
);
510 json_variant_copy_source(w
, c
);
517 int json_variant_new_array_bytes(JsonVariant
**ret
, const void *p
, size_t n
) {
521 assert_return(ret
, -EINVAL
);
523 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
526 assert_return(p
, -EINVAL
);
528 v
= new(JsonVariant
, n
+ 1);
534 .type
= JSON_VARIANT_ARRAY
,
539 for (i
= 0; i
< n
; i
++) {
540 JsonVariant
*w
= v
+ 1 + i
;
545 .type
= JSON_VARIANT_UNSIGNED
,
546 .value
.unsig
= ((const uint8_t*) p
)[i
],
554 int json_variant_new_array_strv(JsonVariant
**ret
, char **l
) {
555 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
563 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
567 v
= new(JsonVariant
, n
+ 1);
573 .type
= JSON_VARIANT_ARRAY
,
577 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
578 JsonVariant
*w
= v
+ 1 + v
->n_elements
;
584 .type
= JSON_VARIANT_STRING
,
587 k
= strlen(l
[v
->n_elements
]);
589 if (k
> INLINE_STRING_MAX
) {
590 /* If string is too long, store it as reference. */
592 r
= json_variant_new_string(&w
->reference
, l
[v
->n_elements
]);
596 w
->is_reference
= true;
598 memcpy(w
->string
, l
[v
->n_elements
], k
+1);
605 int json_variant_new_object(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
606 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
608 assert_return(ret
, -EINVAL
);
610 *ret
= JSON_VARIANT_MAGIC_EMPTY_OBJECT
;
613 assert_return(array
, -EINVAL
);
614 assert_return(n
% 2 == 0, -EINVAL
);
616 v
= new(JsonVariant
, n
+ 1);
622 .type
= JSON_VARIANT_OBJECT
,
625 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
626 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
627 *c
= array
[v
->n_elements
];
630 if ((v
->n_elements
& 1) == 0 &&
631 !json_variant_is_string(c
))
632 return -EINVAL
; /* Every second one needs to be a string, as it is the key name */
634 d
= json_variant_depth(c
);
635 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
645 json_variant_set(w
, c
);
646 json_variant_copy_source(w
, c
);
653 static void json_variant_free_inner(JsonVariant
*v
) {
656 if (!json_variant_is_regular(v
))
659 json_source_unref(v
->source
);
661 if (v
->is_reference
) {
662 json_variant_unref(v
->reference
);
666 if (IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
)) {
669 for (i
= 0; i
< v
->n_elements
; i
++)
670 json_variant_free_inner(v
+ 1 + i
);
674 JsonVariant
*json_variant_ref(JsonVariant
*v
) {
677 if (!json_variant_is_regular(v
))
681 json_variant_ref(v
->parent
); /* ref the compounding variant instead */
683 assert(v
->n_ref
> 0);
690 JsonVariant
*json_variant_unref(JsonVariant
*v
) {
693 if (!json_variant_is_regular(v
))
697 json_variant_unref(v
->parent
);
699 assert(v
->n_ref
> 0);
703 json_variant_free_inner(v
);
711 void json_variant_unref_many(JsonVariant
**array
, size_t n
) {
714 assert(array
|| n
== 0);
716 for (i
= 0; i
< n
; i
++)
717 json_variant_unref(array
[i
]);
720 const char *json_variant_string(JsonVariant
*v
) {
723 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
725 if (json_variant_is_magic(v
))
727 if (json_variant_is_const_string(v
)) {
728 uintptr_t p
= (uintptr_t) v
;
730 assert((p
& 1) != 0);
731 return (const char*) (p
^ 1U);
735 return json_variant_string(v
->reference
);
736 if (v
->type
!= JSON_VARIANT_STRING
)
742 log_debug("Non-string JSON variant requested as string, returning NULL.");
746 bool json_variant_boolean(JsonVariant
*v
) {
749 if (v
== JSON_VARIANT_MAGIC_TRUE
)
751 if (v
== JSON_VARIANT_MAGIC_FALSE
)
753 if (!json_variant_is_regular(v
))
755 if (v
->type
!= JSON_VARIANT_BOOLEAN
)
758 return json_variant_boolean(v
->reference
);
760 return v
->value
.boolean
;
763 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
767 intmax_t json_variant_integer(JsonVariant
*v
) {
770 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
771 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
772 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
774 if (!json_variant_is_regular(v
))
777 return json_variant_integer(v
->reference
);
781 case JSON_VARIANT_INTEGER
:
782 return v
->value
.integer
;
784 case JSON_VARIANT_UNSIGNED
:
785 if (v
->value
.unsig
<= INTMAX_MAX
)
786 return (intmax_t) v
->value
.unsig
;
788 log_debug("Unsigned integer %ju requested as signed integer and out of range, returning 0.", v
->value
.unsig
);
791 case JSON_VARIANT_REAL
: {
794 converted
= (intmax_t) v
->value
.real
;
796 #pragma GCC diagnostic push
797 #pragma GCC diagnostic ignored "-Wfloat-equal"
798 if ((long double) converted
== v
->value
.real
)
799 #pragma GCC diagnostic pop
802 log_debug("Real %Lg requested as integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
811 log_debug("Non-integer JSON variant requested as integer, returning 0.");
815 uintmax_t json_variant_unsigned(JsonVariant
*v
) {
818 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
819 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
820 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
822 if (!json_variant_is_regular(v
))
825 return json_variant_integer(v
->reference
);
829 case JSON_VARIANT_INTEGER
:
830 if (v
->value
.integer
>= 0)
831 return (uintmax_t) v
->value
.integer
;
833 log_debug("Signed integer %ju requested as unsigned integer and out of range, returning 0.", v
->value
.integer
);
836 case JSON_VARIANT_UNSIGNED
:
837 return v
->value
.unsig
;
839 case JSON_VARIANT_REAL
: {
842 converted
= (uintmax_t) v
->value
.real
;
844 #pragma GCC diagnostic push
845 #pragma GCC diagnostic ignored "-Wfloat-equal"
846 if ((long double) converted
== v
->value
.real
)
847 #pragma GCC diagnostic pop
850 log_debug("Real %Lg requested as unsigned integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
859 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
863 long double json_variant_real(JsonVariant
*v
) {
866 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
867 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
868 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
870 if (!json_variant_is_regular(v
))
873 return json_variant_real(v
->reference
);
877 case JSON_VARIANT_REAL
:
878 return v
->value
.real
;
880 case JSON_VARIANT_INTEGER
: {
881 long double converted
;
883 converted
= (long double) v
->value
.integer
;
885 if ((intmax_t) converted
== v
->value
.integer
)
888 log_debug("Signed integer %ji requested as real, and cannot be converted losslessly, returning 0.", v
->value
.integer
);
892 case JSON_VARIANT_UNSIGNED
: {
893 long double converted
;
895 converted
= (long double) v
->value
.unsig
;
897 if ((uintmax_t) converted
== v
->value
.unsig
)
900 log_debug("Unsigned integer %ju requested as real, and cannot be converted losslessly, returning 0.", v
->value
.unsig
);
909 log_debug("Non-integer JSON variant requested as integer, returning 0.");
913 bool json_variant_is_negative(JsonVariant
*v
) {
916 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
917 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
918 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
920 if (!json_variant_is_regular(v
))
923 return json_variant_is_negative(v
->reference
);
925 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
926 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
931 case JSON_VARIANT_REAL
:
932 return v
->value
.real
< 0;
934 case JSON_VARIANT_INTEGER
:
935 return v
->value
.integer
< 0;
937 case JSON_VARIANT_UNSIGNED
:
945 log_debug("Non-integer JSON variant tested for negativity, returning false.");
949 JsonVariantType
json_variant_type(JsonVariant
*v
) {
952 return _JSON_VARIANT_TYPE_INVALID
;
954 if (json_variant_is_const_string(v
))
955 return JSON_VARIANT_STRING
;
957 if (v
== JSON_VARIANT_MAGIC_TRUE
|| v
== JSON_VARIANT_MAGIC_FALSE
)
958 return JSON_VARIANT_BOOLEAN
;
960 if (v
== JSON_VARIANT_MAGIC_NULL
)
961 return JSON_VARIANT_NULL
;
963 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
)
964 return JSON_VARIANT_INTEGER
;
966 if (v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
)
967 return JSON_VARIANT_UNSIGNED
;
969 if (v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
970 return JSON_VARIANT_REAL
;
972 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
973 return JSON_VARIANT_STRING
;
975 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
)
976 return JSON_VARIANT_ARRAY
;
978 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
979 return JSON_VARIANT_OBJECT
;
984 bool json_variant_has_type(JsonVariant
*v
, JsonVariantType type
) {
987 v
= json_variant_dereference(v
);
991 rt
= json_variant_type(v
);
995 /* If it's a const string, then it only can be a string, and if it is not, it's not */
996 if (json_variant_is_const_string(v
))
999 /* All three magic zeroes qualify as integer, unsigned and as real */
1000 if ((v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
|| v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
|| v
== JSON_VARIANT_MAGIC_ZERO_REAL
) &&
1001 IN_SET(type
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
, JSON_VARIANT_NUMBER
))
1004 /* All other magic variant types are only equal to themselves */
1005 if (json_variant_is_magic(v
))
1008 /* Handle the "number" pseudo type */
1009 if (type
== JSON_VARIANT_NUMBER
)
1010 return IN_SET(rt
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
);
1012 /* Integer conversions are OK in many cases */
1013 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_UNSIGNED
)
1014 return v
->value
.integer
>= 0;
1015 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_INTEGER
)
1016 return v
->value
.unsig
<= INTMAX_MAX
;
1018 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1019 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_REAL
)
1020 return (intmax_t) (long double) v
->value
.integer
== v
->value
.integer
;
1021 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_REAL
)
1022 return (uintmax_t) (long double) v
->value
.unsig
== v
->value
.unsig
;
1024 #pragma GCC diagnostic push
1025 #pragma GCC diagnostic ignored "-Wfloat-equal"
1026 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1027 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_INTEGER
)
1028 return (long double) (intmax_t) v
->value
.real
== v
->value
.real
;
1029 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_UNSIGNED
)
1030 return (long double) (uintmax_t) v
->value
.real
== v
->value
.real
;
1031 #pragma GCC diagnostic pop
1036 size_t json_variant_elements(JsonVariant
*v
) {
1039 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1040 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1042 if (!json_variant_is_regular(v
))
1044 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1046 if (v
->is_reference
)
1047 return json_variant_elements(v
->reference
);
1049 return v
->n_elements
;
1052 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1056 JsonVariant
*json_variant_by_index(JsonVariant
*v
, size_t idx
) {
1059 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1060 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1062 if (!json_variant_is_regular(v
))
1064 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1066 if (v
->is_reference
)
1067 return json_variant_by_index(v
->reference
, idx
);
1068 if (idx
>= v
->n_elements
)
1071 return json_variant_conservative_normalize(v
+ 1 + idx
);
1074 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1078 JsonVariant
*json_variant_by_key_full(JsonVariant
*v
, const char *key
, JsonVariant
**ret_key
) {
1085 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1087 if (!json_variant_is_regular(v
))
1089 if (v
->type
!= JSON_VARIANT_OBJECT
)
1091 if (v
->is_reference
)
1092 return json_variant_by_key(v
->reference
, key
);
1094 for (i
= 0; i
< v
->n_elements
; i
+= 2) {
1097 p
= json_variant_dereference(v
+ 1 + i
);
1099 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1102 if (streq(json_variant_string(p
), key
)) {
1105 *ret_key
= json_variant_conservative_normalize(v
+ 1 + i
);
1107 return json_variant_conservative_normalize(v
+ 1 + i
+ 1);
1118 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1125 JsonVariant
*json_variant_by_key(JsonVariant
*v
, const char *key
) {
1126 return json_variant_by_key_full(v
, key
, NULL
);
1129 bool json_variant_equal(JsonVariant
*a
, JsonVariant
*b
) {
1132 a
= json_variant_normalize(a
);
1133 b
= json_variant_normalize(b
);
1138 t
= json_variant_type(a
);
1139 if (!json_variant_has_type(b
, t
))
1144 case JSON_VARIANT_STRING
:
1145 return streq(json_variant_string(a
), json_variant_string(b
));
1147 case JSON_VARIANT_INTEGER
:
1148 return json_variant_integer(a
) == json_variant_integer(b
);
1150 case JSON_VARIANT_UNSIGNED
:
1151 return json_variant_unsigned(a
) == json_variant_unsigned(b
);
1153 case JSON_VARIANT_REAL
:
1154 #pragma GCC diagnostic push
1155 #pragma GCC diagnostic ignored "-Wfloat-equal"
1156 return json_variant_real(a
) == json_variant_real(b
);
1157 #pragma GCC diagnostic pop
1159 case JSON_VARIANT_BOOLEAN
:
1160 return json_variant_boolean(a
) == json_variant_boolean(b
);
1162 case JSON_VARIANT_NULL
:
1165 case JSON_VARIANT_ARRAY
: {
1168 n
= json_variant_elements(a
);
1169 if (n
!= json_variant_elements(b
))
1172 for (i
= 0; i
< n
; i
++) {
1173 if (!json_variant_equal(json_variant_by_index(a
, i
), json_variant_by_index(b
, i
)))
1180 case JSON_VARIANT_OBJECT
: {
1183 n
= json_variant_elements(a
);
1184 if (n
!= json_variant_elements(b
))
1187 /* Iterate through all keys in 'a' */
1188 for (i
= 0; i
< n
; i
+= 2) {
1192 /* Match them against all keys in 'b' */
1193 for (j
= 0; j
< n
; j
+= 2) {
1196 key_b
= json_variant_by_index(b
, j
);
1198 /* During the first iteration unmark everything */
1200 key_b
->is_marked
= false;
1201 else if (key_b
->is_marked
) /* In later iterations if we already marked something, don't bother with it again */
1207 if (json_variant_equal(json_variant_by_index(a
, i
), key_b
) &&
1208 json_variant_equal(json_variant_by_index(a
, i
+1), json_variant_by_index(b
, j
+1))) {
1209 /* Key and values match! */
1210 key_b
->is_marked
= found
= true;
1212 /* In the first iteration we continue the inner loop since we want to mark
1213 * everything, otherwise exit the loop quickly after we found what we were
1228 assert_not_reached("Unknown variant type.");
1232 int json_variant_get_source(JsonVariant
*v
, const char **ret_source
, unsigned *ret_line
, unsigned *ret_column
) {
1233 assert_return(v
, -EINVAL
);
1236 *ret_source
= json_variant_is_regular(v
) && v
->source
? v
->source
->name
: NULL
;
1239 *ret_line
= json_variant_is_regular(v
) ? v
->line
: 0;
1242 *ret_column
= json_variant_is_regular(v
) ? v
->column
: 0;
1247 static int print_source(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, bool whitespace
) {
1250 if (!FLAGS_SET(flags
, JSON_FORMAT_SOURCE
|JSON_FORMAT_PRETTY
))
1253 if (!json_variant_is_regular(v
))
1256 if (!v
->source
&& v
->line
== 0 && v
->column
== 0)
1259 /* The max width we need to format the line numbers for this source file */
1260 w
= (v
->source
&& v
->source
->max_line
> 0) ?
1261 DECIMAL_STR_WIDTH(v
->source
->max_line
) :
1262 DECIMAL_STR_MAX(unsigned)-1;
1263 k
= (v
->source
&& v
->source
->max_column
> 0) ?
1264 DECIMAL_STR_WIDTH(v
->source
->max_column
) :
1265 DECIMAL_STR_MAX(unsigned) -1;
1270 n
= 1 + (v
->source
? strlen(v
->source
->name
) : 0) +
1271 ((v
->source
&& (v
->line
> 0 || v
->column
> 0)) ? 1 : 0) +
1272 (v
->line
> 0 ? w
: 0) +
1273 (((v
->source
|| v
->line
> 0) && v
->column
> 0) ? 1 : 0) +
1274 (v
->column
> 0 ? k
: 0) +
1277 for (i
= 0; i
< n
; i
++)
1283 fputs(v
->source
->name
, f
);
1284 if (v
->source
&& (v
->line
> 0 || v
->column
> 0))
1287 fprintf(f
, "%*u", (int) w
, v
->line
);
1288 if ((v
->source
|| v
->line
> 0) || v
->column
> 0)
1291 fprintf(f
, "%*u", (int) k
, v
->column
);
1300 static int json_format(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, const char *prefix
) {
1306 switch (json_variant_type(v
)) {
1308 case JSON_VARIANT_REAL
: {
1311 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
1312 if (loc
== (locale_t
) 0)
1315 if (flags
& JSON_FORMAT_COLOR
)
1316 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1318 fprintf(f
, "%.*Le", DECIMAL_DIG
, json_variant_real(v
));
1320 if (flags
& JSON_FORMAT_COLOR
)
1321 fputs(ANSI_NORMAL
, f
);
1327 case JSON_VARIANT_INTEGER
:
1328 if (flags
& JSON_FORMAT_COLOR
)
1329 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1331 fprintf(f
, "%" PRIdMAX
, json_variant_integer(v
));
1333 if (flags
& JSON_FORMAT_COLOR
)
1334 fputs(ANSI_NORMAL
, f
);
1337 case JSON_VARIANT_UNSIGNED
:
1338 if (flags
& JSON_FORMAT_COLOR
)
1339 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1341 fprintf(f
, "%" PRIuMAX
, json_variant_unsigned(v
));
1343 if (flags
& JSON_FORMAT_COLOR
)
1344 fputs(ANSI_NORMAL
, f
);
1347 case JSON_VARIANT_BOOLEAN
:
1349 if (flags
& JSON_FORMAT_COLOR
)
1350 fputs(ANSI_HIGHLIGHT
, f
);
1352 if (json_variant_boolean(v
))
1357 if (flags
& JSON_FORMAT_COLOR
)
1358 fputs(ANSI_NORMAL
, f
);
1362 case JSON_VARIANT_NULL
:
1363 if (flags
& JSON_FORMAT_COLOR
)
1364 fputs(ANSI_HIGHLIGHT
, f
);
1368 if (flags
& JSON_FORMAT_COLOR
)
1369 fputs(ANSI_NORMAL
, f
);
1372 case JSON_VARIANT_STRING
: {
1377 if (flags
& JSON_FORMAT_COLOR
)
1378 fputs(ANSI_GREEN
, f
);
1380 for (q
= json_variant_string(v
); *q
; q
++) {
1413 if ((signed char) *q
>= 0 && *q
< ' ')
1414 fprintf(f
, "\\u%04x", *q
);
1421 if (flags
& JSON_FORMAT_COLOR
)
1422 fputs(ANSI_NORMAL
, f
);
1428 case JSON_VARIANT_ARRAY
: {
1431 n
= json_variant_elements(v
);
1436 _cleanup_free_
char *joined
= NULL
;
1437 const char *prefix2
;
1439 if (flags
& JSON_FORMAT_PRETTY
) {
1440 joined
= strjoin(strempty(prefix
), "\t");
1447 prefix2
= strempty(prefix
);
1451 for (i
= 0; i
< n
; i
++) {
1454 assert_se(e
= json_variant_by_index(v
, i
));
1457 if (flags
& JSON_FORMAT_PRETTY
)
1463 if (flags
& JSON_FORMAT_PRETTY
) {
1464 print_source(f
, e
, flags
, false);
1468 r
= json_format(f
, e
, flags
, prefix2
);
1473 if (flags
& JSON_FORMAT_PRETTY
) {
1475 print_source(f
, v
, flags
, true);
1476 fputs(strempty(prefix
), f
);
1484 case JSON_VARIANT_OBJECT
: {
1487 n
= json_variant_elements(v
);
1492 _cleanup_free_
char *joined
= NULL
;
1493 const char *prefix2
;
1495 if (flags
& JSON_FORMAT_PRETTY
) {
1496 joined
= strjoin(strempty(prefix
), "\t");
1503 prefix2
= strempty(prefix
);
1507 for (i
= 0; i
< n
; i
+= 2) {
1510 e
= json_variant_by_index(v
, i
);
1513 if (flags
& JSON_FORMAT_PRETTY
)
1519 if (flags
& JSON_FORMAT_PRETTY
) {
1520 print_source(f
, e
, flags
, false);
1524 r
= json_format(f
, e
, flags
, prefix2
);
1528 fputs(flags
& JSON_FORMAT_PRETTY
? " : " : ":", f
);
1530 r
= json_format(f
, json_variant_by_index(v
, i
+1), flags
, prefix2
);
1535 if (flags
& JSON_FORMAT_PRETTY
) {
1537 print_source(f
, v
, flags
, true);
1538 fputs(strempty(prefix
), f
);
1547 assert_not_reached("Unexpected variant type.");
1553 int json_variant_format(JsonVariant
*v
, JsonFormatFlags flags
, char **ret
) {
1554 _cleanup_free_
char *s
= NULL
;
1558 assert_return(v
, -EINVAL
);
1559 assert_return(ret
, -EINVAL
);
1562 _cleanup_fclose_
FILE *f
= NULL
;
1564 f
= open_memstream_unlocked(&s
, &sz
);
1568 json_variant_dump(v
, flags
, f
, NULL
);
1570 r
= fflush_and_check(f
);
1581 void json_variant_dump(JsonVariant
*v
, JsonFormatFlags flags
, FILE *f
, const char *prefix
) {
1588 print_source(f
, v
, flags
, false);
1590 if (((flags
& (JSON_FORMAT_COLOR_AUTO
|JSON_FORMAT_COLOR
)) == JSON_FORMAT_COLOR_AUTO
) && colors_enabled())
1591 flags
|= JSON_FORMAT_COLOR
;
1593 if (flags
& JSON_FORMAT_SSE
)
1595 if (flags
& JSON_FORMAT_SEQ
)
1596 fputc('\x1e', f
); /* ASCII Record Separator */
1598 json_format(f
, v
, flags
, prefix
);
1600 if (flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_SEQ
|JSON_FORMAT_SSE
|JSON_FORMAT_NEWLINE
))
1602 if (flags
& JSON_FORMAT_SSE
)
1603 fputc('\n', f
); /* In case of SSE add a second newline */
1606 static int json_variant_copy(JsonVariant
**nv
, JsonVariant
*v
) {
1616 /* Let's copy the simple types literally, and the larger types by references */
1617 t
= json_variant_type(v
);
1619 case JSON_VARIANT_INTEGER
:
1620 k
= sizeof(intmax_t);
1621 value
.integer
= json_variant_integer(v
);
1625 case JSON_VARIANT_UNSIGNED
:
1626 k
= sizeof(uintmax_t);
1627 value
.unsig
= json_variant_unsigned(v
);
1631 case JSON_VARIANT_REAL
:
1632 k
= sizeof(long double);
1633 value
.real
= json_variant_real(v
);
1637 case JSON_VARIANT_BOOLEAN
:
1639 value
.boolean
= json_variant_boolean(v
);
1643 case JSON_VARIANT_NULL
:
1648 case JSON_VARIANT_STRING
:
1649 source
= json_variant_string(v
);
1650 k
= strnlen(source
, INLINE_STRING_MAX
+ 1);
1651 if (k
<= INLINE_STRING_MAX
) {
1659 /* Everything else copy by reference */
1661 c
= malloc0(offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*));
1667 c
->is_reference
= true;
1668 c
->reference
= json_variant_ref(json_variant_normalize(v
));
1674 c
= malloc0(offsetof(JsonVariant
, value
) + k
);
1681 memcpy_safe(&c
->value
, source
, k
);
1687 static bool json_single_ref(JsonVariant
*v
) {
1689 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
1691 if (!json_variant_is_regular(v
))
1695 return json_single_ref(v
->parent
);
1697 assert(v
->n_ref
> 0);
1698 return v
->n_ref
== 1;
1701 static int json_variant_set_source(JsonVariant
**v
, JsonSource
*source
, unsigned line
, unsigned column
) {
1707 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole referencer of
1708 * the object. If not, allocates a new object, possibly a surrogate for the original one */
1713 if (source
&& line
> source
->max_line
)
1714 source
->max_line
= line
;
1715 if (source
&& column
> source
->max_column
)
1716 source
->max_column
= column
;
1718 if (!json_variant_is_regular(*v
)) {
1720 if (!source
&& line
== 0 && column
== 0)
1724 if (json_source_equal((*v
)->source
, source
) &&
1725 (*v
)->line
== line
&&
1726 (*v
)->column
== column
)
1729 if (json_single_ref(*v
)) { /* Sole reference? */
1730 json_source_unref((*v
)->source
);
1731 (*v
)->source
= json_source_ref(source
);
1733 (*v
)->column
= column
;
1738 r
= json_variant_copy(&w
, *v
);
1742 assert(json_variant_is_regular(w
));
1743 assert(!w
->is_embedded
);
1744 assert(w
->n_ref
== 1);
1747 w
->source
= json_source_ref(source
);
1751 json_variant_unref(*v
);
1757 static void inc_lines_columns(unsigned *line
, unsigned *column
, const char *s
, size_t n
) {
1760 assert(s
|| n
== 0);
1766 } else if ((signed char) *s
>= 0 && *s
< 127) /* Process ASCII chars quickly */
1771 w
= utf8_encoded_valid_unichar(s
, n
);
1772 if (w
< 0) /* count invalid unichars as normal characters */
1774 else if ((size_t) w
> n
) /* never read more than the specified number of characters */
1789 static int unhex_ucs2(const char *c
, uint16_t *ret
) {
1796 aa
= unhexchar(c
[0]);
1800 bb
= unhexchar(c
[1]);
1804 cc
= unhexchar(c
[2]);
1808 dd
= unhexchar(c
[3]);
1812 x
= ((uint16_t) aa
<< 12) |
1813 ((uint16_t) bb
<< 8) |
1814 ((uint16_t) cc
<< 4) |
1825 static int json_parse_string(const char **p
, char **ret
) {
1826 _cleanup_free_
char *s
= NULL
;
1827 size_t n
= 0, allocated
= 0;
1848 /* Check for control characters 0x00..0x1f */
1849 if (*c
> 0 && *c
< ' ')
1852 /* Check for control character 0x7f */
1867 return JSON_TOKEN_STRING
;
1877 if (IN_SET(*c
, '"', '\\', '/'))
1889 else if (*c
== 'u') {
1893 r
= unhex_ucs2(c
+ 1, &x
);
1899 if (!GREEDY_REALLOC(s
, allocated
, n
+ 5))
1902 if (!utf16_is_surrogate(x
))
1903 n
+= utf8_encode_unichar(s
+ n
, (char32_t
) x
);
1904 else if (utf16_is_trailing_surrogate(x
))
1909 if (c
[0] != '\\' || c
[1] != 'u')
1912 r
= unhex_ucs2(c
+ 2, &y
);
1918 if (!utf16_is_trailing_surrogate(y
))
1921 n
+= utf8_encode_unichar(s
+ n
, utf16_surrogate_pair_to_unichar(x
, y
));
1928 if (!GREEDY_REALLOC(s
, allocated
, n
+ 2))
1936 len
= utf8_encoded_valid_unichar(c
, (size_t) -1);
1940 if (!GREEDY_REALLOC(s
, allocated
, n
+ len
+ 1))
1943 memcpy(s
+ n
, c
, len
);
1949 static int json_parse_number(const char **p
, JsonValue
*ret
) {
1950 bool negative
= false, exponent_negative
= false, is_real
= false;
1951 long double x
= 0.0, y
= 0.0, exponent
= 0.0, shift
= 1.0;
1970 if (!strchr("123456789", *c
) || *c
== 0)
1977 if (i
< INTMAX_MIN
/ 10) /* overflow */
1980 intmax_t t
= 10 * i
;
1982 if (t
< INTMAX_MIN
+ (*c
- '0')) /* overflow */
1988 if (u
> UINTMAX_MAX
/ 10) /* overflow */
1991 uintmax_t t
= 10 * u
;
1993 if (t
> UINTMAX_MAX
- (*c
- '0')) /* overflow */
2001 x
= 10.0 * x
+ (*c
- '0');
2004 } while (strchr("0123456789", *c
) && *c
!= 0);
2011 if (!strchr("0123456789", *c
) || *c
== 0)
2015 y
= 10.0 * y
+ (*c
- '0');
2016 shift
= 10.0 * shift
;
2018 } while (strchr("0123456789", *c
) && *c
!= 0);
2021 if (IN_SET(*c
, 'e', 'E')) {
2026 exponent_negative
= true;
2028 } else if (*c
== '+')
2031 if (!strchr("0123456789", *c
) || *c
== 0)
2035 exponent
= 10.0 * exponent
+ (*c
- '0');
2037 } while (strchr("0123456789", *c
) && *c
!= 0);
2043 ret
->real
= ((negative
? -1.0 : 1.0) * (x
+ (y
/ shift
))) * exp10l((exponent_negative
? -1.0 : 1.0) * exponent
);
2044 return JSON_TOKEN_REAL
;
2045 } else if (negative
) {
2047 return JSON_TOKEN_INTEGER
;
2050 return JSON_TOKEN_UNSIGNED
;
2057 JsonValue
*ret_value
,
2058 unsigned *ret_line
, /* 'ret_line' returns the line at the beginning of this token */
2059 unsigned *ret_column
,
2061 unsigned *line
, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2064 unsigned start_line
, start_column
;
2065 const char *start
, *c
;
2085 t
= PTR_TO_INT(*state
);
2086 if (t
== STATE_NULL
) {
2092 /* Skip over the whitespace */
2093 n
= strspn(*p
, WHITESPACE
);
2094 inc_lines_columns(line
, column
, *p
, n
);
2097 /* Remember where we started processing this token */
2100 start_column
= *column
;
2104 *ret_value
= JSON_VALUE_NULL
;
2115 *state
= INT_TO_PTR(STATE_VALUE
);
2116 r
= JSON_TOKEN_OBJECT_OPEN
;
2119 } else if (*c
== '}') {
2121 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2122 r
= JSON_TOKEN_OBJECT_CLOSE
;
2125 } else if (*c
== '[') {
2127 *state
= INT_TO_PTR(STATE_VALUE
);
2128 r
= JSON_TOKEN_ARRAY_OPEN
;
2131 } else if (*c
== ']') {
2133 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2134 r
= JSON_TOKEN_ARRAY_CLOSE
;
2137 } else if (*c
== '"') {
2139 r
= json_parse_string(&c
, ret_string
);
2143 *ret_value
= JSON_VALUE_NULL
;
2144 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2147 } else if (strchr("-0123456789", *c
)) {
2149 r
= json_parse_number(&c
, ret_value
);
2154 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2157 } else if (startswith(c
, "true")) {
2159 ret_value
->boolean
= true;
2161 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2162 r
= JSON_TOKEN_BOOLEAN
;
2165 } else if (startswith(c
, "false")) {
2167 ret_value
->boolean
= false;
2169 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2170 r
= JSON_TOKEN_BOOLEAN
;
2173 } else if (startswith(c
, "null")) {
2175 *ret_value
= JSON_VALUE_NULL
;
2177 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2178 r
= JSON_TOKEN_NULL
;
2185 case STATE_VALUE_POST
:
2189 *state
= INT_TO_PTR(STATE_VALUE
);
2190 r
= JSON_TOKEN_COLON
;
2193 } else if (*c
== ',') {
2195 *state
= INT_TO_PTR(STATE_VALUE
);
2196 r
= JSON_TOKEN_COMMA
;
2199 } else if (*c
== '}') {
2201 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2202 r
= JSON_TOKEN_OBJECT_CLOSE
;
2205 } else if (*c
== ']') {
2207 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2208 r
= JSON_TOKEN_ARRAY_CLOSE
;
2215 assert_not_reached("Unexpected tokenizer state");
2220 *ret_value
= JSON_VALUE_NULL
;
2223 inc_lines_columns(line
, column
, start
, c
- start
);
2226 *ret_line
= start_line
;
2227 *ret_column
= start_column
;
2232 typedef enum JsonExpect
{
2233 /* The following values are used by json_parse() */
2236 EXPECT_OBJECT_FIRST_KEY
,
2237 EXPECT_OBJECT_NEXT_KEY
,
2238 EXPECT_OBJECT_COLON
,
2239 EXPECT_OBJECT_VALUE
,
2240 EXPECT_OBJECT_COMMA
,
2241 EXPECT_ARRAY_FIRST_ELEMENT
,
2242 EXPECT_ARRAY_NEXT_ELEMENT
,
2245 /* And these are used by json_build() */
2246 EXPECT_ARRAY_ELEMENT
,
2250 typedef struct JsonStack
{
2252 JsonVariant
**elements
;
2253 size_t n_elements
, n_elements_allocated
;
2254 unsigned line_before
;
2255 unsigned column_before
;
2256 size_t n_suppress
; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2259 static void json_stack_release(JsonStack
*s
) {
2262 json_variant_unref_many(s
->elements
, s
->n_elements
);
2263 s
->elements
= mfree(s
->elements
);
2266 static int json_parse_internal(
2272 bool continue_end
) {
2274 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2275 unsigned line_buffer
= 0, column_buffer
= 0;
2276 void *tokenizer_state
= NULL
;
2277 JsonStack
*stack
= NULL
;
2281 assert_return(input
, -EINVAL
);
2282 assert_return(ret
, -EINVAL
);
2286 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2289 stack
[0] = (JsonStack
) {
2290 .expect
= EXPECT_TOPLEVEL
,
2294 line
= &line_buffer
;
2296 column
= &column_buffer
;
2299 _cleanup_free_
char *string
= NULL
;
2300 unsigned line_token
, column_token
;
2301 JsonVariant
*add
= NULL
;
2306 assert(n_stack
> 0);
2307 current
= stack
+ n_stack
- 1;
2309 if (continue_end
&& current
->expect
== EXPECT_END
)
2312 token
= json_tokenize(&p
, &string
, &value
, &line_token
, &column_token
, &tokenizer_state
, line
, column
);
2320 case JSON_TOKEN_END
:
2321 if (current
->expect
!= EXPECT_END
) {
2326 assert(current
->n_elements
== 1);
2327 assert(n_stack
== 1);
2330 case JSON_TOKEN_COLON
:
2332 if (current
->expect
!= EXPECT_OBJECT_COLON
) {
2337 current
->expect
= EXPECT_OBJECT_VALUE
;
2340 case JSON_TOKEN_COMMA
:
2342 if (current
->expect
== EXPECT_OBJECT_COMMA
)
2343 current
->expect
= EXPECT_OBJECT_NEXT_KEY
;
2344 else if (current
->expect
== EXPECT_ARRAY_COMMA
)
2345 current
->expect
= EXPECT_ARRAY_NEXT_ELEMENT
;
2353 case JSON_TOKEN_OBJECT_OPEN
:
2355 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2360 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2364 current
= stack
+ n_stack
- 1;
2366 /* Prepare the expect for when we return from the child */
2367 if (current
->expect
== EXPECT_TOPLEVEL
)
2368 current
->expect
= EXPECT_END
;
2369 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2370 current
->expect
= EXPECT_OBJECT_COMMA
;
2372 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2373 current
->expect
= EXPECT_ARRAY_COMMA
;
2376 stack
[n_stack
++] = (JsonStack
) {
2377 .expect
= EXPECT_OBJECT_FIRST_KEY
,
2378 .line_before
= line_token
,
2379 .column_before
= column_token
,
2382 current
= stack
+ n_stack
- 1;
2385 case JSON_TOKEN_OBJECT_CLOSE
:
2386 if (!IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_COMMA
)) {
2391 assert(n_stack
> 1);
2393 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
2397 line_token
= current
->line_before
;
2398 column_token
= current
->column_before
;
2400 json_stack_release(current
);
2401 n_stack
--, current
--;
2405 case JSON_TOKEN_ARRAY_OPEN
:
2406 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2411 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2415 current
= stack
+ n_stack
- 1;
2417 /* Prepare the expect for when we return from the child */
2418 if (current
->expect
== EXPECT_TOPLEVEL
)
2419 current
->expect
= EXPECT_END
;
2420 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2421 current
->expect
= EXPECT_OBJECT_COMMA
;
2423 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2424 current
->expect
= EXPECT_ARRAY_COMMA
;
2427 stack
[n_stack
++] = (JsonStack
) {
2428 .expect
= EXPECT_ARRAY_FIRST_ELEMENT
,
2429 .line_before
= line_token
,
2430 .column_before
= column_token
,
2435 case JSON_TOKEN_ARRAY_CLOSE
:
2436 if (!IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_COMMA
)) {
2441 assert(n_stack
> 1);
2443 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2447 line_token
= current
->line_before
;
2448 column_token
= current
->column_before
;
2450 json_stack_release(current
);
2451 n_stack
--, current
--;
2454 case JSON_TOKEN_STRING
:
2455 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
)) {
2460 r
= json_variant_new_string(&add
, string
);
2464 if (current
->expect
== EXPECT_TOPLEVEL
)
2465 current
->expect
= EXPECT_END
;
2466 else if (IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_NEXT_KEY
))
2467 current
->expect
= EXPECT_OBJECT_COLON
;
2468 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2469 current
->expect
= EXPECT_OBJECT_COMMA
;
2471 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2472 current
->expect
= EXPECT_ARRAY_COMMA
;
2477 case JSON_TOKEN_REAL
:
2478 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2483 r
= json_variant_new_real(&add
, value
.real
);
2487 if (current
->expect
== EXPECT_TOPLEVEL
)
2488 current
->expect
= EXPECT_END
;
2489 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2490 current
->expect
= EXPECT_OBJECT_COMMA
;
2492 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2493 current
->expect
= EXPECT_ARRAY_COMMA
;
2498 case JSON_TOKEN_INTEGER
:
2499 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2504 r
= json_variant_new_integer(&add
, value
.integer
);
2508 if (current
->expect
== EXPECT_TOPLEVEL
)
2509 current
->expect
= EXPECT_END
;
2510 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2511 current
->expect
= EXPECT_OBJECT_COMMA
;
2513 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2514 current
->expect
= EXPECT_ARRAY_COMMA
;
2519 case JSON_TOKEN_UNSIGNED
:
2520 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2525 r
= json_variant_new_unsigned(&add
, value
.unsig
);
2529 if (current
->expect
== EXPECT_TOPLEVEL
)
2530 current
->expect
= EXPECT_END
;
2531 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2532 current
->expect
= EXPECT_OBJECT_COMMA
;
2534 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2535 current
->expect
= EXPECT_ARRAY_COMMA
;
2540 case JSON_TOKEN_BOOLEAN
:
2541 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2546 r
= json_variant_new_boolean(&add
, value
.boolean
);
2550 if (current
->expect
== EXPECT_TOPLEVEL
)
2551 current
->expect
= EXPECT_END
;
2552 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2553 current
->expect
= EXPECT_OBJECT_COMMA
;
2555 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2556 current
->expect
= EXPECT_ARRAY_COMMA
;
2561 case JSON_TOKEN_NULL
:
2562 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2567 r
= json_variant_new_null(&add
);
2571 if (current
->expect
== EXPECT_TOPLEVEL
)
2572 current
->expect
= EXPECT_END
;
2573 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2574 current
->expect
= EXPECT_OBJECT_COMMA
;
2576 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2577 current
->expect
= EXPECT_ARRAY_COMMA
;
2583 assert_not_reached("Unexpected token");
2587 (void) json_variant_set_source(&add
, source
, line_token
, column_token
);
2589 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
2594 current
->elements
[current
->n_elements
++] = add
;
2599 assert(n_stack
== 1);
2600 assert(stack
[0].n_elements
== 1);
2602 *ret
= json_variant_ref(stack
[0].elements
[0]);
2607 for (i
= 0; i
< n_stack
; i
++)
2608 json_stack_release(stack
+ i
);
2615 int json_parse(const char *input
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2616 return json_parse_internal(&input
, NULL
, ret
, ret_line
, ret_column
, false);
2619 int json_parse_continue(const char **p
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2620 return json_parse_internal(p
, NULL
, ret
, ret_line
, ret_column
, true);
2623 int json_parse_file(FILE *f
, const char *path
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
2624 _cleanup_(json_source_unrefp
) JsonSource
*source
= NULL
;
2625 _cleanup_free_
char *text
= NULL
;
2630 r
= read_full_stream(f
, &text
, NULL
);
2632 r
= read_full_file(path
, &text
, NULL
);
2639 source
= json_source_new(path
);
2645 return json_parse_internal(&p
, source
, ret
, ret_line
, ret_column
, false);
2648 int json_buildv(JsonVariant
**ret
, va_list ap
) {
2649 JsonStack
*stack
= NULL
;
2650 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2653 assert_return(ret
, -EINVAL
);
2655 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2658 stack
[0] = (JsonStack
) {
2659 .expect
= EXPECT_TOPLEVEL
,
2663 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
2664 size_t n_subtract
= 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
2665 * have been added to the current variant */
2669 assert(n_stack
> 0);
2670 current
= stack
+ n_stack
- 1;
2672 if (current
->expect
== EXPECT_END
)
2675 command
= va_arg(ap
, int);
2679 case _JSON_BUILD_STRING
: {
2682 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2687 p
= va_arg(ap
, const char *);
2689 if (current
->n_suppress
== 0) {
2690 r
= json_variant_new_string(&add
, p
);
2697 if (current
->expect
== EXPECT_TOPLEVEL
)
2698 current
->expect
= EXPECT_END
;
2699 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2700 current
->expect
= EXPECT_OBJECT_KEY
;
2702 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2707 case _JSON_BUILD_INTEGER
: {
2710 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2715 j
= va_arg(ap
, intmax_t);
2717 if (current
->n_suppress
== 0) {
2718 r
= json_variant_new_integer(&add
, j
);
2725 if (current
->expect
== EXPECT_TOPLEVEL
)
2726 current
->expect
= EXPECT_END
;
2727 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2728 current
->expect
= EXPECT_OBJECT_KEY
;
2730 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2735 case _JSON_BUILD_UNSIGNED
: {
2738 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2743 j
= va_arg(ap
, uintmax_t);
2745 if (current
->n_suppress
== 0) {
2746 r
= json_variant_new_unsigned(&add
, j
);
2753 if (current
->expect
== EXPECT_TOPLEVEL
)
2754 current
->expect
= EXPECT_END
;
2755 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2756 current
->expect
= EXPECT_OBJECT_KEY
;
2758 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2763 case _JSON_BUILD_REAL
: {
2766 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2771 d
= va_arg(ap
, long double);
2773 if (current
->n_suppress
== 0) {
2774 r
= json_variant_new_real(&add
, d
);
2781 if (current
->expect
== EXPECT_TOPLEVEL
)
2782 current
->expect
= EXPECT_END
;
2783 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2784 current
->expect
= EXPECT_OBJECT_KEY
;
2786 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2791 case _JSON_BUILD_BOOLEAN
: {
2794 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2799 b
= va_arg(ap
, int);
2801 if (current
->n_suppress
== 0) {
2802 r
= json_variant_new_boolean(&add
, b
);
2809 if (current
->expect
== EXPECT_TOPLEVEL
)
2810 current
->expect
= EXPECT_END
;
2811 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2812 current
->expect
= EXPECT_OBJECT_KEY
;
2814 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2819 case _JSON_BUILD_NULL
:
2821 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2826 if (current
->n_suppress
== 0) {
2827 r
= json_variant_new_null(&add
);
2834 if (current
->expect
== EXPECT_TOPLEVEL
)
2835 current
->expect
= EXPECT_END
;
2836 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2837 current
->expect
= EXPECT_OBJECT_KEY
;
2839 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2843 case _JSON_BUILD_VARIANT
:
2845 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2850 /* Note that we don't care for current->n_suppress here, after all the variant is already
2851 * allocated anyway... */
2852 add
= va_arg(ap
, JsonVariant
*);
2854 add
= JSON_VARIANT_MAGIC_NULL
;
2856 json_variant_ref(add
);
2860 if (current
->expect
== EXPECT_TOPLEVEL
)
2861 current
->expect
= EXPECT_END
;
2862 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2863 current
->expect
= EXPECT_OBJECT_KEY
;
2865 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2869 case _JSON_BUILD_LITERAL
: {
2872 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2877 l
= va_arg(ap
, const char *);
2880 /* Note that we don't care for current->n_suppress here, we should generate parsing
2881 * errors even in suppressed object properties */
2883 r
= json_parse(l
, &add
, NULL
, NULL
);
2887 add
= JSON_VARIANT_MAGIC_NULL
;
2891 if (current
->expect
== EXPECT_TOPLEVEL
)
2892 current
->expect
= EXPECT_END
;
2893 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2894 current
->expect
= EXPECT_OBJECT_KEY
;
2896 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2901 case _JSON_BUILD_ARRAY_BEGIN
:
2903 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2908 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2912 current
= stack
+ n_stack
- 1;
2914 if (current
->expect
== EXPECT_TOPLEVEL
)
2915 current
->expect
= EXPECT_END
;
2916 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2917 current
->expect
= EXPECT_OBJECT_KEY
;
2919 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2921 stack
[n_stack
++] = (JsonStack
) {
2922 .expect
= EXPECT_ARRAY_ELEMENT
,
2923 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
2924 * new array, then we should
2925 * also suppress all array
2931 case _JSON_BUILD_ARRAY_END
:
2932 if (current
->expect
!= EXPECT_ARRAY_ELEMENT
) {
2937 assert(n_stack
> 1);
2939 if (current
->n_suppress
== 0) {
2940 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2947 json_stack_release(current
);
2948 n_stack
--, current
--;
2952 case _JSON_BUILD_STRV
: {
2955 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2960 l
= va_arg(ap
, char **);
2962 if (current
->n_suppress
== 0) {
2963 r
= json_variant_new_array_strv(&add
, l
);
2970 if (current
->expect
== EXPECT_TOPLEVEL
)
2971 current
->expect
= EXPECT_END
;
2972 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2973 current
->expect
= EXPECT_OBJECT_KEY
;
2975 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
2980 case _JSON_BUILD_OBJECT_BEGIN
:
2982 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
2987 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2991 current
= stack
+ n_stack
- 1;
2993 if (current
->expect
== EXPECT_TOPLEVEL
)
2994 current
->expect
= EXPECT_END
;
2995 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2996 current
->expect
= EXPECT_OBJECT_KEY
;
2998 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3000 stack
[n_stack
++] = (JsonStack
) {
3001 .expect
= EXPECT_OBJECT_KEY
,
3002 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3003 * new object, then we should
3004 * also suppress all object
3010 case _JSON_BUILD_OBJECT_END
:
3012 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3017 assert(n_stack
> 1);
3019 if (current
->n_suppress
== 0) {
3020 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
3027 json_stack_release(current
);
3028 n_stack
--, current
--;
3032 case _JSON_BUILD_PAIR
: {
3035 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3040 n
= va_arg(ap
, const char *);
3042 if (current
->n_suppress
== 0) {
3043 r
= json_variant_new_string(&add
, n
);
3050 current
->expect
= EXPECT_OBJECT_VALUE
;
3054 case _JSON_BUILD_PAIR_CONDITION
: {
3058 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3063 b
= va_arg(ap
, int);
3064 n
= va_arg(ap
, const char *);
3066 if (b
&& current
->n_suppress
== 0) {
3067 r
= json_variant_new_string(&add
, n
);
3072 n_subtract
= 1; /* we generated one item */
3074 if (!b
&& current
->n_suppress
!= (size_t) -1)
3075 current
->n_suppress
+= 2; /* Suppress this one and the next item */
3077 current
->expect
= EXPECT_OBJECT_VALUE
;
3081 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3082 if (add
&& current
->n_suppress
== 0) {
3083 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3088 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3091 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3092 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3093 * on this stack level */
3094 if (current
->n_suppress
!= (size_t) -1) {
3095 if (current
->n_suppress
<= n_subtract
) /* Saturated */
3096 current
->n_suppress
= 0;
3098 current
->n_suppress
-= n_subtract
;
3103 assert(n_stack
== 1);
3104 assert(stack
[0].n_elements
== 1);
3106 *ret
= json_variant_ref(stack
[0].elements
[0]);
3110 for (i
= 0; i
< n_stack
; i
++)
3111 json_stack_release(stack
+ i
);
3118 int json_build(JsonVariant
**ret
, ...) {
3123 r
= json_buildv(ret
, ap
);
3129 int json_log_internal(
3130 JsonVariant
*variant
,
3136 const char *format
, ...) {
3140 unsigned source_line
, source_column
;
3141 char buffer
[LINE_MAX
];
3146 errno
= ERRNO_VALUE(error
);
3148 va_start(ap
, format
);
3149 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
3153 r
= json_variant_get_source(variant
, &source
, &source_line
, &source_column
);
3162 if (source
&& source_line
> 0 && source_column
> 0)
3163 return log_struct_internal(
3164 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3167 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3168 "CONFIG_FILE=%s", source
,
3169 "CONFIG_LINE=%u", source_line
,
3170 "CONFIG_COLUMN=%u", source_column
,
3171 LOG_MESSAGE("%s:%u:%u: %s", source
, source_line
, source_column
, buffer
),
3174 return log_struct_internal(
3175 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3178 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3179 LOG_MESSAGE("%s", buffer
),
3183 int json_dispatch(JsonVariant
*v
, const JsonDispatch table
[], JsonDispatchCallback bad
, JsonDispatchFlags flags
, void *userdata
) {
3184 const JsonDispatch
*p
;
3189 if (!json_variant_is_object(v
)) {
3190 json_log(v
, flags
, 0, "JSON variant is not an object.");
3192 if (flags
& JSON_PERMISSIVE
)
3198 for (p
= table
, m
= 0; p
->name
; p
++)
3201 found
= newa0(bool, m
);
3203 n
= json_variant_elements(v
);
3204 for (i
= 0; i
< n
; i
+= 2) {
3205 JsonVariant
*key
, *value
;
3207 assert_se(key
= json_variant_by_index(v
, i
));
3208 assert_se(value
= json_variant_by_index(v
, i
+1));
3210 for (p
= table
; p
->name
; p
++)
3211 if (p
->name
== (const char*) -1 ||
3212 streq_ptr(json_variant_string(key
), p
->name
))
3215 if (p
->name
) { /* Found a matching entry! :-) */
3216 JsonDispatchFlags merged_flags
;
3218 merged_flags
= flags
| p
->flags
;
3220 if (p
->type
!= _JSON_VARIANT_TYPE_INVALID
&&
3221 !json_variant_has_type(value
, p
->type
)) {
3223 json_log(value
, merged_flags
, 0,
3224 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key
),
3225 json_variant_type_to_string(json_variant_type(value
)), json_variant_type_to_string(p
->type
));
3227 if (merged_flags
& JSON_PERMISSIVE
)
3233 if (found
[p
-table
]) {
3234 json_log(value
, merged_flags
, 0, "Duplicate object field '%s'.", json_variant_string(key
));
3236 if (merged_flags
& JSON_PERMISSIVE
)
3242 found
[p
-table
] = true;
3245 r
= p
->callback(json_variant_string(key
), value
, merged_flags
, (uint8_t*) userdata
+ p
->offset
);
3247 if (merged_flags
& JSON_PERMISSIVE
)
3256 } else { /* Didn't find a matching entry! :-( */
3259 r
= bad(json_variant_string(key
), value
, flags
, userdata
);
3261 if (flags
& JSON_PERMISSIVE
)
3269 json_log(value
, flags
, 0, "Unexpected object field '%s'.", json_variant_string(key
));
3271 if (flags
& JSON_PERMISSIVE
)
3274 return -EADDRNOTAVAIL
;
3279 for (p
= table
; p
->name
; p
++) {
3280 JsonDispatchFlags merged_flags
= p
->flags
| flags
;
3282 if ((merged_flags
& JSON_MANDATORY
) && !found
[p
-table
]) {
3283 json_log(v
, merged_flags
, 0, "Missing object field '%s'.", p
->name
);
3285 if ((merged_flags
& JSON_PERMISSIVE
))
3295 int json_dispatch_boolean(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3301 if (!json_variant_is_boolean(variant
))
3302 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "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 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3317 *b
= json_variant_boolean(variant
);
3321 int json_dispatch_integer(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3322 intmax_t *i
= userdata
;
3327 if (!json_variant_is_integer(variant
))
3328 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3330 *i
= json_variant_integer(variant
);
3334 int json_dispatch_unsigned(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3335 uintmax_t *u
= userdata
;
3340 if (!json_variant_is_unsigned(variant
))
3341 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3343 *u
= json_variant_unsigned(variant
);
3347 int json_dispatch_uint32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3348 uint32_t *u
= userdata
;
3353 if (!json_variant_is_unsigned(variant
))
3354 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3356 if (json_variant_unsigned(variant
) > UINT32_MAX
)
3357 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3359 *u
= (uint32_t) json_variant_unsigned(variant
);
3363 int json_dispatch_int32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3364 int32_t *i
= userdata
;
3369 if (!json_variant_is_integer(variant
))
3370 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3372 if (json_variant_integer(variant
) < INT32_MIN
|| json_variant_integer(variant
) > INT32_MAX
)
3373 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3375 *i
= (int32_t) json_variant_integer(variant
);
3379 int json_dispatch_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3380 char **s
= userdata
;
3386 if (json_variant_is_null(variant
)) {
3391 if (!json_variant_is_string(variant
))
3392 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
3394 r
= free_and_strdup(s
, json_variant_string(variant
));
3396 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
3401 int json_dispatch_strv(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3402 _cleanup_strv_free_
char **l
= NULL
;
3403 char ***s
= userdata
;
3410 if (json_variant_is_null(variant
)) {
3415 if (!json_variant_is_array(variant
))
3416 return json_log(variant
, SYNTHETIC_ERRNO(EINVAL
), flags
, "JSON field '%s' is not an array.", strna(name
));
3418 for (i
= 0; i
< json_variant_elements(variant
); i
++) {
3421 assert_se(e
= json_variant_by_index(variant
, i
));
3423 if (!json_variant_is_string(e
))
3424 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON array element is not a string.");
3426 r
= strv_extend(&l
, json_variant_string(e
));
3428 return json_log(e
, flags
, r
, "Failed to append array element: %m");
3431 strv_free_and_replace(*s
, l
);
3435 int json_dispatch_variant(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3436 JsonVariant
**p
= userdata
;
3441 json_variant_unref(*p
);
3442 *p
= json_variant_ref(variant
);
3447 static const char* const json_variant_type_table
[_JSON_VARIANT_TYPE_MAX
] = {
3448 [JSON_VARIANT_STRING
] = "string",
3449 [JSON_VARIANT_INTEGER
] = "integer",
3450 [JSON_VARIANT_UNSIGNED
] = "unsigned",
3451 [JSON_VARIANT_REAL
] = "real",
3452 [JSON_VARIANT_NUMBER
] = "number",
3453 [JSON_VARIANT_BOOLEAN
] = "boolean",
3454 [JSON_VARIANT_ARRAY
] = "array",
3455 [JSON_VARIANT_OBJECT
] = "object",
3456 [JSON_VARIANT_NULL
] = "null",
3459 DEFINE_STRING_TABLE_LOOKUP(json_variant_type
, JsonVariantType
);