1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "sd-messages.h"
12 #include "alloc-util.h"
13 #include "errno-util.h"
17 #include "hexdecoct.h"
18 #include "json-internal.h"
21 #include "memory-util.h"
22 #include "string-table.h"
23 #include "string-util.h"
25 #include "terminal-util.h"
26 #include "user-util.h"
29 /* Refuse putting together variants with a larger depth than 2K 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
33 * The value first was 16k, but it was discovered to be too high on llvm/x86-64. See also:
34 * https://github.com/systemd/systemd/issues/10738
36 * The value then was 4k, but it was discovered to be too high on s390x/aarch64. See also:
37 * https://github.com/systemd/systemd/issues/14396 */
39 #define DEPTH_MAX (2U*1024U)
40 assert_cc(DEPTH_MAX
<= UINT16_MAX
);
42 typedef struct JsonSource
{
43 /* When we parse from a file or similar, encodes the filename, to indicate the source of a json variant */
50 /* On x86-64 this whole structure should have a size of 6 * 64 bit = 48 bytes */
53 /* We either maintain a reference counter for this variant itself, or we are embedded into an
54 * array/object, in which case only that surrounding object is ref-counted. (If 'embedded' is false,
58 /* If this JsonVariant is part of an array/object, then this field points to the surrounding
59 * JSON_VARIANT_ARRAY/JSON_VARIANT_OBJECT object. (If 'embedded' is true, see below.) */
63 /* If this was parsed from some file or buffer, this stores where from, as well as the source line/column */
65 unsigned line
, column
;
67 JsonVariantType type
:5;
69 /* A marker whether this variant is embedded into in array/object or not. If true, the 'parent' pointer above
70 * is valid. If false, the 'n_ref' field above is valid instead. */
73 /* In some conditions (for example, if this object is part of an array of strings or objects), we don't store
74 * any data inline, but instead simply reference an external object and act as surrogate of it. In that case
75 * this bool is set, and the external object is referenced through the .reference field below. */
78 /* While comparing two arrays, we use this for marking what we already have seen */
81 /* Erase from memory when freeing */
84 /* If this is an object the fields are strictly ordered by name */
87 /* If in addition to this object all objects referenced by it are also ordered strictly by name */
90 /* The current 'depth' of the JsonVariant, i.e. how many levels of member variants this has */
94 /* For simple types we store the value in-line. */
97 /* For objects and arrays we store the number of elements immediately following */
100 /* If is_reference as indicated above is set, this is where the reference object is actually stored. */
101 JsonVariant
*reference
;
103 /* Strings are placed immediately after the structure. Note that when this is a JsonVariant embedded
104 * into an array we might encode strings up to INLINE_STRING_LENGTH characters directly inside the
105 * element, while longer strings are stored as references. When this object is not embedded into an
106 * array, but stand-alone we allocate the right size for the whole structure, i.e. the array might be
107 * much larger than INLINE_STRING_LENGTH.
109 * Note that because we want to allocate arrays of the JsonVariant structure we specify [0] here,
110 * rather than the prettier []. If we wouldn't, then this char array would have undefined size, and so
111 * would the union and then the struct this is included in. And of structures with undefined size we
112 * can't allocate arrays (at least not easily). */
117 /* Inside string arrays we have a series of JasonVariant structures one after the other. In this case, strings longer
118 * than INLINE_STRING_MAX are stored as references, and all shorter ones inline. (This means — on x86-64 — strings up
119 * to 15 chars are stored within the array elements, and all others in separate allocations) */
120 #define INLINE_STRING_MAX (sizeof(JsonVariant) - offsetof(JsonVariant, string) - 1U)
122 /* Let's make sure this structure isn't increased in size accidentally. This check is only for our most relevant arch
125 assert_cc(sizeof(JsonVariant
) == 48U);
126 assert_cc(INLINE_STRING_MAX
== 15U);
129 static JsonSource
* json_source_new(const char *name
) {
134 s
= malloc(offsetof(JsonSource
, name
) + strlen(name
) + 1);
141 strcpy(s
->name
, name
);
146 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(JsonSource
, json_source
, mfree
);
148 static bool json_source_equal(JsonSource
*a
, JsonSource
*b
) {
155 return streq(a
->name
, b
->name
);
158 DEFINE_TRIVIAL_CLEANUP_FUNC(JsonSource
*, json_source_unref
);
160 /* There are four kind of JsonVariant* pointers:
163 * 2. A 'regular' one, i.e. pointing to malloc() memory
164 * 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.
165 * 4. A 'const string' one, i.e. a pointer to a const string.
167 * The four kinds of pointers can be discerned like this:
169 * Detecting #1 is easy, just compare with NULL. Detecting #3 is similarly easy: all magic pointers are below
170 * _JSON_VARIANT_MAGIC_MAX (which is pretty low, within the first memory page, which is special on Linux and other
171 * 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,
172 * otherwise #4. This makes use of the fact that malloc() will return "maximum aligned" memory, which definitely
173 * means the pointer is even. This means we can use the uneven pointers to reference static strings, as long as we
174 * make sure that all static strings used like this are aligned to 2 (or higher), and that we mask the bit on
175 * access. The JSON_VARIANT_STRING_CONST() macro encodes strings as JsonVariant* pointers, with the bit set. */
177 static bool json_variant_is_magic(const JsonVariant
*v
) {
181 return v
< _JSON_VARIANT_MAGIC_MAX
;
184 static bool json_variant_is_const_string(const JsonVariant
*v
) {
186 if (v
< _JSON_VARIANT_MAGIC_MAX
)
189 /* A proper JsonVariant is aligned to whatever malloc() aligns things too, which is definitely not uneven. We
190 * hence use all uneven pointers as indicators for const strings. */
192 return (((uintptr_t) v
) & 1) != 0;
195 static bool json_variant_is_regular(const JsonVariant
*v
) {
197 if (v
< _JSON_VARIANT_MAGIC_MAX
)
200 return (((uintptr_t) v
) & 1) == 0;
203 static JsonVariant
*json_variant_dereference(JsonVariant
*v
) {
205 /* Recursively dereference variants that are references to other variants */
210 if (!json_variant_is_regular(v
))
213 if (!v
->is_reference
)
216 return json_variant_dereference(v
->reference
);
219 static uint16_t json_variant_depth(JsonVariant
*v
) {
221 v
= json_variant_dereference(v
);
225 if (!json_variant_is_regular(v
))
231 static JsonVariant
*json_variant_formalize(JsonVariant
*v
) {
233 /* Converts json variant pointers to their normalized form, i.e. fully dereferenced and wherever
234 * possible converted to the "magic" version if there is one */
239 v
= json_variant_dereference(v
);
241 switch (json_variant_type(v
)) {
243 case JSON_VARIANT_BOOLEAN
:
244 return json_variant_boolean(v
) ? JSON_VARIANT_MAGIC_TRUE
: JSON_VARIANT_MAGIC_FALSE
;
246 case JSON_VARIANT_NULL
:
247 return JSON_VARIANT_MAGIC_NULL
;
249 case JSON_VARIANT_INTEGER
:
250 return json_variant_integer(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_INTEGER
: v
;
252 case JSON_VARIANT_UNSIGNED
:
253 return json_variant_unsigned(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_UNSIGNED
: v
;
255 case JSON_VARIANT_REAL
:
256 DISABLE_WARNING_FLOAT_EQUAL
;
257 return json_variant_real(v
) == 0.0 ? JSON_VARIANT_MAGIC_ZERO_REAL
: v
;
260 case JSON_VARIANT_STRING
:
261 return isempty(json_variant_string(v
)) ? JSON_VARIANT_MAGIC_EMPTY_STRING
: v
;
263 case JSON_VARIANT_ARRAY
:
264 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_ARRAY
: v
;
266 case JSON_VARIANT_OBJECT
:
267 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_OBJECT
: v
;
274 static JsonVariant
*json_variant_conservative_formalize(JsonVariant
*v
) {
276 /* Much like json_variant_formalize(), but won't simplify if the variant has a source/line location attached to
277 * it, in order not to lose context */
282 if (!json_variant_is_regular(v
))
285 if (v
->source
|| v
->line
> 0 || v
->column
> 0)
288 return json_variant_formalize(v
);
291 static int json_variant_new(JsonVariant
**ret
, JsonVariantType type
, size_t space
) {
294 assert_return(ret
, -EINVAL
);
296 v
= malloc0(MAX(sizeof(JsonVariant
),
297 offsetof(JsonVariant
, value
) + space
));
308 int json_variant_new_integer(JsonVariant
**ret
, intmax_t i
) {
312 assert_return(ret
, -EINVAL
);
315 *ret
= JSON_VARIANT_MAGIC_ZERO_INTEGER
;
319 r
= json_variant_new(&v
, JSON_VARIANT_INTEGER
, sizeof(i
));
323 v
->value
.integer
= i
;
329 int json_variant_new_unsigned(JsonVariant
**ret
, uintmax_t u
) {
333 assert_return(ret
, -EINVAL
);
335 *ret
= JSON_VARIANT_MAGIC_ZERO_UNSIGNED
;
339 r
= json_variant_new(&v
, JSON_VARIANT_UNSIGNED
, sizeof(u
));
349 int json_variant_new_real(JsonVariant
**ret
, long double d
) {
353 assert_return(ret
, -EINVAL
);
355 DISABLE_WARNING_FLOAT_EQUAL
;
357 *ret
= JSON_VARIANT_MAGIC_ZERO_REAL
;
362 r
= json_variant_new(&v
, JSON_VARIANT_REAL
, sizeof(d
));
372 int json_variant_new_boolean(JsonVariant
**ret
, bool b
) {
373 assert_return(ret
, -EINVAL
);
376 *ret
= JSON_VARIANT_MAGIC_TRUE
;
378 *ret
= JSON_VARIANT_MAGIC_FALSE
;
383 int json_variant_new_null(JsonVariant
**ret
) {
384 assert_return(ret
, -EINVAL
);
386 *ret
= JSON_VARIANT_MAGIC_NULL
;
390 int json_variant_new_stringn(JsonVariant
**ret
, const char *s
, size_t n
) {
394 assert_return(ret
, -EINVAL
);
396 assert_return(IN_SET(n
, 0, (size_t) -1), -EINVAL
);
397 return json_variant_new_null(ret
);
399 if (n
== (size_t) -1) /* determine length automatically */
401 else if (memchr(s
, 0, n
)) /* don't allow embedded NUL, as we can't express that in JSON */
404 *ret
= JSON_VARIANT_MAGIC_EMPTY_STRING
;
408 r
= json_variant_new(&v
, JSON_VARIANT_STRING
, n
+ 1);
412 memcpy(v
->string
, s
, n
);
419 int json_variant_new_base64(JsonVariant
**ret
, const void *p
, size_t n
) {
420 _cleanup_free_
char *s
= NULL
;
423 assert_return(ret
, -EINVAL
);
424 assert_return(n
== 0 || p
, -EINVAL
);
426 k
= base64mem(p
, n
, &s
);
430 return json_variant_new_stringn(ret
, s
, k
);
433 int json_variant_new_id128(JsonVariant
**ret
, sd_id128_t id
) {
434 char s
[SD_ID128_STRING_MAX
];
436 return json_variant_new_string(ret
, sd_id128_to_string(id
, s
));
439 static void json_variant_set(JsonVariant
*a
, JsonVariant
*b
) {
442 b
= json_variant_dereference(b
);
444 a
->type
= JSON_VARIANT_NULL
;
448 a
->type
= json_variant_type(b
);
451 case JSON_VARIANT_INTEGER
:
452 a
->value
.integer
= json_variant_integer(b
);
455 case JSON_VARIANT_UNSIGNED
:
456 a
->value
.unsig
= json_variant_unsigned(b
);
459 case JSON_VARIANT_REAL
:
460 a
->value
.real
= json_variant_real(b
);
463 case JSON_VARIANT_BOOLEAN
:
464 a
->value
.boolean
= json_variant_boolean(b
);
467 case JSON_VARIANT_STRING
: {
470 assert_se(s
= json_variant_string(b
));
472 /* Short strings we can store inline */
473 if (strnlen(s
, INLINE_STRING_MAX
+1) <= INLINE_STRING_MAX
) {
474 strcpy(a
->string
, s
);
478 /* For longer strings, use a reference… */
482 case JSON_VARIANT_ARRAY
:
483 case JSON_VARIANT_OBJECT
:
484 a
->is_reference
= true;
485 a
->reference
= json_variant_ref(json_variant_conservative_formalize(b
));
488 case JSON_VARIANT_NULL
:
492 assert_not_reached("Unexpected variant type");
496 static void json_variant_copy_source(JsonVariant
*v
, JsonVariant
*from
) {
500 if (!json_variant_is_regular(from
))
503 v
->line
= from
->line
;
504 v
->column
= from
->column
;
505 v
->source
= json_source_ref(from
->source
);
508 int json_variant_new_array(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
509 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
510 bool normalized
= true;
512 assert_return(ret
, -EINVAL
);
514 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
517 assert_return(array
, -EINVAL
);
519 v
= new(JsonVariant
, n
+ 1);
525 .type
= JSON_VARIANT_ARRAY
,
528 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
529 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
530 *c
= array
[v
->n_elements
];
533 d
= json_variant_depth(c
);
534 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
544 json_variant_set(w
, c
);
545 json_variant_copy_source(w
, c
);
547 if (!json_variant_is_normalized(c
))
551 v
->normalized
= normalized
;
557 int json_variant_new_array_bytes(JsonVariant
**ret
, const void *p
, size_t n
) {
561 assert_return(ret
, -EINVAL
);
563 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
566 assert_return(p
, -EINVAL
);
568 v
= new(JsonVariant
, n
+ 1);
574 .type
= JSON_VARIANT_ARRAY
,
579 for (i
= 0; i
< n
; i
++) {
580 JsonVariant
*w
= v
+ 1 + i
;
585 .type
= JSON_VARIANT_UNSIGNED
,
586 .value
.unsig
= ((const uint8_t*) p
)[i
],
590 v
->normalized
= true;
596 int json_variant_new_array_strv(JsonVariant
**ret
, char **l
) {
597 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
605 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
609 v
= new(JsonVariant
, n
+ 1);
615 .type
= JSON_VARIANT_ARRAY
,
619 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
620 JsonVariant
*w
= v
+ 1 + v
->n_elements
;
626 .type
= JSON_VARIANT_STRING
,
629 k
= strlen(l
[v
->n_elements
]);
631 if (k
> INLINE_STRING_MAX
) {
632 /* If string is too long, store it as reference. */
634 r
= json_variant_new_string(&w
->reference
, l
[v
->n_elements
]);
638 w
->is_reference
= true;
640 memcpy(w
->string
, l
[v
->n_elements
], k
+1);
643 v
->normalized
= true;
649 int json_variant_new_object(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
650 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
651 const char *prev
= NULL
;
652 bool sorted
= true, normalized
= true;
654 assert_return(ret
, -EINVAL
);
656 *ret
= JSON_VARIANT_MAGIC_EMPTY_OBJECT
;
659 assert_return(array
, -EINVAL
);
660 assert_return(n
% 2 == 0, -EINVAL
);
662 v
= new(JsonVariant
, n
+ 1);
668 .type
= JSON_VARIANT_OBJECT
,
671 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
672 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
673 *c
= array
[v
->n_elements
];
676 if ((v
->n_elements
& 1) == 0) {
679 if (!json_variant_is_string(c
))
680 return -EINVAL
; /* Every second one needs to be a string, as it is the key name */
682 assert_se(k
= json_variant_string(c
));
684 if (prev
&& strcmp(k
, prev
) <= 0)
685 sorted
= normalized
= false;
688 } else if (!json_variant_is_normalized(c
))
691 d
= json_variant_depth(c
);
692 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
702 json_variant_set(w
, c
);
703 json_variant_copy_source(w
, c
);
706 v
->normalized
= normalized
;
713 static size_t json_variant_size(JsonVariant
* v
) {
715 if (!json_variant_is_regular(v
))
719 return offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*);
723 case JSON_VARIANT_STRING
:
724 return offsetof(JsonVariant
, string
) + strlen(v
->string
) + 1;
726 case JSON_VARIANT_REAL
:
727 return offsetof(JsonVariant
, value
) + sizeof(long double);
729 case JSON_VARIANT_UNSIGNED
:
730 return offsetof(JsonVariant
, value
) + sizeof(uintmax_t);
732 case JSON_VARIANT_INTEGER
:
733 return offsetof(JsonVariant
, value
) + sizeof(intmax_t);
735 case JSON_VARIANT_BOOLEAN
:
736 return offsetof(JsonVariant
, value
) + sizeof(bool);
738 case JSON_VARIANT_ARRAY
:
739 case JSON_VARIANT_OBJECT
:
740 return offsetof(JsonVariant
, n_elements
) + sizeof(size_t);
742 case JSON_VARIANT_NULL
:
743 return offsetof(JsonVariant
, value
);
746 assert_not_reached("unexpected type");
750 static void json_variant_free_inner(JsonVariant
*v
, bool force_sensitive
) {
755 if (!json_variant_is_regular(v
))
758 json_source_unref(v
->source
);
760 sensitive
= v
->sensitive
|| force_sensitive
;
762 if (v
->is_reference
) {
764 json_variant_sensitive(v
->reference
);
766 json_variant_unref(v
->reference
);
770 if (IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
)) {
773 for (i
= 0; i
< v
->n_elements
; i
++)
774 json_variant_free_inner(v
+ 1 + i
, sensitive
);
778 explicit_bzero_safe(v
, json_variant_size(v
));
781 JsonVariant
*json_variant_ref(JsonVariant
*v
) {
784 if (!json_variant_is_regular(v
))
788 json_variant_ref(v
->parent
); /* ref the compounding variant instead */
790 assert(v
->n_ref
> 0);
797 JsonVariant
*json_variant_unref(JsonVariant
*v
) {
800 if (!json_variant_is_regular(v
))
804 json_variant_unref(v
->parent
);
806 assert(v
->n_ref
> 0);
810 json_variant_free_inner(v
, false);
818 void json_variant_unref_many(JsonVariant
**array
, size_t n
) {
821 assert(array
|| n
== 0);
823 for (i
= 0; i
< n
; i
++)
824 json_variant_unref(array
[i
]);
827 const char *json_variant_string(JsonVariant
*v
) {
830 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
832 if (json_variant_is_magic(v
))
834 if (json_variant_is_const_string(v
)) {
835 uintptr_t p
= (uintptr_t) v
;
837 assert((p
& 1) != 0);
838 return (const char*) (p
^ 1U);
842 return json_variant_string(v
->reference
);
843 if (v
->type
!= JSON_VARIANT_STRING
)
849 log_debug("Non-string JSON variant requested as string, returning NULL.");
853 bool json_variant_boolean(JsonVariant
*v
) {
856 if (v
== JSON_VARIANT_MAGIC_TRUE
)
858 if (v
== JSON_VARIANT_MAGIC_FALSE
)
860 if (!json_variant_is_regular(v
))
862 if (v
->type
!= JSON_VARIANT_BOOLEAN
)
865 return json_variant_boolean(v
->reference
);
867 return v
->value
.boolean
;
870 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
874 intmax_t json_variant_integer(JsonVariant
*v
) {
877 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
878 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
879 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
881 if (!json_variant_is_regular(v
))
884 return json_variant_integer(v
->reference
);
888 case JSON_VARIANT_INTEGER
:
889 return v
->value
.integer
;
891 case JSON_VARIANT_UNSIGNED
:
892 if (v
->value
.unsig
<= INTMAX_MAX
)
893 return (intmax_t) v
->value
.unsig
;
895 log_debug("Unsigned integer %ju requested as signed integer and out of range, returning 0.", v
->value
.unsig
);
898 case JSON_VARIANT_REAL
: {
901 converted
= (intmax_t) v
->value
.real
;
903 DISABLE_WARNING_FLOAT_EQUAL
;
904 if ((long double) converted
== v
->value
.real
)
908 log_debug("Real %Lg requested as integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
917 log_debug("Non-integer JSON variant requested as integer, returning 0.");
921 uintmax_t json_variant_unsigned(JsonVariant
*v
) {
924 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
925 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
926 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
928 if (!json_variant_is_regular(v
))
931 return json_variant_integer(v
->reference
);
935 case JSON_VARIANT_INTEGER
:
936 if (v
->value
.integer
>= 0)
937 return (uintmax_t) v
->value
.integer
;
939 log_debug("Signed integer %ju requested as unsigned integer and out of range, returning 0.", v
->value
.integer
);
942 case JSON_VARIANT_UNSIGNED
:
943 return v
->value
.unsig
;
945 case JSON_VARIANT_REAL
: {
948 converted
= (uintmax_t) v
->value
.real
;
950 DISABLE_WARNING_FLOAT_EQUAL
;
951 if ((long double) converted
== v
->value
.real
)
955 log_debug("Real %Lg requested as unsigned integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
964 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
968 long double json_variant_real(JsonVariant
*v
) {
971 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
972 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
973 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
975 if (!json_variant_is_regular(v
))
978 return json_variant_real(v
->reference
);
982 case JSON_VARIANT_REAL
:
983 return v
->value
.real
;
985 case JSON_VARIANT_INTEGER
: {
986 long double converted
;
988 converted
= (long double) v
->value
.integer
;
990 if ((intmax_t) converted
== v
->value
.integer
)
993 log_debug("Signed integer %ji requested as real, and cannot be converted losslessly, returning 0.", v
->value
.integer
);
997 case JSON_VARIANT_UNSIGNED
: {
998 long double converted
;
1000 converted
= (long double) v
->value
.unsig
;
1002 if ((uintmax_t) converted
== v
->value
.unsig
)
1005 log_debug("Unsigned integer %ju requested as real, and cannot be converted losslessly, returning 0.", v
->value
.unsig
);
1014 log_debug("Non-integer JSON variant requested as integer, returning 0.");
1018 bool json_variant_is_negative(JsonVariant
*v
) {
1021 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
1022 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
1023 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
1025 if (!json_variant_is_regular(v
))
1027 if (v
->is_reference
)
1028 return json_variant_is_negative(v
->reference
);
1030 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
1031 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
1036 case JSON_VARIANT_REAL
:
1037 return v
->value
.real
< 0;
1039 case JSON_VARIANT_INTEGER
:
1040 return v
->value
.integer
< 0;
1042 case JSON_VARIANT_UNSIGNED
:
1050 log_debug("Non-integer JSON variant tested for negativity, returning false.");
1054 bool json_variant_is_blank_object(JsonVariant
*v
) {
1055 /* Returns true if the specified object is null or empty */
1057 json_variant_is_null(v
) ||
1058 (json_variant_is_object(v
) && json_variant_elements(v
) == 0);
1061 bool json_variant_is_blank_array(JsonVariant
*v
) {
1063 json_variant_is_null(v
) ||
1064 (json_variant_is_array(v
) && json_variant_elements(v
) == 0);
1067 JsonVariantType
json_variant_type(JsonVariant
*v
) {
1070 return _JSON_VARIANT_TYPE_INVALID
;
1072 if (json_variant_is_const_string(v
))
1073 return JSON_VARIANT_STRING
;
1075 if (v
== JSON_VARIANT_MAGIC_TRUE
|| v
== JSON_VARIANT_MAGIC_FALSE
)
1076 return JSON_VARIANT_BOOLEAN
;
1078 if (v
== JSON_VARIANT_MAGIC_NULL
)
1079 return JSON_VARIANT_NULL
;
1081 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
)
1082 return JSON_VARIANT_INTEGER
;
1084 if (v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
)
1085 return JSON_VARIANT_UNSIGNED
;
1087 if (v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
1088 return JSON_VARIANT_REAL
;
1090 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
1091 return JSON_VARIANT_STRING
;
1093 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
)
1094 return JSON_VARIANT_ARRAY
;
1096 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1097 return JSON_VARIANT_OBJECT
;
1102 _function_no_sanitize_float_cast_overflow_
bool json_variant_has_type(JsonVariant
*v
, JsonVariantType type
) {
1105 /* Note: we turn off ubsan float cast overflo detection for this function, since it would complain
1106 * about our float casts but we do them explicitly to detect conversion errors. */
1108 v
= json_variant_dereference(v
);
1112 rt
= json_variant_type(v
);
1116 /* If it's a const string, then it only can be a string, and if it is not, it's not */
1117 if (json_variant_is_const_string(v
))
1120 /* All three magic zeroes qualify as integer, unsigned and as real */
1121 if ((v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
|| v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
|| v
== JSON_VARIANT_MAGIC_ZERO_REAL
) &&
1122 IN_SET(type
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
, JSON_VARIANT_NUMBER
))
1125 /* All other magic variant types are only equal to themselves */
1126 if (json_variant_is_magic(v
))
1129 /* Handle the "number" pseudo type */
1130 if (type
== JSON_VARIANT_NUMBER
)
1131 return IN_SET(rt
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
);
1133 /* Integer conversions are OK in many cases */
1134 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_UNSIGNED
)
1135 return v
->value
.integer
>= 0;
1136 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_INTEGER
)
1137 return v
->value
.unsig
<= INTMAX_MAX
;
1139 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1140 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_REAL
)
1141 return (intmax_t) (long double) v
->value
.integer
== v
->value
.integer
;
1142 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_REAL
)
1143 return (uintmax_t) (long double) v
->value
.unsig
== v
->value
.unsig
;
1145 DISABLE_WARNING_FLOAT_EQUAL
;
1147 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1148 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_INTEGER
)
1149 return (long double) (intmax_t) v
->value
.real
== v
->value
.real
;
1150 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_UNSIGNED
)
1151 return (long double) (uintmax_t) v
->value
.real
== v
->value
.real
;
1158 size_t json_variant_elements(JsonVariant
*v
) {
1161 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1162 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1164 if (!json_variant_is_regular(v
))
1166 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1168 if (v
->is_reference
)
1169 return json_variant_elements(v
->reference
);
1171 return v
->n_elements
;
1174 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1178 JsonVariant
*json_variant_by_index(JsonVariant
*v
, size_t idx
) {
1181 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1182 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1184 if (!json_variant_is_regular(v
))
1186 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1188 if (v
->is_reference
)
1189 return json_variant_by_index(v
->reference
, idx
);
1190 if (idx
>= v
->n_elements
)
1193 return json_variant_conservative_formalize(v
+ 1 + idx
);
1196 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1200 JsonVariant
*json_variant_by_key_full(JsonVariant
*v
, const char *key
, JsonVariant
**ret_key
) {
1207 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1209 if (!json_variant_is_regular(v
))
1211 if (v
->type
!= JSON_VARIANT_OBJECT
)
1213 if (v
->is_reference
)
1214 return json_variant_by_key(v
->reference
, key
);
1217 size_t a
= 0, b
= v
->n_elements
/2;
1219 /* If the variant is sorted we can use bisection to find the entry we need in O(log(n)) time */
1227 p
= json_variant_dereference(v
+ 1 + i
*2);
1229 assert_se(f
= json_variant_string(p
));
1234 *ret_key
= json_variant_conservative_formalize(v
+ 1 + i
*2);
1236 return json_variant_conservative_formalize(v
+ 1 + i
*2 + 1);
1246 /* The variant is not sorted, hence search for the field linearly */
1247 for (i
= 0; i
< v
->n_elements
; i
+= 2) {
1250 p
= json_variant_dereference(v
+ 1 + i
);
1252 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1255 if (streq(json_variant_string(p
), key
)) {
1258 *ret_key
= json_variant_conservative_formalize(v
+ 1 + i
);
1260 return json_variant_conservative_formalize(v
+ 1 + i
+ 1);
1271 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1278 JsonVariant
*json_variant_by_key(JsonVariant
*v
, const char *key
) {
1279 return json_variant_by_key_full(v
, key
, NULL
);
1282 bool json_variant_equal(JsonVariant
*a
, JsonVariant
*b
) {
1285 a
= json_variant_formalize(a
);
1286 b
= json_variant_formalize(b
);
1291 t
= json_variant_type(a
);
1292 if (!json_variant_has_type(b
, t
))
1297 case JSON_VARIANT_STRING
:
1298 return streq(json_variant_string(a
), json_variant_string(b
));
1300 case JSON_VARIANT_INTEGER
:
1301 return json_variant_integer(a
) == json_variant_integer(b
);
1303 case JSON_VARIANT_UNSIGNED
:
1304 return json_variant_unsigned(a
) == json_variant_unsigned(b
);
1306 case JSON_VARIANT_REAL
:
1307 DISABLE_WARNING_FLOAT_EQUAL
;
1308 return json_variant_real(a
) == json_variant_real(b
);
1311 case JSON_VARIANT_BOOLEAN
:
1312 return json_variant_boolean(a
) == json_variant_boolean(b
);
1314 case JSON_VARIANT_NULL
:
1317 case JSON_VARIANT_ARRAY
: {
1320 n
= json_variant_elements(a
);
1321 if (n
!= json_variant_elements(b
))
1324 for (i
= 0; i
< n
; i
++) {
1325 if (!json_variant_equal(json_variant_by_index(a
, i
), json_variant_by_index(b
, i
)))
1332 case JSON_VARIANT_OBJECT
: {
1335 n
= json_variant_elements(a
);
1336 if (n
!= json_variant_elements(b
))
1339 /* Iterate through all keys in 'a' */
1340 for (i
= 0; i
< n
; i
+= 2) {
1344 /* Match them against all keys in 'b' */
1345 for (j
= 0; j
< n
; j
+= 2) {
1348 key_b
= json_variant_by_index(b
, j
);
1350 /* During the first iteration unmark everything */
1352 key_b
->is_marked
= false;
1353 else if (key_b
->is_marked
) /* In later iterations if we already marked something, don't bother with it again */
1359 if (json_variant_equal(json_variant_by_index(a
, i
), key_b
) &&
1360 json_variant_equal(json_variant_by_index(a
, i
+1), json_variant_by_index(b
, j
+1))) {
1361 /* Key and values match! */
1362 key_b
->is_marked
= found
= true;
1364 /* In the first iteration we continue the inner loop since we want to mark
1365 * everything, otherwise exit the loop quickly after we found what we were
1380 assert_not_reached("Unknown variant type.");
1384 void json_variant_sensitive(JsonVariant
*v
) {
1387 /* Marks a variant as "sensitive", so that it is erased from memory when it is destroyed. This is a
1388 * one-way operation: as soon as it is marked this way it remains marked this way until it's
1389 * destroyed. A magic variant is never sensitive though, even when asked, since it's too
1390 * basic. Similar, const string variant are never sensitive either, after all they are included in
1391 * the source code as they are, which is not suitable for inclusion of secrets.
1393 * Note that this flag has a recursive effect: when we destroy an object or array we'll propagate the
1394 * flag to all contained variants. And if those are then destroyed this is propagated further down,
1397 v
= json_variant_formalize(v
);
1398 if (!json_variant_is_regular(v
))
1401 v
->sensitive
= true;
1404 bool json_variant_is_sensitive(JsonVariant
*v
) {
1405 v
= json_variant_formalize(v
);
1406 if (!json_variant_is_regular(v
))
1409 return v
->sensitive
;
1412 static void json_variant_propagate_sensitive(JsonVariant
*from
, JsonVariant
*to
) {
1413 if (json_variant_is_sensitive(from
))
1414 json_variant_sensitive(to
);
1417 int json_variant_get_source(JsonVariant
*v
, const char **ret_source
, unsigned *ret_line
, unsigned *ret_column
) {
1418 assert_return(v
, -EINVAL
);
1421 *ret_source
= json_variant_is_regular(v
) && v
->source
? v
->source
->name
: NULL
;
1424 *ret_line
= json_variant_is_regular(v
) ? v
->line
: 0;
1427 *ret_column
= json_variant_is_regular(v
) ? v
->column
: 0;
1432 static int print_source(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, bool whitespace
) {
1435 if (!FLAGS_SET(flags
, JSON_FORMAT_SOURCE
|JSON_FORMAT_PRETTY
))
1438 if (!json_variant_is_regular(v
))
1441 if (!v
->source
&& v
->line
== 0 && v
->column
== 0)
1444 /* The max width we need to format the line numbers for this source file */
1445 w
= (v
->source
&& v
->source
->max_line
> 0) ?
1446 DECIMAL_STR_WIDTH(v
->source
->max_line
) :
1447 DECIMAL_STR_MAX(unsigned)-1;
1448 k
= (v
->source
&& v
->source
->max_column
> 0) ?
1449 DECIMAL_STR_WIDTH(v
->source
->max_column
) :
1450 DECIMAL_STR_MAX(unsigned) -1;
1455 n
= 1 + (v
->source
? strlen(v
->source
->name
) : 0) +
1456 ((v
->source
&& (v
->line
> 0 || v
->column
> 0)) ? 1 : 0) +
1457 (v
->line
> 0 ? w
: 0) +
1458 (((v
->source
|| v
->line
> 0) && v
->column
> 0) ? 1 : 0) +
1459 (v
->column
> 0 ? k
: 0) +
1462 for (i
= 0; i
< n
; i
++)
1468 fputs(v
->source
->name
, f
);
1469 if (v
->source
&& (v
->line
> 0 || v
->column
> 0))
1472 fprintf(f
, "%*u", (int) w
, v
->line
);
1473 if ((v
->source
|| v
->line
> 0) || v
->column
> 0)
1476 fprintf(f
, "%*u", (int) k
, v
->column
);
1485 static int json_format(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, const char *prefix
) {
1491 switch (json_variant_type(v
)) {
1493 case JSON_VARIANT_REAL
: {
1496 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
1497 if (loc
== (locale_t
) 0)
1500 if (flags
& JSON_FORMAT_COLOR
)
1501 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1503 fprintf(f
, "%.*Le", DECIMAL_DIG
, json_variant_real(v
));
1505 if (flags
& JSON_FORMAT_COLOR
)
1506 fputs(ANSI_NORMAL
, f
);
1512 case JSON_VARIANT_INTEGER
:
1513 if (flags
& JSON_FORMAT_COLOR
)
1514 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1516 fprintf(f
, "%" PRIdMAX
, json_variant_integer(v
));
1518 if (flags
& JSON_FORMAT_COLOR
)
1519 fputs(ANSI_NORMAL
, f
);
1522 case JSON_VARIANT_UNSIGNED
:
1523 if (flags
& JSON_FORMAT_COLOR
)
1524 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1526 fprintf(f
, "%" PRIuMAX
, json_variant_unsigned(v
));
1528 if (flags
& JSON_FORMAT_COLOR
)
1529 fputs(ANSI_NORMAL
, f
);
1532 case JSON_VARIANT_BOOLEAN
:
1534 if (flags
& JSON_FORMAT_COLOR
)
1535 fputs(ANSI_HIGHLIGHT
, f
);
1537 if (json_variant_boolean(v
))
1542 if (flags
& JSON_FORMAT_COLOR
)
1543 fputs(ANSI_NORMAL
, f
);
1547 case JSON_VARIANT_NULL
:
1548 if (flags
& JSON_FORMAT_COLOR
)
1549 fputs(ANSI_HIGHLIGHT
, f
);
1553 if (flags
& JSON_FORMAT_COLOR
)
1554 fputs(ANSI_NORMAL
, f
);
1557 case JSON_VARIANT_STRING
: {
1562 if (flags
& JSON_FORMAT_COLOR
)
1563 fputs(ANSI_GREEN
, f
);
1565 for (q
= json_variant_string(v
); *q
; q
++) {
1598 if ((signed char) *q
>= 0 && *q
< ' ')
1599 fprintf(f
, "\\u%04x", *q
);
1606 if (flags
& JSON_FORMAT_COLOR
)
1607 fputs(ANSI_NORMAL
, f
);
1613 case JSON_VARIANT_ARRAY
: {
1616 n
= json_variant_elements(v
);
1621 _cleanup_free_
char *joined
= NULL
;
1622 const char *prefix2
;
1624 if (flags
& JSON_FORMAT_PRETTY
) {
1625 joined
= strjoin(strempty(prefix
), "\t");
1632 prefix2
= strempty(prefix
);
1636 for (i
= 0; i
< n
; i
++) {
1639 assert_se(e
= json_variant_by_index(v
, i
));
1642 if (flags
& JSON_FORMAT_PRETTY
)
1648 if (flags
& JSON_FORMAT_PRETTY
) {
1649 print_source(f
, e
, flags
, false);
1653 r
= json_format(f
, e
, flags
, prefix2
);
1658 if (flags
& JSON_FORMAT_PRETTY
) {
1660 print_source(f
, v
, flags
, true);
1661 fputs(strempty(prefix
), f
);
1669 case JSON_VARIANT_OBJECT
: {
1672 n
= json_variant_elements(v
);
1677 _cleanup_free_
char *joined
= NULL
;
1678 const char *prefix2
;
1680 if (flags
& JSON_FORMAT_PRETTY
) {
1681 joined
= strjoin(strempty(prefix
), "\t");
1688 prefix2
= strempty(prefix
);
1692 for (i
= 0; i
< n
; i
+= 2) {
1695 e
= json_variant_by_index(v
, i
);
1698 if (flags
& JSON_FORMAT_PRETTY
)
1704 if (flags
& JSON_FORMAT_PRETTY
) {
1705 print_source(f
, e
, flags
, false);
1709 r
= json_format(f
, e
, flags
, prefix2
);
1713 fputs(flags
& JSON_FORMAT_PRETTY
? " : " : ":", f
);
1715 r
= json_format(f
, json_variant_by_index(v
, i
+1), flags
, prefix2
);
1720 if (flags
& JSON_FORMAT_PRETTY
) {
1722 print_source(f
, v
, flags
, true);
1723 fputs(strempty(prefix
), f
);
1732 assert_not_reached("Unexpected variant type.");
1738 int json_variant_format(JsonVariant
*v
, JsonFormatFlags flags
, char **ret
) {
1739 _cleanup_free_
char *s
= NULL
;
1743 /* Returns the length of the generated string (without the terminating NUL),
1744 * or negative on error. */
1746 assert_return(v
, -EINVAL
);
1747 assert_return(ret
, -EINVAL
);
1750 _cleanup_fclose_
FILE *f
= NULL
;
1752 f
= open_memstream_unlocked(&s
, &sz
);
1756 json_variant_dump(v
, flags
, f
, NULL
);
1758 /* Add terminating 0, so that the output buffer is a valid string. */
1761 r
= fflush_and_check(f
);
1769 return (int) sz
- 1;
1772 void json_variant_dump(JsonVariant
*v
, JsonFormatFlags flags
, FILE *f
, const char *prefix
) {
1779 print_source(f
, v
, flags
, false);
1781 if (((flags
& (JSON_FORMAT_COLOR_AUTO
|JSON_FORMAT_COLOR
)) == JSON_FORMAT_COLOR_AUTO
) && colors_enabled())
1782 flags
|= JSON_FORMAT_COLOR
;
1784 if (((flags
& (JSON_FORMAT_PRETTY_AUTO
|JSON_FORMAT_PRETTY
)) == JSON_FORMAT_PRETTY_AUTO
))
1785 flags
|= on_tty() ? JSON_FORMAT_PRETTY
: JSON_FORMAT_NEWLINE
;
1787 if (flags
& JSON_FORMAT_SSE
)
1789 if (flags
& JSON_FORMAT_SEQ
)
1790 fputc('\x1e', f
); /* ASCII Record Separator */
1792 json_format(f
, v
, flags
, prefix
);
1794 if (flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_SEQ
|JSON_FORMAT_SSE
|JSON_FORMAT_NEWLINE
))
1796 if (flags
& JSON_FORMAT_SSE
)
1797 fputc('\n', f
); /* In case of SSE add a second newline */
1799 if (flags
& JSON_FORMAT_FLUSH
)
1803 int json_variant_filter(JsonVariant
**v
, char **to_remove
) {
1804 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
1805 _cleanup_free_ JsonVariant
**array
= NULL
;
1806 size_t i
, n
= 0, k
= 0;
1811 if (json_variant_is_blank_object(*v
))
1813 if (!json_variant_is_object(*v
))
1816 if (strv_isempty(to_remove
))
1819 for (i
= 0; i
< json_variant_elements(*v
); i
+= 2) {
1822 p
= json_variant_by_index(*v
, i
);
1823 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1826 if (strv_contains(to_remove
, json_variant_string(p
))) {
1828 array
= new(JsonVariant
*, json_variant_elements(*v
) - 2);
1832 for (k
= 0; k
< i
; k
++)
1833 array
[k
] = json_variant_by_index(*v
, k
);
1839 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1846 r
= json_variant_new_object(&w
, array
, k
);
1850 json_variant_propagate_sensitive(*v
, w
);
1852 json_variant_unref(*v
);
1858 int json_variant_set_field(JsonVariant
**v
, const char *field
, JsonVariant
*value
) {
1859 _cleanup_(json_variant_unrefp
) JsonVariant
*field_variant
= NULL
, *w
= NULL
;
1860 _cleanup_free_ JsonVariant
**array
= NULL
;
1867 if (json_variant_is_blank_object(*v
)) {
1868 array
= new(JsonVariant
*, 2);
1873 if (!json_variant_is_object(*v
))
1876 for (i
= 0; i
< json_variant_elements(*v
); i
+= 2) {
1879 p
= json_variant_by_index(*v
, i
);
1880 if (!json_variant_is_string(p
))
1883 if (streq(json_variant_string(p
), field
)) {
1886 array
= new(JsonVariant
*, json_variant_elements(*v
));
1890 for (k
= 0; k
< i
; k
++)
1891 array
[k
] = json_variant_by_index(*v
, k
);
1896 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1901 array
= new(JsonVariant
*, json_variant_elements(*v
) + 2);
1905 for (k
= 0; k
< json_variant_elements(*v
); k
++)
1906 array
[k
] = json_variant_by_index(*v
, k
);
1910 r
= json_variant_new_string(&field_variant
, field
);
1914 array
[k
++] = field_variant
;
1917 r
= json_variant_new_object(&w
, array
, k
);
1921 json_variant_propagate_sensitive(*v
, w
);
1923 json_variant_unref(*v
);
1929 int json_variant_set_field_string(JsonVariant
**v
, const char *field
, const char *value
) {
1930 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1933 r
= json_variant_new_string(&m
, value
);
1937 return json_variant_set_field(v
, field
, m
);
1940 int json_variant_set_field_integer(JsonVariant
**v
, const char *field
, intmax_t i
) {
1941 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1944 r
= json_variant_new_integer(&m
, i
);
1948 return json_variant_set_field(v
, field
, m
);
1951 int json_variant_set_field_unsigned(JsonVariant
**v
, const char *field
, uintmax_t u
) {
1952 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1955 r
= json_variant_new_unsigned(&m
, u
);
1959 return json_variant_set_field(v
, field
, m
);
1962 int json_variant_set_field_boolean(JsonVariant
**v
, const char *field
, bool b
) {
1963 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1966 r
= json_variant_new_boolean(&m
, b
);
1970 return json_variant_set_field(v
, field
, m
);
1973 int json_variant_set_field_strv(JsonVariant
**v
, const char *field
, char **l
) {
1974 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1977 r
= json_variant_new_array_strv(&m
, l
);
1981 return json_variant_set_field(v
, field
, m
);
1984 int json_variant_merge(JsonVariant
**v
, JsonVariant
*m
) {
1985 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
1986 _cleanup_free_ JsonVariant
**array
= NULL
;
1987 size_t v_elements
, m_elements
, i
, k
;
1988 bool v_blank
, m_blank
;
1991 m
= json_variant_dereference(m
);
1993 v_blank
= json_variant_is_blank_object(*v
);
1994 m_blank
= json_variant_is_blank_object(m
);
1996 if (!v_blank
&& !json_variant_is_object(*v
))
1998 if (!m_blank
&& !json_variant_is_object(m
))
2002 return 0; /* nothing to do */
2005 json_variant_unref(*v
);
2006 *v
= json_variant_ref(m
);
2010 v_elements
= json_variant_elements(*v
);
2011 m_elements
= json_variant_elements(m
);
2012 if (v_elements
> SIZE_MAX
- m_elements
) /* overflow check */
2015 array
= new(JsonVariant
*, v_elements
+ m_elements
);
2020 for (i
= 0; i
< v_elements
; i
+= 2) {
2023 u
= json_variant_by_index(*v
, i
);
2024 if (!json_variant_is_string(u
))
2027 if (json_variant_by_key(m
, json_variant_string(u
)))
2028 continue; /* skip if exists in second variant */
2031 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
2034 for (i
= 0; i
< m_elements
; i
++)
2035 array
[k
++] = json_variant_by_index(m
, i
);
2037 r
= json_variant_new_object(&w
, array
, k
);
2041 json_variant_propagate_sensitive(*v
, w
);
2042 json_variant_propagate_sensitive(m
, w
);
2044 json_variant_unref(*v
);
2050 int json_variant_append_array(JsonVariant
**v
, JsonVariant
*element
) {
2051 _cleanup_(json_variant_unrefp
) JsonVariant
*nv
= NULL
;
2059 if (!*v
|| json_variant_is_null(*v
))
2061 else if (!json_variant_is_array(*v
))
2064 blank
= json_variant_elements(*v
) == 0;
2067 r
= json_variant_new_array(&nv
, (JsonVariant
*[]) { element
}, 1);
2069 _cleanup_free_ JsonVariant
**array
= NULL
;
2072 array
= new(JsonVariant
*, json_variant_elements(*v
) + 1);
2076 for (i
= 0; i
< json_variant_elements(*v
); i
++)
2077 array
[i
] = json_variant_by_index(*v
, i
);
2081 r
= json_variant_new_array(&nv
, array
, i
+ 1);
2086 json_variant_propagate_sensitive(*v
, nv
);
2088 json_variant_unref(*v
);
2094 int json_variant_strv(JsonVariant
*v
, char ***ret
) {
2102 if (!v
|| json_variant_is_null(v
)) {
2111 if (!json_variant_is_array(v
))
2114 sensitive
= v
->sensitive
;
2116 n
= json_variant_elements(v
);
2117 l
= new(char*, n
+1);
2121 for (i
= 0; i
< n
; i
++) {
2124 assert_se(e
= json_variant_by_index(v
, i
));
2125 sensitive
= sensitive
|| e
->sensitive
;
2127 if (!json_variant_is_string(e
)) {
2133 l
[i
] = strdup(json_variant_string(e
));
2154 static int json_variant_copy(JsonVariant
**nv
, JsonVariant
*v
) {
2164 /* Let's copy the simple types literally, and the larger types by references */
2165 t
= json_variant_type(v
);
2167 case JSON_VARIANT_INTEGER
:
2168 k
= sizeof(intmax_t);
2169 value
.integer
= json_variant_integer(v
);
2173 case JSON_VARIANT_UNSIGNED
:
2174 k
= sizeof(uintmax_t);
2175 value
.unsig
= json_variant_unsigned(v
);
2179 case JSON_VARIANT_REAL
:
2180 k
= sizeof(long double);
2181 value
.real
= json_variant_real(v
);
2185 case JSON_VARIANT_BOOLEAN
:
2187 value
.boolean
= json_variant_boolean(v
);
2191 case JSON_VARIANT_NULL
:
2196 case JSON_VARIANT_STRING
:
2197 source
= json_variant_string(v
);
2198 k
= strnlen(source
, INLINE_STRING_MAX
+ 1);
2199 if (k
<= INLINE_STRING_MAX
) {
2207 /* Everything else copy by reference */
2209 c
= malloc0(MAX(sizeof(JsonVariant
),
2210 offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*)));
2216 c
->is_reference
= true;
2217 c
->reference
= json_variant_ref(json_variant_formalize(v
));
2223 c
= malloc0(MAX(sizeof(JsonVariant
),
2224 offsetof(JsonVariant
, value
) + k
));
2231 memcpy_safe(&c
->value
, source
, k
);
2233 json_variant_propagate_sensitive(v
, c
);
2239 static bool json_single_ref(JsonVariant
*v
) {
2241 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
2243 if (!json_variant_is_regular(v
))
2247 return json_single_ref(v
->parent
);
2249 assert(v
->n_ref
> 0);
2250 return v
->n_ref
== 1;
2253 static int json_variant_set_source(JsonVariant
**v
, JsonSource
*source
, unsigned line
, unsigned column
) {
2259 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole referencer of
2260 * the object. If not, allocates a new object, possibly a surrogate for the original one */
2265 if (source
&& line
> source
->max_line
)
2266 source
->max_line
= line
;
2267 if (source
&& column
> source
->max_column
)
2268 source
->max_column
= column
;
2270 if (!json_variant_is_regular(*v
)) {
2272 if (!source
&& line
== 0 && column
== 0)
2276 if (json_source_equal((*v
)->source
, source
) &&
2277 (*v
)->line
== line
&&
2278 (*v
)->column
== column
)
2281 if (json_single_ref(*v
)) { /* Sole reference? */
2282 json_source_unref((*v
)->source
);
2283 (*v
)->source
= json_source_ref(source
);
2285 (*v
)->column
= column
;
2290 r
= json_variant_copy(&w
, *v
);
2294 assert(json_variant_is_regular(w
));
2295 assert(!w
->is_embedded
);
2296 assert(w
->n_ref
== 1);
2299 w
->source
= json_source_ref(source
);
2303 json_variant_unref(*v
);
2309 static void inc_lines_columns(unsigned *line
, unsigned *column
, const char *s
, size_t n
) {
2312 assert(s
|| n
== 0);
2318 } else if ((signed char) *s
>= 0 && *s
< 127) /* Process ASCII chars quickly */
2323 w
= utf8_encoded_valid_unichar(s
, n
);
2324 if (w
< 0) /* count invalid unichars as normal characters */
2326 else if ((size_t) w
> n
) /* never read more than the specified number of characters */
2341 static int unhex_ucs2(const char *c
, uint16_t *ret
) {
2348 aa
= unhexchar(c
[0]);
2352 bb
= unhexchar(c
[1]);
2356 cc
= unhexchar(c
[2]);
2360 dd
= unhexchar(c
[3]);
2364 x
= ((uint16_t) aa
<< 12) |
2365 ((uint16_t) bb
<< 8) |
2366 ((uint16_t) cc
<< 4) |
2377 static int json_parse_string(const char **p
, char **ret
) {
2378 _cleanup_free_
char *s
= NULL
;
2379 size_t n
= 0, allocated
= 0;
2400 /* Check for control characters 0x00..0x1f */
2401 if (*c
> 0 && *c
< ' ')
2404 /* Check for control character 0x7f */
2419 return JSON_TOKEN_STRING
;
2429 if (IN_SET(*c
, '"', '\\', '/'))
2441 else if (*c
== 'u') {
2445 r
= unhex_ucs2(c
+ 1, &x
);
2451 if (!GREEDY_REALLOC(s
, allocated
, n
+ 5))
2454 if (!utf16_is_surrogate(x
))
2455 n
+= utf8_encode_unichar(s
+ n
, (char32_t
) x
);
2456 else if (utf16_is_trailing_surrogate(x
))
2461 if (c
[0] != '\\' || c
[1] != 'u')
2464 r
= unhex_ucs2(c
+ 2, &y
);
2470 if (!utf16_is_trailing_surrogate(y
))
2473 n
+= utf8_encode_unichar(s
+ n
, utf16_surrogate_pair_to_unichar(x
, y
));
2480 if (!GREEDY_REALLOC(s
, allocated
, n
+ 2))
2488 len
= utf8_encoded_valid_unichar(c
, (size_t) -1);
2492 if (!GREEDY_REALLOC(s
, allocated
, n
+ len
+ 1))
2495 memcpy(s
+ n
, c
, len
);
2501 static int json_parse_number(const char **p
, JsonValue
*ret
) {
2502 bool negative
= false, exponent_negative
= false, is_real
= false;
2503 long double x
= 0.0, y
= 0.0, exponent
= 0.0, shift
= 1.0;
2522 if (!strchr("123456789", *c
) || *c
== 0)
2529 if (i
< INTMAX_MIN
/ 10) /* overflow */
2532 intmax_t t
= 10 * i
;
2534 if (t
< INTMAX_MIN
+ (*c
- '0')) /* overflow */
2540 if (u
> UINTMAX_MAX
/ 10) /* overflow */
2543 uintmax_t t
= 10 * u
;
2545 if (t
> UINTMAX_MAX
- (*c
- '0')) /* overflow */
2553 x
= 10.0 * x
+ (*c
- '0');
2556 } while (strchr("0123456789", *c
) && *c
!= 0);
2563 if (!strchr("0123456789", *c
) || *c
== 0)
2567 y
= 10.0 * y
+ (*c
- '0');
2568 shift
= 10.0 * shift
;
2570 } while (strchr("0123456789", *c
) && *c
!= 0);
2573 if (IN_SET(*c
, 'e', 'E')) {
2578 exponent_negative
= true;
2580 } else if (*c
== '+')
2583 if (!strchr("0123456789", *c
) || *c
== 0)
2587 exponent
= 10.0 * exponent
+ (*c
- '0');
2589 } while (strchr("0123456789", *c
) && *c
!= 0);
2595 ret
->real
= ((negative
? -1.0 : 1.0) * (x
+ (y
/ shift
))) * exp10l((exponent_negative
? -1.0 : 1.0) * exponent
);
2596 return JSON_TOKEN_REAL
;
2597 } else if (negative
) {
2599 return JSON_TOKEN_INTEGER
;
2602 return JSON_TOKEN_UNSIGNED
;
2609 JsonValue
*ret_value
,
2610 unsigned *ret_line
, /* 'ret_line' returns the line at the beginning of this token */
2611 unsigned *ret_column
,
2613 unsigned *line
, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2616 unsigned start_line
, start_column
;
2617 const char *start
, *c
;
2637 t
= PTR_TO_INT(*state
);
2638 if (t
== STATE_NULL
) {
2644 /* Skip over the whitespace */
2645 n
= strspn(*p
, WHITESPACE
);
2646 inc_lines_columns(line
, column
, *p
, n
);
2649 /* Remember where we started processing this token */
2652 start_column
= *column
;
2656 *ret_value
= JSON_VALUE_NULL
;
2667 *state
= INT_TO_PTR(STATE_VALUE
);
2668 r
= JSON_TOKEN_OBJECT_OPEN
;
2671 } else if (*c
== '}') {
2673 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2674 r
= JSON_TOKEN_OBJECT_CLOSE
;
2677 } else if (*c
== '[') {
2679 *state
= INT_TO_PTR(STATE_VALUE
);
2680 r
= JSON_TOKEN_ARRAY_OPEN
;
2683 } else if (*c
== ']') {
2685 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2686 r
= JSON_TOKEN_ARRAY_CLOSE
;
2689 } else if (*c
== '"') {
2691 r
= json_parse_string(&c
, ret_string
);
2695 *ret_value
= JSON_VALUE_NULL
;
2696 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2699 } else if (strchr("-0123456789", *c
)) {
2701 r
= json_parse_number(&c
, ret_value
);
2706 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2709 } else if (startswith(c
, "true")) {
2711 ret_value
->boolean
= true;
2713 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2714 r
= JSON_TOKEN_BOOLEAN
;
2717 } else if (startswith(c
, "false")) {
2719 ret_value
->boolean
= false;
2721 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2722 r
= JSON_TOKEN_BOOLEAN
;
2725 } else if (startswith(c
, "null")) {
2727 *ret_value
= JSON_VALUE_NULL
;
2729 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2730 r
= JSON_TOKEN_NULL
;
2737 case STATE_VALUE_POST
:
2741 *state
= INT_TO_PTR(STATE_VALUE
);
2742 r
= JSON_TOKEN_COLON
;
2745 } else if (*c
== ',') {
2747 *state
= INT_TO_PTR(STATE_VALUE
);
2748 r
= JSON_TOKEN_COMMA
;
2751 } else if (*c
== '}') {
2753 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2754 r
= JSON_TOKEN_OBJECT_CLOSE
;
2757 } else if (*c
== ']') {
2759 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2760 r
= JSON_TOKEN_ARRAY_CLOSE
;
2767 assert_not_reached("Unexpected tokenizer state");
2772 *ret_value
= JSON_VALUE_NULL
;
2775 inc_lines_columns(line
, column
, start
, c
- start
);
2778 *ret_line
= start_line
;
2779 *ret_column
= start_column
;
2784 typedef enum JsonExpect
{
2785 /* The following values are used by json_parse() */
2788 EXPECT_OBJECT_FIRST_KEY
,
2789 EXPECT_OBJECT_NEXT_KEY
,
2790 EXPECT_OBJECT_COLON
,
2791 EXPECT_OBJECT_VALUE
,
2792 EXPECT_OBJECT_COMMA
,
2793 EXPECT_ARRAY_FIRST_ELEMENT
,
2794 EXPECT_ARRAY_NEXT_ELEMENT
,
2797 /* And these are used by json_build() */
2798 EXPECT_ARRAY_ELEMENT
,
2802 typedef struct JsonStack
{
2804 JsonVariant
**elements
;
2805 size_t n_elements
, n_elements_allocated
;
2806 unsigned line_before
;
2807 unsigned column_before
;
2808 size_t n_suppress
; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2811 static void json_stack_release(JsonStack
*s
) {
2814 json_variant_unref_many(s
->elements
, s
->n_elements
);
2815 s
->elements
= mfree(s
->elements
);
2818 static int json_parse_internal(
2821 JsonParseFlags flags
,
2825 bool continue_end
) {
2827 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2828 unsigned line_buffer
= 0, column_buffer
= 0;
2829 void *tokenizer_state
= NULL
;
2830 JsonStack
*stack
= NULL
;
2834 assert_return(input
, -EINVAL
);
2835 assert_return(ret
, -EINVAL
);
2839 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2842 stack
[0] = (JsonStack
) {
2843 .expect
= EXPECT_TOPLEVEL
,
2847 line
= &line_buffer
;
2849 column
= &column_buffer
;
2852 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
2853 _cleanup_free_
char *string
= NULL
;
2854 unsigned line_token
, column_token
;
2859 assert(n_stack
> 0);
2860 current
= stack
+ n_stack
- 1;
2862 if (continue_end
&& current
->expect
== EXPECT_END
)
2865 token
= json_tokenize(&p
, &string
, &value
, &line_token
, &column_token
, &tokenizer_state
, line
, column
);
2873 case JSON_TOKEN_END
:
2874 if (current
->expect
!= EXPECT_END
) {
2879 assert(current
->n_elements
== 1);
2880 assert(n_stack
== 1);
2883 case JSON_TOKEN_COLON
:
2885 if (current
->expect
!= EXPECT_OBJECT_COLON
) {
2890 current
->expect
= EXPECT_OBJECT_VALUE
;
2893 case JSON_TOKEN_COMMA
:
2895 if (current
->expect
== EXPECT_OBJECT_COMMA
)
2896 current
->expect
= EXPECT_OBJECT_NEXT_KEY
;
2897 else if (current
->expect
== EXPECT_ARRAY_COMMA
)
2898 current
->expect
= EXPECT_ARRAY_NEXT_ELEMENT
;
2906 case JSON_TOKEN_OBJECT_OPEN
:
2908 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2913 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2917 current
= stack
+ n_stack
- 1;
2919 /* Prepare the expect for when we return from the child */
2920 if (current
->expect
== EXPECT_TOPLEVEL
)
2921 current
->expect
= EXPECT_END
;
2922 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2923 current
->expect
= EXPECT_OBJECT_COMMA
;
2925 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2926 current
->expect
= EXPECT_ARRAY_COMMA
;
2929 stack
[n_stack
++] = (JsonStack
) {
2930 .expect
= EXPECT_OBJECT_FIRST_KEY
,
2931 .line_before
= line_token
,
2932 .column_before
= column_token
,
2935 current
= stack
+ n_stack
- 1;
2938 case JSON_TOKEN_OBJECT_CLOSE
:
2939 if (!IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_COMMA
)) {
2944 assert(n_stack
> 1);
2946 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
2950 line_token
= current
->line_before
;
2951 column_token
= current
->column_before
;
2953 json_stack_release(current
);
2954 n_stack
--, current
--;
2958 case JSON_TOKEN_ARRAY_OPEN
:
2959 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2964 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2968 current
= stack
+ n_stack
- 1;
2970 /* Prepare the expect for when we return from the child */
2971 if (current
->expect
== EXPECT_TOPLEVEL
)
2972 current
->expect
= EXPECT_END
;
2973 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2974 current
->expect
= EXPECT_OBJECT_COMMA
;
2976 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2977 current
->expect
= EXPECT_ARRAY_COMMA
;
2980 stack
[n_stack
++] = (JsonStack
) {
2981 .expect
= EXPECT_ARRAY_FIRST_ELEMENT
,
2982 .line_before
= line_token
,
2983 .column_before
= column_token
,
2988 case JSON_TOKEN_ARRAY_CLOSE
:
2989 if (!IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_COMMA
)) {
2994 assert(n_stack
> 1);
2996 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
3000 line_token
= current
->line_before
;
3001 column_token
= current
->column_before
;
3003 json_stack_release(current
);
3004 n_stack
--, current
--;
3007 case JSON_TOKEN_STRING
:
3008 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
)) {
3013 r
= json_variant_new_string(&add
, string
);
3017 if (current
->expect
== EXPECT_TOPLEVEL
)
3018 current
->expect
= EXPECT_END
;
3019 else if (IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_NEXT_KEY
))
3020 current
->expect
= EXPECT_OBJECT_COLON
;
3021 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3022 current
->expect
= EXPECT_OBJECT_COMMA
;
3024 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3025 current
->expect
= EXPECT_ARRAY_COMMA
;
3030 case JSON_TOKEN_REAL
:
3031 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3036 r
= json_variant_new_real(&add
, value
.real
);
3040 if (current
->expect
== EXPECT_TOPLEVEL
)
3041 current
->expect
= EXPECT_END
;
3042 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3043 current
->expect
= EXPECT_OBJECT_COMMA
;
3045 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3046 current
->expect
= EXPECT_ARRAY_COMMA
;
3051 case JSON_TOKEN_INTEGER
:
3052 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3057 r
= json_variant_new_integer(&add
, value
.integer
);
3061 if (current
->expect
== EXPECT_TOPLEVEL
)
3062 current
->expect
= EXPECT_END
;
3063 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3064 current
->expect
= EXPECT_OBJECT_COMMA
;
3066 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3067 current
->expect
= EXPECT_ARRAY_COMMA
;
3072 case JSON_TOKEN_UNSIGNED
:
3073 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3078 r
= json_variant_new_unsigned(&add
, value
.unsig
);
3082 if (current
->expect
== EXPECT_TOPLEVEL
)
3083 current
->expect
= EXPECT_END
;
3084 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3085 current
->expect
= EXPECT_OBJECT_COMMA
;
3087 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3088 current
->expect
= EXPECT_ARRAY_COMMA
;
3093 case JSON_TOKEN_BOOLEAN
:
3094 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3099 r
= json_variant_new_boolean(&add
, value
.boolean
);
3103 if (current
->expect
== EXPECT_TOPLEVEL
)
3104 current
->expect
= EXPECT_END
;
3105 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3106 current
->expect
= EXPECT_OBJECT_COMMA
;
3108 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3109 current
->expect
= EXPECT_ARRAY_COMMA
;
3114 case JSON_TOKEN_NULL
:
3115 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3120 r
= json_variant_new_null(&add
);
3124 if (current
->expect
== EXPECT_TOPLEVEL
)
3125 current
->expect
= EXPECT_END
;
3126 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3127 current
->expect
= EXPECT_OBJECT_COMMA
;
3129 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3130 current
->expect
= EXPECT_ARRAY_COMMA
;
3136 assert_not_reached("Unexpected token");
3140 /* If we are asked to make this parsed object sensitive, then let's apply this
3141 * immediately after allocating each variant, so that when we abort half-way
3142 * everything we already allocated that is then freed is correctly marked. */
3143 if (FLAGS_SET(flags
, JSON_PARSE_SENSITIVE
))
3144 json_variant_sensitive(add
);
3146 (void) json_variant_set_source(&add
, source
, line_token
, column_token
);
3148 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3153 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3158 assert(n_stack
== 1);
3159 assert(stack
[0].n_elements
== 1);
3161 *ret
= json_variant_ref(stack
[0].elements
[0]);
3166 for (i
= 0; i
< n_stack
; i
++)
3167 json_stack_release(stack
+ i
);
3174 int json_parse(const char *input
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3175 return json_parse_internal(&input
, NULL
, flags
, ret
, ret_line
, ret_column
, false);
3178 int json_parse_continue(const char **p
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3179 return json_parse_internal(p
, NULL
, flags
, ret
, ret_line
, ret_column
, true);
3182 int json_parse_file_at(FILE *f
, int dir_fd
, const char *path
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3183 _cleanup_(json_source_unrefp
) JsonSource
*source
= NULL
;
3184 _cleanup_free_
char *text
= NULL
;
3189 r
= read_full_stream(f
, &text
, NULL
);
3191 r
= read_full_file_full(dir_fd
, path
, 0, &text
, NULL
);
3198 source
= json_source_new(path
);
3204 return json_parse_internal(&p
, source
, flags
, ret
, ret_line
, ret_column
, false);
3207 int json_buildv(JsonVariant
**ret
, va_list ap
) {
3208 JsonStack
*stack
= NULL
;
3209 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
3212 assert_return(ret
, -EINVAL
);
3214 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
3217 stack
[0] = (JsonStack
) {
3218 .expect
= EXPECT_TOPLEVEL
,
3222 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
3223 size_t n_subtract
= 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
3224 * have been added to the current variant */
3228 assert(n_stack
> 0);
3229 current
= stack
+ n_stack
- 1;
3231 if (current
->expect
== EXPECT_END
)
3234 command
= va_arg(ap
, int);
3238 case _JSON_BUILD_STRING
: {
3241 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3246 p
= va_arg(ap
, const char *);
3248 if (current
->n_suppress
== 0) {
3249 r
= json_variant_new_string(&add
, p
);
3256 if (current
->expect
== EXPECT_TOPLEVEL
)
3257 current
->expect
= EXPECT_END
;
3258 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3259 current
->expect
= EXPECT_OBJECT_KEY
;
3261 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3266 case _JSON_BUILD_INTEGER
: {
3269 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3274 j
= va_arg(ap
, intmax_t);
3276 if (current
->n_suppress
== 0) {
3277 r
= json_variant_new_integer(&add
, j
);
3284 if (current
->expect
== EXPECT_TOPLEVEL
)
3285 current
->expect
= EXPECT_END
;
3286 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3287 current
->expect
= EXPECT_OBJECT_KEY
;
3289 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3294 case _JSON_BUILD_UNSIGNED
: {
3297 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3302 j
= va_arg(ap
, uintmax_t);
3304 if (current
->n_suppress
== 0) {
3305 r
= json_variant_new_unsigned(&add
, j
);
3312 if (current
->expect
== EXPECT_TOPLEVEL
)
3313 current
->expect
= EXPECT_END
;
3314 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3315 current
->expect
= EXPECT_OBJECT_KEY
;
3317 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3322 case _JSON_BUILD_REAL
: {
3325 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3330 d
= va_arg(ap
, long double);
3332 if (current
->n_suppress
== 0) {
3333 r
= json_variant_new_real(&add
, d
);
3340 if (current
->expect
== EXPECT_TOPLEVEL
)
3341 current
->expect
= EXPECT_END
;
3342 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3343 current
->expect
= EXPECT_OBJECT_KEY
;
3345 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3350 case _JSON_BUILD_BOOLEAN
: {
3353 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3358 b
= va_arg(ap
, int);
3360 if (current
->n_suppress
== 0) {
3361 r
= json_variant_new_boolean(&add
, b
);
3368 if (current
->expect
== EXPECT_TOPLEVEL
)
3369 current
->expect
= EXPECT_END
;
3370 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3371 current
->expect
= EXPECT_OBJECT_KEY
;
3373 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3378 case _JSON_BUILD_NULL
:
3380 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3385 if (current
->n_suppress
== 0) {
3386 r
= json_variant_new_null(&add
);
3393 if (current
->expect
== EXPECT_TOPLEVEL
)
3394 current
->expect
= EXPECT_END
;
3395 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3396 current
->expect
= EXPECT_OBJECT_KEY
;
3398 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3402 case _JSON_BUILD_VARIANT
:
3404 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3409 /* Note that we don't care for current->n_suppress here, after all the variant is already
3410 * allocated anyway... */
3411 add
= va_arg(ap
, JsonVariant
*);
3413 add
= JSON_VARIANT_MAGIC_NULL
;
3415 json_variant_ref(add
);
3419 if (current
->expect
== EXPECT_TOPLEVEL
)
3420 current
->expect
= EXPECT_END
;
3421 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3422 current
->expect
= EXPECT_OBJECT_KEY
;
3424 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3428 case _JSON_BUILD_VARIANT_ARRAY
: {
3429 JsonVariant
**array
;
3432 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3437 array
= va_arg(ap
, JsonVariant
**);
3438 n
= va_arg(ap
, size_t);
3440 if (current
->n_suppress
== 0) {
3441 r
= json_variant_new_array(&add
, array
, n
);
3448 if (current
->expect
== EXPECT_TOPLEVEL
)
3449 current
->expect
= EXPECT_END
;
3450 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3451 current
->expect
= EXPECT_OBJECT_KEY
;
3453 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3458 case _JSON_BUILD_LITERAL
: {
3461 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3466 l
= va_arg(ap
, const char *);
3469 /* Note that we don't care for current->n_suppress here, we should generate parsing
3470 * errors even in suppressed object properties */
3472 r
= json_parse(l
, 0, &add
, NULL
, NULL
);
3476 add
= JSON_VARIANT_MAGIC_NULL
;
3480 if (current
->expect
== EXPECT_TOPLEVEL
)
3481 current
->expect
= EXPECT_END
;
3482 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3483 current
->expect
= EXPECT_OBJECT_KEY
;
3485 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3490 case _JSON_BUILD_ARRAY_BEGIN
:
3492 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3497 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
3501 current
= stack
+ n_stack
- 1;
3503 if (current
->expect
== EXPECT_TOPLEVEL
)
3504 current
->expect
= EXPECT_END
;
3505 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3506 current
->expect
= EXPECT_OBJECT_KEY
;
3508 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3510 stack
[n_stack
++] = (JsonStack
) {
3511 .expect
= EXPECT_ARRAY_ELEMENT
,
3512 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3513 * new array, then we should
3514 * also suppress all array
3520 case _JSON_BUILD_ARRAY_END
:
3521 if (current
->expect
!= EXPECT_ARRAY_ELEMENT
) {
3526 assert(n_stack
> 1);
3528 if (current
->n_suppress
== 0) {
3529 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
3536 json_stack_release(current
);
3537 n_stack
--, current
--;
3541 case _JSON_BUILD_STRV
: {
3544 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3549 l
= va_arg(ap
, char **);
3551 if (current
->n_suppress
== 0) {
3552 r
= json_variant_new_array_strv(&add
, l
);
3559 if (current
->expect
== EXPECT_TOPLEVEL
)
3560 current
->expect
= EXPECT_END
;
3561 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3562 current
->expect
= EXPECT_OBJECT_KEY
;
3564 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3569 case _JSON_BUILD_BASE64
: {
3573 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3578 p
= va_arg(ap
, const void *);
3579 n
= va_arg(ap
, size_t);
3581 if (current
->n_suppress
== 0) {
3582 r
= json_variant_new_base64(&add
, p
, n
);
3589 if (current
->expect
== EXPECT_TOPLEVEL
)
3590 current
->expect
= EXPECT_END
;
3591 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3592 current
->expect
= EXPECT_OBJECT_KEY
;
3594 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3599 case _JSON_BUILD_ID128
: {
3602 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3607 id
= va_arg(ap
, sd_id128_t
);
3609 if (current
->n_suppress
== 0) {
3610 r
= json_variant_new_id128(&add
, id
);
3617 if (current
->expect
== EXPECT_TOPLEVEL
)
3618 current
->expect
= EXPECT_END
;
3619 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3620 current
->expect
= EXPECT_OBJECT_KEY
;
3622 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3627 case _JSON_BUILD_OBJECT_BEGIN
:
3629 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3634 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
3638 current
= stack
+ n_stack
- 1;
3640 if (current
->expect
== EXPECT_TOPLEVEL
)
3641 current
->expect
= EXPECT_END
;
3642 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3643 current
->expect
= EXPECT_OBJECT_KEY
;
3645 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3647 stack
[n_stack
++] = (JsonStack
) {
3648 .expect
= EXPECT_OBJECT_KEY
,
3649 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3650 * new object, then we should
3651 * also suppress all object
3657 case _JSON_BUILD_OBJECT_END
:
3659 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3664 assert(n_stack
> 1);
3666 if (current
->n_suppress
== 0) {
3667 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
3674 json_stack_release(current
);
3675 n_stack
--, current
--;
3679 case _JSON_BUILD_PAIR
: {
3682 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3687 n
= va_arg(ap
, const char *);
3689 if (current
->n_suppress
== 0) {
3690 r
= json_variant_new_string(&add
, n
);
3697 current
->expect
= EXPECT_OBJECT_VALUE
;
3701 case _JSON_BUILD_PAIR_CONDITION
: {
3705 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3710 b
= va_arg(ap
, int);
3711 n
= va_arg(ap
, const char *);
3713 if (b
&& current
->n_suppress
== 0) {
3714 r
= json_variant_new_string(&add
, n
);
3719 n_subtract
= 1; /* we generated one item */
3721 if (!b
&& current
->n_suppress
!= (size_t) -1)
3722 current
->n_suppress
+= 2; /* Suppress this one and the next item */
3724 current
->expect
= EXPECT_OBJECT_VALUE
;
3728 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3729 if (add
&& current
->n_suppress
== 0) {
3730 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3735 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3738 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3739 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3740 * on this stack level */
3741 if (current
->n_suppress
!= (size_t) -1) {
3742 if (current
->n_suppress
<= n_subtract
) /* Saturated */
3743 current
->n_suppress
= 0;
3745 current
->n_suppress
-= n_subtract
;
3750 assert(n_stack
== 1);
3751 assert(stack
[0].n_elements
== 1);
3753 *ret
= json_variant_ref(stack
[0].elements
[0]);
3757 for (i
= 0; i
< n_stack
; i
++)
3758 json_stack_release(stack
+ i
);
3765 int json_build(JsonVariant
**ret
, ...) {
3770 r
= json_buildv(ret
, ap
);
3776 int json_log_internal(
3777 JsonVariant
*variant
,
3783 const char *format
, ...) {
3787 unsigned source_line
, source_column
;
3788 char buffer
[LINE_MAX
];
3793 errno
= ERRNO_VALUE(error
);
3795 va_start(ap
, format
);
3796 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
3800 r
= json_variant_get_source(variant
, &source
, &source_line
, &source_column
);
3809 if (source
&& source_line
> 0 && source_column
> 0)
3810 return log_struct_internal(
3811 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3814 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3815 "CONFIG_FILE=%s", source
,
3816 "CONFIG_LINE=%u", source_line
,
3817 "CONFIG_COLUMN=%u", source_column
,
3818 LOG_MESSAGE("%s:%u:%u: %s", source
, source_line
, source_column
, buffer
),
3821 return log_struct_internal(
3822 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3825 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3826 LOG_MESSAGE("%s", buffer
),
3830 int json_dispatch(JsonVariant
*v
, const JsonDispatch table
[], JsonDispatchCallback bad
, JsonDispatchFlags flags
, void *userdata
) {
3831 const JsonDispatch
*p
;
3836 if (!json_variant_is_object(v
)) {
3837 json_log(v
, flags
, 0, "JSON variant is not an object.");
3839 if (flags
& JSON_PERMISSIVE
)
3845 for (p
= table
, m
= 0; p
->name
; p
++)
3848 found
= newa0(bool, m
);
3850 n
= json_variant_elements(v
);
3851 for (i
= 0; i
< n
; i
+= 2) {
3852 JsonVariant
*key
, *value
;
3854 assert_se(key
= json_variant_by_index(v
, i
));
3855 assert_se(value
= json_variant_by_index(v
, i
+1));
3857 for (p
= table
; p
->name
; p
++)
3858 if (p
->name
== (const char*) -1 ||
3859 streq_ptr(json_variant_string(key
), p
->name
))
3862 if (p
->name
) { /* Found a matching entry! :-) */
3863 JsonDispatchFlags merged_flags
;
3865 merged_flags
= flags
| p
->flags
;
3867 if (p
->type
!= _JSON_VARIANT_TYPE_INVALID
&&
3868 !json_variant_has_type(value
, p
->type
)) {
3870 json_log(value
, merged_flags
, 0,
3871 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key
),
3872 json_variant_type_to_string(json_variant_type(value
)), json_variant_type_to_string(p
->type
));
3874 if (merged_flags
& JSON_PERMISSIVE
)
3880 if (found
[p
-table
]) {
3881 json_log(value
, merged_flags
, 0, "Duplicate object field '%s'.", json_variant_string(key
));
3883 if (merged_flags
& JSON_PERMISSIVE
)
3889 found
[p
-table
] = true;
3892 r
= p
->callback(json_variant_string(key
), value
, merged_flags
, (uint8_t*) userdata
+ p
->offset
);
3894 if (merged_flags
& JSON_PERMISSIVE
)
3903 } else { /* Didn't find a matching entry! :-( */
3906 r
= bad(json_variant_string(key
), value
, flags
, userdata
);
3908 if (flags
& JSON_PERMISSIVE
)
3916 json_log(value
, flags
, 0, "Unexpected object field '%s'.", json_variant_string(key
));
3918 if (flags
& JSON_PERMISSIVE
)
3921 return -EADDRNOTAVAIL
;
3926 for (p
= table
; p
->name
; p
++) {
3927 JsonDispatchFlags merged_flags
= p
->flags
| flags
;
3929 if ((merged_flags
& JSON_MANDATORY
) && !found
[p
-table
]) {
3930 json_log(v
, merged_flags
, 0, "Missing object field '%s'.", p
->name
);
3932 if ((merged_flags
& JSON_PERMISSIVE
))
3942 int json_dispatch_boolean(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3948 if (!json_variant_is_boolean(variant
))
3949 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3951 *b
= json_variant_boolean(variant
);
3955 int json_dispatch_tristate(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3961 if (json_variant_is_null(variant
)) {
3966 if (!json_variant_is_boolean(variant
))
3967 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3969 *b
= json_variant_boolean(variant
);
3973 int json_dispatch_integer(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3974 intmax_t *i
= userdata
;
3979 if (!json_variant_is_integer(variant
))
3980 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3982 *i
= json_variant_integer(variant
);
3986 int json_dispatch_unsigned(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3987 uintmax_t *u
= userdata
;
3992 if (!json_variant_is_unsigned(variant
))
3993 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3995 *u
= json_variant_unsigned(variant
);
3999 int json_dispatch_uint32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4000 uint32_t *u
= userdata
;
4005 if (!json_variant_is_unsigned(variant
))
4006 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
4008 if (json_variant_unsigned(variant
) > UINT32_MAX
)
4009 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
4011 *u
= (uint32_t) json_variant_unsigned(variant
);
4015 int json_dispatch_int32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4016 int32_t *i
= userdata
;
4021 if (!json_variant_is_integer(variant
))
4022 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
4024 if (json_variant_integer(variant
) < INT32_MIN
|| json_variant_integer(variant
) > INT32_MAX
)
4025 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
4027 *i
= (int32_t) json_variant_integer(variant
);
4031 int json_dispatch_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4032 char **s
= userdata
;
4038 if (json_variant_is_null(variant
)) {
4043 if (!json_variant_is_string(variant
))
4044 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
4046 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(variant
)))
4047 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
4049 r
= free_and_strdup(s
, json_variant_string(variant
));
4051 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
4056 int json_dispatch_const_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4057 const char **s
= userdata
;
4062 if (json_variant_is_null(variant
)) {
4067 if (!json_variant_is_string(variant
))
4068 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
4070 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(variant
)))
4071 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
4073 *s
= json_variant_string(variant
);
4077 int json_dispatch_strv(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4078 _cleanup_strv_free_
char **l
= NULL
;
4079 char ***s
= userdata
;
4086 if (json_variant_is_null(variant
)) {
4091 /* Let's be flexible here: accept a single string in place of a single-item array */
4092 if (json_variant_is_string(variant
)) {
4093 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(variant
)))
4094 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
4096 l
= strv_new(json_variant_string(variant
));
4100 strv_free_and_replace(*s
, l
);
4104 if (!json_variant_is_array(variant
))
4105 return json_log(variant
, SYNTHETIC_ERRNO(EINVAL
), flags
, "JSON field '%s' is not an array.", strna(name
));
4107 JSON_VARIANT_ARRAY_FOREACH(e
, variant
) {
4108 if (!json_variant_is_string(e
))
4109 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON array element is not a string.");
4111 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(e
)))
4112 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
4114 r
= strv_extend(&l
, json_variant_string(e
));
4116 return json_log(e
, flags
, r
, "Failed to append array element: %m");
4119 strv_free_and_replace(*s
, l
);
4123 int json_dispatch_variant(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4124 JsonVariant
**p
= userdata
;
4129 json_variant_unref(*p
);
4130 *p
= json_variant_ref(variant
);
4135 int json_dispatch_uid_gid(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4136 uid_t
*uid
= userdata
;
4139 assert_cc(sizeof(uid_t
) == sizeof(uint32_t));
4140 assert_cc(sizeof(gid_t
) == sizeof(uint32_t));
4142 DISABLE_WARNING_TYPE_LIMITS
;
4143 assert_cc(((uid_t
) -1 < (uid_t
) 0) == ((gid_t
) -1 < (gid_t
) 0));
4146 if (json_variant_is_null(variant
)) {
4151 if (!json_variant_is_unsigned(variant
))
4152 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a integer.", strna(name
));
4154 k
= json_variant_unsigned(variant
);
4155 if (k
> UINT32_MAX
|| !uid_is_valid(k
))
4156 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a valid UID/GID.", strna(name
));
4162 int json_dispatch_user_group_name(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4163 char **s
= userdata
;
4167 if (json_variant_is_null(variant
)) {
4172 if (!json_variant_is_string(variant
))
4173 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
4175 n
= json_variant_string(variant
);
4176 if (!valid_user_group_name(n
, FLAGS_SET(flags
, JSON_RELAX
) ? VALID_USER_RELAX
: 0))
4177 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a valid user/group name.", strna(name
));
4179 r
= free_and_strdup(s
, n
);
4181 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
4186 int json_dispatch_id128(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4187 sd_id128_t
*uuid
= userdata
;
4190 if (json_variant_is_null(variant
)) {
4191 *uuid
= SD_ID128_NULL
;
4195 if (!json_variant_is_string(variant
))
4196 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
4198 r
= sd_id128_from_string(json_variant_string(variant
), uuid
);
4200 return json_log(variant
, flags
, r
, "JSON field '%s' is not a valid UID.", strna(name
));
4205 int json_dispatch_unsupported(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
4206 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not allowed in this object.", strna(name
));
4209 static int json_cmp_strings(const void *x
, const void *y
) {
4210 JsonVariant
*const *a
= x
, *const *b
= y
;
4212 if (!json_variant_is_string(*a
) || !json_variant_is_string(*b
))
4215 return strcmp(json_variant_string(*a
), json_variant_string(*b
));
4218 int json_variant_sort(JsonVariant
**v
) {
4219 _cleanup_free_ JsonVariant
**a
= NULL
;
4220 JsonVariant
*n
= NULL
;
4226 if (json_variant_is_sorted(*v
))
4229 if (!json_variant_is_object(*v
))
4230 return -EMEDIUMTYPE
;
4232 /* Sorts they key/value pairs in an object variant */
4234 m
= json_variant_elements(*v
);
4235 a
= new(JsonVariant
*, m
);
4239 for (i
= 0; i
< m
; i
++)
4240 a
[i
] = json_variant_by_index(*v
, i
);
4242 qsort(a
, m
/2, sizeof(JsonVariant
*)*2, json_cmp_strings
);
4244 r
= json_variant_new_object(&n
, a
, m
);
4248 json_variant_propagate_sensitive(*v
, n
);
4250 if (!n
->sorted
) /* Check if this worked. This will fail if there are multiple identical keys used. */
4253 json_variant_unref(*v
);
4259 int json_variant_normalize(JsonVariant
**v
) {
4260 _cleanup_free_ JsonVariant
**a
= NULL
;
4261 JsonVariant
*n
= NULL
;
4267 if (json_variant_is_normalized(*v
))
4270 if (!json_variant_is_object(*v
) && !json_variant_is_array(*v
))
4271 return -EMEDIUMTYPE
;
4273 /* Sorts the key/value pairs in an object variant anywhere down the tree in the specified variant */
4275 m
= json_variant_elements(*v
);
4276 a
= new(JsonVariant
*, m
);
4280 for (i
= 0; i
< m
; i
++) {
4281 a
[i
] = json_variant_ref(json_variant_by_index(*v
, i
));
4283 r
= json_variant_normalize(a
+ i
);
4288 qsort(a
, m
/2, sizeof(JsonVariant
*)*2, json_cmp_strings
);
4290 if (json_variant_is_object(*v
))
4291 r
= json_variant_new_object(&n
, a
, m
);
4293 assert(json_variant_is_array(*v
));
4294 r
= json_variant_new_array(&n
, a
, m
);
4299 json_variant_propagate_sensitive(*v
, n
);
4301 if (!n
->normalized
) { /* Let's see if normalization worked. It will fail if there are multiple
4302 * identical keys used in the same object anywhere, or if there are floating
4303 * point numbers used (see below) */
4308 json_variant_unref(*v
);
4314 for (j
= 0; j
< i
; j
++)
4315 json_variant_unref(a
[j
]);
4320 bool json_variant_is_normalized(JsonVariant
*v
) {
4322 /* For now, let's consider anything containing numbers not expressible as integers as
4323 * non-normalized. That's because we cannot sensibly compare them due to accuracy issues, nor even
4324 * store them if they are too large. */
4325 if (json_variant_is_real(v
) && !json_variant_is_integer(v
) && !json_variant_is_unsigned(v
))
4328 /* The concept only applies to variants that include other variants, i.e. objects and arrays. All
4329 * others are normalized anyway. */
4330 if (!json_variant_is_object(v
) && !json_variant_is_array(v
))
4333 /* Empty objects/arrays don't include any other variant, hence are always normalized too */
4334 if (json_variant_elements(v
) == 0)
4337 return v
->normalized
; /* For everything else there's an explicit boolean we maintain */
4340 bool json_variant_is_sorted(JsonVariant
*v
) {
4342 /* Returns true if all key/value pairs of an object are properly sorted. Note that this only applies
4343 * to objects, not arrays. */
4345 if (!json_variant_is_object(v
))
4347 if (json_variant_elements(v
) <= 1)
4353 int json_variant_unbase64(JsonVariant
*v
, void **ret
, size_t *ret_size
) {
4355 if (!json_variant_is_string(v
))
4358 return unbase64mem(json_variant_string(v
), (size_t) -1, ret
, ret_size
);
4361 static const char* const json_variant_type_table
[_JSON_VARIANT_TYPE_MAX
] = {
4362 [JSON_VARIANT_STRING
] = "string",
4363 [JSON_VARIANT_INTEGER
] = "integer",
4364 [JSON_VARIANT_UNSIGNED
] = "unsigned",
4365 [JSON_VARIANT_REAL
] = "real",
4366 [JSON_VARIANT_NUMBER
] = "number",
4367 [JSON_VARIANT_BOOLEAN
] = "boolean",
4368 [JSON_VARIANT_ARRAY
] = "array",
4369 [JSON_VARIANT_OBJECT
] = "object",
4370 [JSON_VARIANT_NULL
] = "null",
4373 DEFINE_STRING_TABLE_LOOKUP(json_variant_type
, JsonVariantType
);