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"
28 /* Refuse putting together variants with a larger depth than 4K by default (as a protection against overflowing stacks
29 * if code processes JSON objects recursively. Note that we store the depth in an uint16_t, hence make sure this
31 * The value was 16k, but it was discovered to be too high on llvm/x86-64. See also the issue #10738. */
32 #define DEPTH_MAX (4U*1024U)
33 assert_cc(DEPTH_MAX
<= UINT16_MAX
);
35 typedef struct JsonSource
{
36 /* When we parse from a file or similar, encodes the filename, to indicate the source of a json variant */
43 /* On x86-64 this whole structure should have a size of 6 * 64 bit = 48 bytes */
46 /* We either maintain a reference counter for this variant itself, or we are embedded into an
47 * array/object, in which case only that surrounding object is ref-counted. (If 'embedded' is false,
51 /* If this JsonVariant is part of an array/object, then this field points to the surrounding
52 * JSON_VARIANT_ARRAY/JSON_VARIANT_OBJECT object. (If 'embedded' is true, see below.) */
56 /* If this was parsed from some file or buffer, this stores where from, as well as the source line/column */
58 unsigned line
, column
;
60 JsonVariantType type
:5;
62 /* A marker whether this variant is embedded into in array/object or not. If true, the 'parent' pointer above
63 * is valid. If false, the 'n_ref' field above is valid instead. */
66 /* In some conditions (for example, if this object is part of an array of strings or objects), we don't store
67 * any data inline, but instead simply reference an external object and act as surrogate of it. In that case
68 * this bool is set, and the external object is referenced through the .reference field below. */
71 /* While comparing two arrays, we use this for marking what we already have seen */
74 /* Erase from memory when freeing */
77 /* If this is an object the fields are strictly ordered by name */
80 /* If in addition to this object all objects referenced by it are also ordered strictly by name */
83 /* The current 'depth' of the JsonVariant, i.e. how many levels of member variants this has */
87 /* For simple types we store the value in-line. */
90 /* For objects and arrays we store the number of elements immediately following */
93 /* If is_reference as indicated above is set, this is where the reference object is actually stored. */
94 JsonVariant
*reference
;
96 /* Strings are placed immediately after the structure. Note that when this is a JsonVariant embedded
97 * into an array we might encode strings up to INLINE_STRING_LENGTH characters directly inside the
98 * element, while longer strings are stored as references. When this object is not embedded into an
99 * array, but stand-alone we allocate the right size for the whole structure, i.e. the array might be
100 * much larger than INLINE_STRING_LENGTH.
102 * Note that because we want to allocate arrays of the JsonVariant structure we specify [0] here,
103 * rather than the prettier []. If we wouldn't, then this char array would have undefined size, and so
104 * would the union and then the struct this is included in. And of structures with undefined size we
105 * can't allocate arrays (at least not easily). */
110 /* Inside string arrays we have a series of JasonVariant structures one after the other. In this case, strings longer
111 * than INLINE_STRING_MAX are stored as references, and all shorter ones inline. (This means — on x86-64 — strings up
112 * to 15 chars are stored within the array elements, and all others in separate allocations) */
113 #define INLINE_STRING_MAX (sizeof(JsonVariant) - offsetof(JsonVariant, string) - 1U)
115 /* Let's make sure this structure isn't increased in size accidentally. This check is only for our most relevant arch
118 assert_cc(sizeof(JsonVariant
) == 48U);
119 assert_cc(INLINE_STRING_MAX
== 15U);
122 static JsonSource
* json_source_new(const char *name
) {
127 s
= malloc(offsetof(JsonSource
, name
) + strlen(name
) + 1);
134 strcpy(s
->name
, name
);
139 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(JsonSource
, json_source
, mfree
);
141 static bool json_source_equal(JsonSource
*a
, JsonSource
*b
) {
148 return streq(a
->name
, b
->name
);
151 DEFINE_TRIVIAL_CLEANUP_FUNC(JsonSource
*, json_source_unref
);
153 /* There are four kind of JsonVariant* pointers:
156 * 2. A 'regular' one, i.e. pointing to malloc() memory
157 * 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.
158 * 4. A 'const string' one, i.e. a pointer to a const string.
160 * The four kinds of pointers can be discerned like this:
162 * Detecting #1 is easy, just compare with NULL. Detecting #3 is similarly easy: all magic pointers are below
163 * _JSON_VARIANT_MAGIC_MAX (which is pretty low, within the first memory page, which is special on Linux and other
164 * 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,
165 * otherwise #4. This makes use of the fact that malloc() will return "maximum aligned" memory, which definitely
166 * means the pointer is even. This means we can use the uneven pointers to reference static strings, as long as we
167 * make sure that all static strings used like this are aligned to 2 (or higher), and that we mask the bit on
168 * access. The JSON_VARIANT_STRING_CONST() macro encodes strings as JsonVariant* pointers, with the bit set. */
170 static bool json_variant_is_magic(const JsonVariant
*v
) {
174 return v
< _JSON_VARIANT_MAGIC_MAX
;
177 static bool json_variant_is_const_string(const JsonVariant
*v
) {
179 if (v
< _JSON_VARIANT_MAGIC_MAX
)
182 /* A proper JsonVariant is aligned to whatever malloc() aligns things too, which is definitely not uneven. We
183 * hence use all uneven pointers as indicators for const strings. */
185 return (((uintptr_t) v
) & 1) != 0;
188 static bool json_variant_is_regular(const JsonVariant
*v
) {
190 if (v
< _JSON_VARIANT_MAGIC_MAX
)
193 return (((uintptr_t) v
) & 1) == 0;
196 static JsonVariant
*json_variant_dereference(JsonVariant
*v
) {
198 /* Recursively dereference variants that are references to other variants */
203 if (!json_variant_is_regular(v
))
206 if (!v
->is_reference
)
209 return json_variant_dereference(v
->reference
);
212 static uint16_t json_variant_depth(JsonVariant
*v
) {
214 v
= json_variant_dereference(v
);
218 if (!json_variant_is_regular(v
))
224 static JsonVariant
*json_variant_formalize(JsonVariant
*v
) {
226 /* Converts json variant pointers to their normalized form, i.e. fully dereferenced and wherever
227 * possible converted to the "magic" version if there is one */
232 v
= json_variant_dereference(v
);
234 switch (json_variant_type(v
)) {
236 case JSON_VARIANT_BOOLEAN
:
237 return json_variant_boolean(v
) ? JSON_VARIANT_MAGIC_TRUE
: JSON_VARIANT_MAGIC_FALSE
;
239 case JSON_VARIANT_NULL
:
240 return JSON_VARIANT_MAGIC_NULL
;
242 case JSON_VARIANT_INTEGER
:
243 return json_variant_integer(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_INTEGER
: v
;
245 case JSON_VARIANT_UNSIGNED
:
246 return json_variant_unsigned(v
) == 0 ? JSON_VARIANT_MAGIC_ZERO_UNSIGNED
: v
;
248 case JSON_VARIANT_REAL
:
249 #pragma GCC diagnostic push
250 #pragma GCC diagnostic ignored "-Wfloat-equal"
251 return json_variant_real(v
) == 0.0 ? JSON_VARIANT_MAGIC_ZERO_REAL
: v
;
252 #pragma GCC diagnostic pop
254 case JSON_VARIANT_STRING
:
255 return isempty(json_variant_string(v
)) ? JSON_VARIANT_MAGIC_EMPTY_STRING
: v
;
257 case JSON_VARIANT_ARRAY
:
258 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_ARRAY
: v
;
260 case JSON_VARIANT_OBJECT
:
261 return json_variant_elements(v
) == 0 ? JSON_VARIANT_MAGIC_EMPTY_OBJECT
: v
;
268 static JsonVariant
*json_variant_conservative_formalize(JsonVariant
*v
) {
270 /* Much like json_variant_formalize(), but won't simplify if the variant has a source/line location attached to
271 * it, in order not to lose context */
276 if (!json_variant_is_regular(v
))
279 if (v
->source
|| v
->line
> 0 || v
->column
> 0)
282 return json_variant_formalize(v
);
285 static int json_variant_new(JsonVariant
**ret
, JsonVariantType type
, size_t space
) {
288 assert_return(ret
, -EINVAL
);
290 v
= malloc0(MAX(sizeof(JsonVariant
),
291 offsetof(JsonVariant
, value
) + space
));
302 int json_variant_new_integer(JsonVariant
**ret
, intmax_t i
) {
306 assert_return(ret
, -EINVAL
);
309 *ret
= JSON_VARIANT_MAGIC_ZERO_INTEGER
;
313 r
= json_variant_new(&v
, JSON_VARIANT_INTEGER
, sizeof(i
));
317 v
->value
.integer
= i
;
323 int json_variant_new_unsigned(JsonVariant
**ret
, uintmax_t u
) {
327 assert_return(ret
, -EINVAL
);
329 *ret
= JSON_VARIANT_MAGIC_ZERO_UNSIGNED
;
333 r
= json_variant_new(&v
, JSON_VARIANT_UNSIGNED
, sizeof(u
));
343 int json_variant_new_real(JsonVariant
**ret
, long double d
) {
347 assert_return(ret
, -EINVAL
);
349 #pragma GCC diagnostic push
350 #pragma GCC diagnostic ignored "-Wfloat-equal"
352 #pragma GCC diagnostic pop
353 *ret
= JSON_VARIANT_MAGIC_ZERO_REAL
;
357 r
= json_variant_new(&v
, JSON_VARIANT_REAL
, sizeof(d
));
367 int json_variant_new_boolean(JsonVariant
**ret
, bool b
) {
368 assert_return(ret
, -EINVAL
);
371 *ret
= JSON_VARIANT_MAGIC_TRUE
;
373 *ret
= JSON_VARIANT_MAGIC_FALSE
;
378 int json_variant_new_null(JsonVariant
**ret
) {
379 assert_return(ret
, -EINVAL
);
381 *ret
= JSON_VARIANT_MAGIC_NULL
;
385 int json_variant_new_stringn(JsonVariant
**ret
, const char *s
, size_t n
) {
389 assert_return(ret
, -EINVAL
);
391 assert_return(IN_SET(n
, 0, (size_t) -1), -EINVAL
);
392 return json_variant_new_null(ret
);
394 if (n
== (size_t) -1) /* determine length automatically */
396 else if (memchr(s
, 0, n
)) /* don't allow embedded NUL, as we can't express that in JSON */
399 *ret
= JSON_VARIANT_MAGIC_EMPTY_STRING
;
403 r
= json_variant_new(&v
, JSON_VARIANT_STRING
, n
+ 1);
407 memcpy(v
->string
, s
, n
);
414 int json_variant_new_base64(JsonVariant
**ret
, const void *p
, size_t n
) {
415 _cleanup_free_
char *s
= NULL
;
418 assert_return(ret
, -EINVAL
);
419 assert_return(n
== 0 || p
, -EINVAL
);
421 k
= base64mem(p
, n
, &s
);
425 return json_variant_new_stringn(ret
, s
, k
);
428 static void json_variant_set(JsonVariant
*a
, JsonVariant
*b
) {
431 b
= json_variant_dereference(b
);
433 a
->type
= JSON_VARIANT_NULL
;
437 a
->type
= json_variant_type(b
);
440 case JSON_VARIANT_INTEGER
:
441 a
->value
.integer
= json_variant_integer(b
);
444 case JSON_VARIANT_UNSIGNED
:
445 a
->value
.unsig
= json_variant_unsigned(b
);
448 case JSON_VARIANT_REAL
:
449 a
->value
.real
= json_variant_real(b
);
452 case JSON_VARIANT_BOOLEAN
:
453 a
->value
.boolean
= json_variant_boolean(b
);
456 case JSON_VARIANT_STRING
: {
459 assert_se(s
= json_variant_string(b
));
461 /* Short strings we can store inline */
462 if (strnlen(s
, INLINE_STRING_MAX
+1) <= INLINE_STRING_MAX
) {
463 strcpy(a
->string
, s
);
467 /* For longer strings, use a reference… */
471 case JSON_VARIANT_ARRAY
:
472 case JSON_VARIANT_OBJECT
:
473 a
->is_reference
= true;
474 a
->reference
= json_variant_ref(json_variant_conservative_formalize(b
));
477 case JSON_VARIANT_NULL
:
481 assert_not_reached("Unexpected variant type");
485 static void json_variant_copy_source(JsonVariant
*v
, JsonVariant
*from
) {
489 if (!json_variant_is_regular(from
))
492 v
->line
= from
->line
;
493 v
->column
= from
->column
;
494 v
->source
= json_source_ref(from
->source
);
497 int json_variant_new_array(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
498 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
499 bool normalized
= true;
501 assert_return(ret
, -EINVAL
);
503 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
506 assert_return(array
, -EINVAL
);
508 v
= new(JsonVariant
, n
+ 1);
514 .type
= JSON_VARIANT_ARRAY
,
517 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
518 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
519 *c
= array
[v
->n_elements
];
522 d
= json_variant_depth(c
);
523 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
533 json_variant_set(w
, c
);
534 json_variant_copy_source(w
, c
);
536 if (!json_variant_is_normalized(c
))
540 v
->normalized
= normalized
;
546 int json_variant_new_array_bytes(JsonVariant
**ret
, const void *p
, size_t n
) {
550 assert_return(ret
, -EINVAL
);
552 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
555 assert_return(p
, -EINVAL
);
557 v
= new(JsonVariant
, n
+ 1);
563 .type
= JSON_VARIANT_ARRAY
,
568 for (i
= 0; i
< n
; i
++) {
569 JsonVariant
*w
= v
+ 1 + i
;
574 .type
= JSON_VARIANT_UNSIGNED
,
575 .value
.unsig
= ((const uint8_t*) p
)[i
],
579 v
->normalized
= true;
585 int json_variant_new_array_strv(JsonVariant
**ret
, char **l
) {
586 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
594 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
598 v
= new(JsonVariant
, n
+ 1);
604 .type
= JSON_VARIANT_ARRAY
,
608 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
609 JsonVariant
*w
= v
+ 1 + v
->n_elements
;
615 .type
= JSON_VARIANT_STRING
,
618 k
= strlen(l
[v
->n_elements
]);
620 if (k
> INLINE_STRING_MAX
) {
621 /* If string is too long, store it as reference. */
623 r
= json_variant_new_string(&w
->reference
, l
[v
->n_elements
]);
627 w
->is_reference
= true;
629 memcpy(w
->string
, l
[v
->n_elements
], k
+1);
632 v
->normalized
= true;
638 int json_variant_new_object(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
639 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
640 const char *prev
= NULL
;
641 bool sorted
= true, normalized
= true;
643 assert_return(ret
, -EINVAL
);
645 *ret
= JSON_VARIANT_MAGIC_EMPTY_OBJECT
;
648 assert_return(array
, -EINVAL
);
649 assert_return(n
% 2 == 0, -EINVAL
);
651 v
= new(JsonVariant
, n
+ 1);
657 .type
= JSON_VARIANT_OBJECT
,
660 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
661 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
662 *c
= array
[v
->n_elements
];
665 if ((v
->n_elements
& 1) == 0) {
668 if (!json_variant_is_string(c
))
669 return -EINVAL
; /* Every second one needs to be a string, as it is the key name */
671 assert_se(k
= json_variant_string(c
));
673 if (prev
&& strcmp(k
, prev
) <= 0)
674 sorted
= normalized
= false;
677 } else if (!json_variant_is_normalized(c
))
680 d
= json_variant_depth(c
);
681 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
691 json_variant_set(w
, c
);
692 json_variant_copy_source(w
, c
);
695 v
->normalized
= normalized
;
702 static size_t json_variant_size(JsonVariant
* v
) {
704 if (!json_variant_is_regular(v
))
708 return offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*);
712 case JSON_VARIANT_STRING
:
713 return offsetof(JsonVariant
, string
) + strlen(v
->string
) + 1;
715 case JSON_VARIANT_REAL
:
716 return offsetof(JsonVariant
, value
) + sizeof(long double);
718 case JSON_VARIANT_UNSIGNED
:
719 return offsetof(JsonVariant
, value
) + sizeof(uintmax_t);
721 case JSON_VARIANT_INTEGER
:
722 return offsetof(JsonVariant
, value
) + sizeof(intmax_t);
724 case JSON_VARIANT_BOOLEAN
:
725 return offsetof(JsonVariant
, value
) + sizeof(bool);
727 case JSON_VARIANT_ARRAY
:
728 case JSON_VARIANT_OBJECT
:
729 return offsetof(JsonVariant
, n_elements
) + sizeof(size_t);
731 case JSON_VARIANT_NULL
:
732 return offsetof(JsonVariant
, value
);
735 assert_not_reached("unexpected type");
739 static void json_variant_free_inner(JsonVariant
*v
, bool force_sensitive
) {
744 if (!json_variant_is_regular(v
))
747 json_source_unref(v
->source
);
749 sensitive
= v
->sensitive
|| force_sensitive
;
751 if (v
->is_reference
) {
753 json_variant_sensitive(v
->reference
);
755 json_variant_unref(v
->reference
);
759 if (IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
)) {
762 for (i
= 0; i
< v
->n_elements
; i
++)
763 json_variant_free_inner(v
+ 1 + i
, sensitive
);
767 explicit_bzero_safe(v
, json_variant_size(v
));
770 JsonVariant
*json_variant_ref(JsonVariant
*v
) {
773 if (!json_variant_is_regular(v
))
777 json_variant_ref(v
->parent
); /* ref the compounding variant instead */
779 assert(v
->n_ref
> 0);
786 JsonVariant
*json_variant_unref(JsonVariant
*v
) {
789 if (!json_variant_is_regular(v
))
793 json_variant_unref(v
->parent
);
795 assert(v
->n_ref
> 0);
799 json_variant_free_inner(v
, false);
807 void json_variant_unref_many(JsonVariant
**array
, size_t n
) {
810 assert(array
|| n
== 0);
812 for (i
= 0; i
< n
; i
++)
813 json_variant_unref(array
[i
]);
816 const char *json_variant_string(JsonVariant
*v
) {
819 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
821 if (json_variant_is_magic(v
))
823 if (json_variant_is_const_string(v
)) {
824 uintptr_t p
= (uintptr_t) v
;
826 assert((p
& 1) != 0);
827 return (const char*) (p
^ 1U);
831 return json_variant_string(v
->reference
);
832 if (v
->type
!= JSON_VARIANT_STRING
)
838 log_debug("Non-string JSON variant requested as string, returning NULL.");
842 bool json_variant_boolean(JsonVariant
*v
) {
845 if (v
== JSON_VARIANT_MAGIC_TRUE
)
847 if (v
== JSON_VARIANT_MAGIC_FALSE
)
849 if (!json_variant_is_regular(v
))
851 if (v
->type
!= JSON_VARIANT_BOOLEAN
)
854 return json_variant_boolean(v
->reference
);
856 return v
->value
.boolean
;
859 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
863 intmax_t json_variant_integer(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_integer(v
->reference
);
877 case JSON_VARIANT_INTEGER
:
878 return v
->value
.integer
;
880 case JSON_VARIANT_UNSIGNED
:
881 if (v
->value
.unsig
<= INTMAX_MAX
)
882 return (intmax_t) v
->value
.unsig
;
884 log_debug("Unsigned integer %ju requested as signed integer and out of range, returning 0.", v
->value
.unsig
);
887 case JSON_VARIANT_REAL
: {
890 converted
= (intmax_t) v
->value
.real
;
892 #pragma GCC diagnostic push
893 #pragma GCC diagnostic ignored "-Wfloat-equal"
894 if ((long double) converted
== v
->value
.real
)
895 #pragma GCC diagnostic pop
898 log_debug("Real %Lg requested as integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
907 log_debug("Non-integer JSON variant requested as integer, returning 0.");
911 uintmax_t json_variant_unsigned(JsonVariant
*v
) {
914 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
915 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
916 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
918 if (!json_variant_is_regular(v
))
921 return json_variant_integer(v
->reference
);
925 case JSON_VARIANT_INTEGER
:
926 if (v
->value
.integer
>= 0)
927 return (uintmax_t) v
->value
.integer
;
929 log_debug("Signed integer %ju requested as unsigned integer and out of range, returning 0.", v
->value
.integer
);
932 case JSON_VARIANT_UNSIGNED
:
933 return v
->value
.unsig
;
935 case JSON_VARIANT_REAL
: {
938 converted
= (uintmax_t) v
->value
.real
;
940 #pragma GCC diagnostic push
941 #pragma GCC diagnostic ignored "-Wfloat-equal"
942 if ((long double) converted
== v
->value
.real
)
943 #pragma GCC diagnostic pop
946 log_debug("Real %Lg requested as unsigned integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
955 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
959 long double json_variant_real(JsonVariant
*v
) {
962 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
963 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
964 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
966 if (!json_variant_is_regular(v
))
969 return json_variant_real(v
->reference
);
973 case JSON_VARIANT_REAL
:
974 return v
->value
.real
;
976 case JSON_VARIANT_INTEGER
: {
977 long double converted
;
979 converted
= (long double) v
->value
.integer
;
981 if ((intmax_t) converted
== v
->value
.integer
)
984 log_debug("Signed integer %ji requested as real, and cannot be converted losslessly, returning 0.", v
->value
.integer
);
988 case JSON_VARIANT_UNSIGNED
: {
989 long double converted
;
991 converted
= (long double) v
->value
.unsig
;
993 if ((uintmax_t) converted
== v
->value
.unsig
)
996 log_debug("Unsigned integer %ju requested as real, and cannot be converted losslessly, returning 0.", v
->value
.unsig
);
1005 log_debug("Non-integer JSON variant requested as integer, returning 0.");
1009 bool json_variant_is_negative(JsonVariant
*v
) {
1012 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
1013 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
1014 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
1016 if (!json_variant_is_regular(v
))
1018 if (v
->is_reference
)
1019 return json_variant_is_negative(v
->reference
);
1021 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
1022 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
1027 case JSON_VARIANT_REAL
:
1028 return v
->value
.real
< 0;
1030 case JSON_VARIANT_INTEGER
:
1031 return v
->value
.integer
< 0;
1033 case JSON_VARIANT_UNSIGNED
:
1041 log_debug("Non-integer JSON variant tested for negativity, returning false.");
1045 bool json_variant_is_blank_object(JsonVariant
*v
) {
1046 /* Returns true if the specified object is null or empty */
1048 json_variant_is_null(v
) ||
1049 (json_variant_is_object(v
) && json_variant_elements(v
) == 0);
1052 bool json_variant_is_blank_array(JsonVariant
*v
) {
1054 json_variant_is_null(v
) ||
1055 (json_variant_is_array(v
) && json_variant_elements(v
) == 0);
1058 JsonVariantType
json_variant_type(JsonVariant
*v
) {
1061 return _JSON_VARIANT_TYPE_INVALID
;
1063 if (json_variant_is_const_string(v
))
1064 return JSON_VARIANT_STRING
;
1066 if (v
== JSON_VARIANT_MAGIC_TRUE
|| v
== JSON_VARIANT_MAGIC_FALSE
)
1067 return JSON_VARIANT_BOOLEAN
;
1069 if (v
== JSON_VARIANT_MAGIC_NULL
)
1070 return JSON_VARIANT_NULL
;
1072 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
)
1073 return JSON_VARIANT_INTEGER
;
1075 if (v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
)
1076 return JSON_VARIANT_UNSIGNED
;
1078 if (v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
1079 return JSON_VARIANT_REAL
;
1081 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
1082 return JSON_VARIANT_STRING
;
1084 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
)
1085 return JSON_VARIANT_ARRAY
;
1087 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1088 return JSON_VARIANT_OBJECT
;
1093 bool json_variant_has_type(JsonVariant
*v
, JsonVariantType type
) {
1096 v
= json_variant_dereference(v
);
1100 rt
= json_variant_type(v
);
1104 /* If it's a const string, then it only can be a string, and if it is not, it's not */
1105 if (json_variant_is_const_string(v
))
1108 /* All three magic zeroes qualify as integer, unsigned and as real */
1109 if ((v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
|| v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
|| v
== JSON_VARIANT_MAGIC_ZERO_REAL
) &&
1110 IN_SET(type
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
, JSON_VARIANT_NUMBER
))
1113 /* All other magic variant types are only equal to themselves */
1114 if (json_variant_is_magic(v
))
1117 /* Handle the "number" pseudo type */
1118 if (type
== JSON_VARIANT_NUMBER
)
1119 return IN_SET(rt
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
);
1121 /* Integer conversions are OK in many cases */
1122 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_UNSIGNED
)
1123 return v
->value
.integer
>= 0;
1124 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_INTEGER
)
1125 return v
->value
.unsig
<= INTMAX_MAX
;
1127 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1128 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_REAL
)
1129 return (intmax_t) (long double) v
->value
.integer
== v
->value
.integer
;
1130 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_REAL
)
1131 return (uintmax_t) (long double) v
->value
.unsig
== v
->value
.unsig
;
1133 #pragma GCC diagnostic push
1134 #pragma GCC diagnostic ignored "-Wfloat-equal"
1135 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1136 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_INTEGER
)
1137 return (long double) (intmax_t) v
->value
.real
== v
->value
.real
;
1138 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_UNSIGNED
)
1139 return (long double) (uintmax_t) v
->value
.real
== v
->value
.real
;
1140 #pragma GCC diagnostic pop
1145 size_t json_variant_elements(JsonVariant
*v
) {
1148 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1149 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1151 if (!json_variant_is_regular(v
))
1153 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1155 if (v
->is_reference
)
1156 return json_variant_elements(v
->reference
);
1158 return v
->n_elements
;
1161 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1165 JsonVariant
*json_variant_by_index(JsonVariant
*v
, size_t idx
) {
1168 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1169 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1171 if (!json_variant_is_regular(v
))
1173 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1175 if (v
->is_reference
)
1176 return json_variant_by_index(v
->reference
, idx
);
1177 if (idx
>= v
->n_elements
)
1180 return json_variant_conservative_formalize(v
+ 1 + idx
);
1183 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1187 JsonVariant
*json_variant_by_key_full(JsonVariant
*v
, const char *key
, JsonVariant
**ret_key
) {
1194 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1196 if (!json_variant_is_regular(v
))
1198 if (v
->type
!= JSON_VARIANT_OBJECT
)
1200 if (v
->is_reference
)
1201 return json_variant_by_key(v
->reference
, key
);
1204 size_t a
= 0, b
= v
->n_elements
/2;
1206 /* If the variant is sorted we can use bisection to find the entry we need in O(log(n)) time */
1214 p
= json_variant_dereference(v
+ 1 + i
*2);
1216 assert_se(f
= json_variant_string(p
));
1221 *ret_key
= json_variant_conservative_formalize(v
+ 1 + i
*2);
1223 return json_variant_conservative_formalize(v
+ 1 + i
*2 + 1);
1233 /* The variant is not sorted, hence search for the field linearly */
1234 for (i
= 0; i
< v
->n_elements
; i
+= 2) {
1237 p
= json_variant_dereference(v
+ 1 + i
);
1239 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1242 if (streq(json_variant_string(p
), key
)) {
1245 *ret_key
= json_variant_conservative_formalize(v
+ 1 + i
);
1247 return json_variant_conservative_formalize(v
+ 1 + i
+ 1);
1258 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1265 JsonVariant
*json_variant_by_key(JsonVariant
*v
, const char *key
) {
1266 return json_variant_by_key_full(v
, key
, NULL
);
1269 bool json_variant_equal(JsonVariant
*a
, JsonVariant
*b
) {
1272 a
= json_variant_formalize(a
);
1273 b
= json_variant_formalize(b
);
1278 t
= json_variant_type(a
);
1279 if (!json_variant_has_type(b
, t
))
1284 case JSON_VARIANT_STRING
:
1285 return streq(json_variant_string(a
), json_variant_string(b
));
1287 case JSON_VARIANT_INTEGER
:
1288 return json_variant_integer(a
) == json_variant_integer(b
);
1290 case JSON_VARIANT_UNSIGNED
:
1291 return json_variant_unsigned(a
) == json_variant_unsigned(b
);
1293 case JSON_VARIANT_REAL
:
1294 #pragma GCC diagnostic push
1295 #pragma GCC diagnostic ignored "-Wfloat-equal"
1296 return json_variant_real(a
) == json_variant_real(b
);
1297 #pragma GCC diagnostic pop
1299 case JSON_VARIANT_BOOLEAN
:
1300 return json_variant_boolean(a
) == json_variant_boolean(b
);
1302 case JSON_VARIANT_NULL
:
1305 case JSON_VARIANT_ARRAY
: {
1308 n
= json_variant_elements(a
);
1309 if (n
!= json_variant_elements(b
))
1312 for (i
= 0; i
< n
; i
++) {
1313 if (!json_variant_equal(json_variant_by_index(a
, i
), json_variant_by_index(b
, i
)))
1320 case JSON_VARIANT_OBJECT
: {
1323 n
= json_variant_elements(a
);
1324 if (n
!= json_variant_elements(b
))
1327 /* Iterate through all keys in 'a' */
1328 for (i
= 0; i
< n
; i
+= 2) {
1332 /* Match them against all keys in 'b' */
1333 for (j
= 0; j
< n
; j
+= 2) {
1336 key_b
= json_variant_by_index(b
, j
);
1338 /* During the first iteration unmark everything */
1340 key_b
->is_marked
= false;
1341 else if (key_b
->is_marked
) /* In later iterations if we already marked something, don't bother with it again */
1347 if (json_variant_equal(json_variant_by_index(a
, i
), key_b
) &&
1348 json_variant_equal(json_variant_by_index(a
, i
+1), json_variant_by_index(b
, j
+1))) {
1349 /* Key and values match! */
1350 key_b
->is_marked
= found
= true;
1352 /* In the first iteration we continue the inner loop since we want to mark
1353 * everything, otherwise exit the loop quickly after we found what we were
1368 assert_not_reached("Unknown variant type.");
1372 void json_variant_sensitive(JsonVariant
*v
) {
1375 /* Marks a variant as "sensitive", so that it is erased from memory when it is destroyed. This is a
1376 * one-way operation: as soon as it is marked this way it remains marked this way until it's
1377 * destoryed. A magic variant is never sensitive though, even when asked, since it's too
1378 * basic. Similar, const string variant are never sensitive either, after all they are included in
1379 * the source code as they are, which is not suitable for inclusion of secrets.
1381 * Note that this flag has a recursive effect: when we destroy an object or array we'll propagate the
1382 * flag to all contained variants. And if those are then destroyed this is propagated further down,
1385 v
= json_variant_formalize(v
);
1386 if (!json_variant_is_regular(v
))
1389 v
->sensitive
= true;
1392 int json_variant_get_source(JsonVariant
*v
, const char **ret_source
, unsigned *ret_line
, unsigned *ret_column
) {
1393 assert_return(v
, -EINVAL
);
1396 *ret_source
= json_variant_is_regular(v
) && v
->source
? v
->source
->name
: NULL
;
1399 *ret_line
= json_variant_is_regular(v
) ? v
->line
: 0;
1402 *ret_column
= json_variant_is_regular(v
) ? v
->column
: 0;
1407 static int print_source(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, bool whitespace
) {
1410 if (!FLAGS_SET(flags
, JSON_FORMAT_SOURCE
|JSON_FORMAT_PRETTY
))
1413 if (!json_variant_is_regular(v
))
1416 if (!v
->source
&& v
->line
== 0 && v
->column
== 0)
1419 /* The max width we need to format the line numbers for this source file */
1420 w
= (v
->source
&& v
->source
->max_line
> 0) ?
1421 DECIMAL_STR_WIDTH(v
->source
->max_line
) :
1422 DECIMAL_STR_MAX(unsigned)-1;
1423 k
= (v
->source
&& v
->source
->max_column
> 0) ?
1424 DECIMAL_STR_WIDTH(v
->source
->max_column
) :
1425 DECIMAL_STR_MAX(unsigned) -1;
1430 n
= 1 + (v
->source
? strlen(v
->source
->name
) : 0) +
1431 ((v
->source
&& (v
->line
> 0 || v
->column
> 0)) ? 1 : 0) +
1432 (v
->line
> 0 ? w
: 0) +
1433 (((v
->source
|| v
->line
> 0) && v
->column
> 0) ? 1 : 0) +
1434 (v
->column
> 0 ? k
: 0) +
1437 for (i
= 0; i
< n
; i
++)
1443 fputs(v
->source
->name
, f
);
1444 if (v
->source
&& (v
->line
> 0 || v
->column
> 0))
1447 fprintf(f
, "%*u", (int) w
, v
->line
);
1448 if ((v
->source
|| v
->line
> 0) || v
->column
> 0)
1451 fprintf(f
, "%*u", (int) k
, v
->column
);
1460 static int json_format(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, const char *prefix
) {
1466 switch (json_variant_type(v
)) {
1468 case JSON_VARIANT_REAL
: {
1471 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
1472 if (loc
== (locale_t
) 0)
1475 if (flags
& JSON_FORMAT_COLOR
)
1476 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1478 fprintf(f
, "%.*Le", DECIMAL_DIG
, json_variant_real(v
));
1480 if (flags
& JSON_FORMAT_COLOR
)
1481 fputs(ANSI_NORMAL
, f
);
1487 case JSON_VARIANT_INTEGER
:
1488 if (flags
& JSON_FORMAT_COLOR
)
1489 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1491 fprintf(f
, "%" PRIdMAX
, json_variant_integer(v
));
1493 if (flags
& JSON_FORMAT_COLOR
)
1494 fputs(ANSI_NORMAL
, f
);
1497 case JSON_VARIANT_UNSIGNED
:
1498 if (flags
& JSON_FORMAT_COLOR
)
1499 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1501 fprintf(f
, "%" PRIuMAX
, json_variant_unsigned(v
));
1503 if (flags
& JSON_FORMAT_COLOR
)
1504 fputs(ANSI_NORMAL
, f
);
1507 case JSON_VARIANT_BOOLEAN
:
1509 if (flags
& JSON_FORMAT_COLOR
)
1510 fputs(ANSI_HIGHLIGHT
, f
);
1512 if (json_variant_boolean(v
))
1517 if (flags
& JSON_FORMAT_COLOR
)
1518 fputs(ANSI_NORMAL
, f
);
1522 case JSON_VARIANT_NULL
:
1523 if (flags
& JSON_FORMAT_COLOR
)
1524 fputs(ANSI_HIGHLIGHT
, f
);
1528 if (flags
& JSON_FORMAT_COLOR
)
1529 fputs(ANSI_NORMAL
, f
);
1532 case JSON_VARIANT_STRING
: {
1537 if (flags
& JSON_FORMAT_COLOR
)
1538 fputs(ANSI_GREEN
, f
);
1540 for (q
= json_variant_string(v
); *q
; q
++) {
1573 if ((signed char) *q
>= 0 && *q
< ' ')
1574 fprintf(f
, "\\u%04x", *q
);
1581 if (flags
& JSON_FORMAT_COLOR
)
1582 fputs(ANSI_NORMAL
, f
);
1588 case JSON_VARIANT_ARRAY
: {
1591 n
= json_variant_elements(v
);
1596 _cleanup_free_
char *joined
= NULL
;
1597 const char *prefix2
;
1599 if (flags
& JSON_FORMAT_PRETTY
) {
1600 joined
= strjoin(strempty(prefix
), "\t");
1607 prefix2
= strempty(prefix
);
1611 for (i
= 0; i
< n
; i
++) {
1614 assert_se(e
= json_variant_by_index(v
, i
));
1617 if (flags
& JSON_FORMAT_PRETTY
)
1623 if (flags
& JSON_FORMAT_PRETTY
) {
1624 print_source(f
, e
, flags
, false);
1628 r
= json_format(f
, e
, flags
, prefix2
);
1633 if (flags
& JSON_FORMAT_PRETTY
) {
1635 print_source(f
, v
, flags
, true);
1636 fputs(strempty(prefix
), f
);
1644 case JSON_VARIANT_OBJECT
: {
1647 n
= json_variant_elements(v
);
1652 _cleanup_free_
char *joined
= NULL
;
1653 const char *prefix2
;
1655 if (flags
& JSON_FORMAT_PRETTY
) {
1656 joined
= strjoin(strempty(prefix
), "\t");
1663 prefix2
= strempty(prefix
);
1667 for (i
= 0; i
< n
; i
+= 2) {
1670 e
= json_variant_by_index(v
, i
);
1673 if (flags
& JSON_FORMAT_PRETTY
)
1679 if (flags
& JSON_FORMAT_PRETTY
) {
1680 print_source(f
, e
, flags
, false);
1684 r
= json_format(f
, e
, flags
, prefix2
);
1688 fputs(flags
& JSON_FORMAT_PRETTY
? " : " : ":", f
);
1690 r
= json_format(f
, json_variant_by_index(v
, i
+1), flags
, prefix2
);
1695 if (flags
& JSON_FORMAT_PRETTY
) {
1697 print_source(f
, v
, flags
, true);
1698 fputs(strempty(prefix
), f
);
1707 assert_not_reached("Unexpected variant type.");
1713 int json_variant_format(JsonVariant
*v
, JsonFormatFlags flags
, char **ret
) {
1714 _cleanup_free_
char *s
= NULL
;
1718 /* Returns the length of the generated string (without the terminating NUL),
1719 * or negative on error. */
1721 assert_return(v
, -EINVAL
);
1722 assert_return(ret
, -EINVAL
);
1725 _cleanup_fclose_
FILE *f
= NULL
;
1727 f
= open_memstream_unlocked(&s
, &sz
);
1731 json_variant_dump(v
, flags
, f
, NULL
);
1733 /* Add terminating 0, so that the output buffer is a valid string. */
1736 r
= fflush_and_check(f
);
1744 return (int) sz
- 1;
1747 void json_variant_dump(JsonVariant
*v
, JsonFormatFlags flags
, FILE *f
, const char *prefix
) {
1754 print_source(f
, v
, flags
, false);
1756 if (((flags
& (JSON_FORMAT_COLOR_AUTO
|JSON_FORMAT_COLOR
)) == JSON_FORMAT_COLOR_AUTO
) && colors_enabled())
1757 flags
|= JSON_FORMAT_COLOR
;
1759 if (flags
& JSON_FORMAT_SSE
)
1761 if (flags
& JSON_FORMAT_SEQ
)
1762 fputc('\x1e', f
); /* ASCII Record Separator */
1764 json_format(f
, v
, flags
, prefix
);
1766 if (flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_SEQ
|JSON_FORMAT_SSE
|JSON_FORMAT_NEWLINE
))
1768 if (flags
& JSON_FORMAT_SSE
)
1769 fputc('\n', f
); /* In case of SSE add a second newline */
1772 int json_variant_filter(JsonVariant
**v
, char **to_remove
) {
1773 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
1774 _cleanup_free_ JsonVariant
**array
= NULL
;
1775 size_t i
, n
= 0, k
= 0;
1780 if (json_variant_is_blank_object(*v
))
1782 if (!json_variant_is_object(*v
))
1785 if (strv_isempty(to_remove
))
1788 for (i
= 0; i
< json_variant_elements(*v
); i
+= 2) {
1791 p
= json_variant_by_index(*v
, i
);
1792 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1795 if (strv_contains(to_remove
, json_variant_string(p
))) {
1797 array
= new(JsonVariant
*, json_variant_elements(*v
) - 2);
1801 for (k
= 0; k
< i
; k
++)
1802 array
[k
] = json_variant_by_index(*v
, k
);
1808 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1815 r
= json_variant_new_object(&w
, array
, k
);
1819 json_variant_unref(*v
);
1825 int json_variant_set_field(JsonVariant
**v
, const char *field
, JsonVariant
*value
) {
1826 _cleanup_(json_variant_unrefp
) JsonVariant
*field_variant
= NULL
, *w
= NULL
;
1827 _cleanup_free_ JsonVariant
**array
= NULL
;
1834 if (json_variant_is_blank_object(*v
)) {
1835 array
= new(JsonVariant
*, 2);
1840 if (!json_variant_is_object(*v
))
1843 for (i
= 0; i
< json_variant_elements(*v
); i
+= 2) {
1846 p
= json_variant_by_index(*v
, i
);
1847 if (!json_variant_is_string(p
))
1850 if (streq(json_variant_string(p
), field
)) {
1853 array
= new(JsonVariant
*, json_variant_elements(*v
));
1857 for (k
= 0; k
< i
; k
++)
1858 array
[k
] = json_variant_by_index(*v
, k
);
1863 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1868 array
= new(JsonVariant
*, json_variant_elements(*v
) + 2);
1872 for (k
= 0; k
< json_variant_elements(*v
); k
++)
1873 array
[k
] = json_variant_by_index(*v
, k
);
1877 r
= json_variant_new_string(&field_variant
, field
);
1881 array
[k
++] = field_variant
;
1884 r
= json_variant_new_object(&w
, array
, k
);
1888 json_variant_unref(*v
);
1894 int json_variant_set_field_string(JsonVariant
**v
, const char *field
, const char *value
) {
1895 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1898 r
= json_variant_new_string(&m
, value
);
1902 return json_variant_set_field(v
, field
, m
);
1905 int json_variant_set_field_unsigned(JsonVariant
**v
, const char *field
, uintmax_t u
) {
1906 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1909 r
= json_variant_new_unsigned(&m
, u
);
1913 return json_variant_set_field(v
, field
, m
);
1916 int json_variant_merge(JsonVariant
**v
, JsonVariant
*m
) {
1917 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
1918 _cleanup_free_ JsonVariant
**array
= NULL
;
1919 size_t v_elements
, m_elements
, i
, k
;
1920 bool v_blank
, m_blank
;
1923 m
= json_variant_dereference(m
);
1925 v_blank
= json_variant_is_blank_object(*v
);
1926 m_blank
= json_variant_is_blank_object(m
);
1928 if (!v_blank
&& !json_variant_is_object(*v
))
1930 if (!m_blank
&& !json_variant_is_object(m
))
1934 return 0; /* nothing to do */
1937 json_variant_unref(*v
);
1938 *v
= json_variant_ref(m
);
1942 v_elements
= json_variant_elements(*v
);
1943 m_elements
= json_variant_elements(m
);
1944 if (v_elements
> SIZE_MAX
- m_elements
) /* overflow check */
1947 array
= new(JsonVariant
*, v_elements
+ m_elements
);
1952 for (i
= 0; i
< v_elements
; i
+= 2) {
1955 u
= json_variant_by_index(*v
, i
);
1956 if (!json_variant_is_string(u
))
1959 if (json_variant_by_key(m
, json_variant_string(u
)))
1960 continue; /* skip if exists in second variant */
1963 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1966 for (i
= 0; i
< m_elements
; i
++)
1967 array
[k
++] = json_variant_by_index(m
, i
);
1969 r
= json_variant_new_object(&w
, array
, k
);
1973 json_variant_unref(*v
);
1979 int json_variant_append_array(JsonVariant
**v
, JsonVariant
*element
) {
1980 _cleanup_(json_variant_unrefp
) JsonVariant
*nv
= NULL
;
1988 if (!*v
|| json_variant_is_null(*v
))
1990 else if (!json_variant_is_array(*v
))
1993 blank
= json_variant_elements(*v
) == 0;
1996 r
= json_variant_new_array(&nv
, (JsonVariant
*[]) { element
}, 1);
1998 _cleanup_free_ JsonVariant
**array
= NULL
;
2001 array
= new(JsonVariant
*, json_variant_elements(*v
) + 1);
2005 for (i
= 0; i
< json_variant_elements(*v
); i
++)
2006 array
[i
] = json_variant_by_index(*v
, i
);
2010 r
= json_variant_new_array(&nv
, array
, i
+ 1);
2016 json_variant_unref(*v
);
2022 int json_variant_strv(JsonVariant
*v
, char ***ret
) {
2030 if (!v
|| json_variant_is_null(v
)) {
2039 if (!json_variant_is_array(v
))
2042 sensitive
= v
->sensitive
;
2044 n
= json_variant_elements(v
);
2045 l
= new(char*, n
+1);
2049 for (i
= 0; i
< n
; i
++) {
2052 assert_se(e
= json_variant_by_index(v
, i
));
2053 sensitive
= sensitive
|| e
->sensitive
;
2055 if (!json_variant_is_string(e
)) {
2061 l
[i
] = strdup(json_variant_string(e
));
2082 static int json_variant_copy(JsonVariant
**nv
, JsonVariant
*v
) {
2092 /* Let's copy the simple types literally, and the larger types by references */
2093 t
= json_variant_type(v
);
2095 case JSON_VARIANT_INTEGER
:
2096 k
= sizeof(intmax_t);
2097 value
.integer
= json_variant_integer(v
);
2101 case JSON_VARIANT_UNSIGNED
:
2102 k
= sizeof(uintmax_t);
2103 value
.unsig
= json_variant_unsigned(v
);
2107 case JSON_VARIANT_REAL
:
2108 k
= sizeof(long double);
2109 value
.real
= json_variant_real(v
);
2113 case JSON_VARIANT_BOOLEAN
:
2115 value
.boolean
= json_variant_boolean(v
);
2119 case JSON_VARIANT_NULL
:
2124 case JSON_VARIANT_STRING
:
2125 source
= json_variant_string(v
);
2126 k
= strnlen(source
, INLINE_STRING_MAX
+ 1);
2127 if (k
<= INLINE_STRING_MAX
) {
2135 /* Everything else copy by reference */
2137 c
= malloc0(MAX(sizeof(JsonVariant
),
2138 offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*)));
2144 c
->is_reference
= true;
2145 c
->reference
= json_variant_ref(json_variant_formalize(v
));
2151 c
= malloc0(MAX(sizeof(JsonVariant
),
2152 offsetof(JsonVariant
, value
) + k
));
2159 memcpy_safe(&c
->value
, source
, k
);
2165 static bool json_single_ref(JsonVariant
*v
) {
2167 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
2169 if (!json_variant_is_regular(v
))
2173 return json_single_ref(v
->parent
);
2175 assert(v
->n_ref
> 0);
2176 return v
->n_ref
== 1;
2179 static int json_variant_set_source(JsonVariant
**v
, JsonSource
*source
, unsigned line
, unsigned column
) {
2185 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole referencer of
2186 * the object. If not, allocates a new object, possibly a surrogate for the original one */
2191 if (source
&& line
> source
->max_line
)
2192 source
->max_line
= line
;
2193 if (source
&& column
> source
->max_column
)
2194 source
->max_column
= column
;
2196 if (!json_variant_is_regular(*v
)) {
2198 if (!source
&& line
== 0 && column
== 0)
2202 if (json_source_equal((*v
)->source
, source
) &&
2203 (*v
)->line
== line
&&
2204 (*v
)->column
== column
)
2207 if (json_single_ref(*v
)) { /* Sole reference? */
2208 json_source_unref((*v
)->source
);
2209 (*v
)->source
= json_source_ref(source
);
2211 (*v
)->column
= column
;
2216 r
= json_variant_copy(&w
, *v
);
2220 assert(json_variant_is_regular(w
));
2221 assert(!w
->is_embedded
);
2222 assert(w
->n_ref
== 1);
2225 w
->source
= json_source_ref(source
);
2229 json_variant_unref(*v
);
2235 static void inc_lines_columns(unsigned *line
, unsigned *column
, const char *s
, size_t n
) {
2238 assert(s
|| n
== 0);
2244 } else if ((signed char) *s
>= 0 && *s
< 127) /* Process ASCII chars quickly */
2249 w
= utf8_encoded_valid_unichar(s
, n
);
2250 if (w
< 0) /* count invalid unichars as normal characters */
2252 else if ((size_t) w
> n
) /* never read more than the specified number of characters */
2267 static int unhex_ucs2(const char *c
, uint16_t *ret
) {
2274 aa
= unhexchar(c
[0]);
2278 bb
= unhexchar(c
[1]);
2282 cc
= unhexchar(c
[2]);
2286 dd
= unhexchar(c
[3]);
2290 x
= ((uint16_t) aa
<< 12) |
2291 ((uint16_t) bb
<< 8) |
2292 ((uint16_t) cc
<< 4) |
2303 static int json_parse_string(const char **p
, char **ret
) {
2304 _cleanup_free_
char *s
= NULL
;
2305 size_t n
= 0, allocated
= 0;
2326 /* Check for control characters 0x00..0x1f */
2327 if (*c
> 0 && *c
< ' ')
2330 /* Check for control character 0x7f */
2345 return JSON_TOKEN_STRING
;
2355 if (IN_SET(*c
, '"', '\\', '/'))
2367 else if (*c
== 'u') {
2371 r
= unhex_ucs2(c
+ 1, &x
);
2377 if (!GREEDY_REALLOC(s
, allocated
, n
+ 5))
2380 if (!utf16_is_surrogate(x
))
2381 n
+= utf8_encode_unichar(s
+ n
, (char32_t
) x
);
2382 else if (utf16_is_trailing_surrogate(x
))
2387 if (c
[0] != '\\' || c
[1] != 'u')
2390 r
= unhex_ucs2(c
+ 2, &y
);
2396 if (!utf16_is_trailing_surrogate(y
))
2399 n
+= utf8_encode_unichar(s
+ n
, utf16_surrogate_pair_to_unichar(x
, y
));
2406 if (!GREEDY_REALLOC(s
, allocated
, n
+ 2))
2414 len
= utf8_encoded_valid_unichar(c
, (size_t) -1);
2418 if (!GREEDY_REALLOC(s
, allocated
, n
+ len
+ 1))
2421 memcpy(s
+ n
, c
, len
);
2427 static int json_parse_number(const char **p
, JsonValue
*ret
) {
2428 bool negative
= false, exponent_negative
= false, is_real
= false;
2429 long double x
= 0.0, y
= 0.0, exponent
= 0.0, shift
= 1.0;
2448 if (!strchr("123456789", *c
) || *c
== 0)
2455 if (i
< INTMAX_MIN
/ 10) /* overflow */
2458 intmax_t t
= 10 * i
;
2460 if (t
< INTMAX_MIN
+ (*c
- '0')) /* overflow */
2466 if (u
> UINTMAX_MAX
/ 10) /* overflow */
2469 uintmax_t t
= 10 * u
;
2471 if (t
> UINTMAX_MAX
- (*c
- '0')) /* overflow */
2479 x
= 10.0 * x
+ (*c
- '0');
2482 } while (strchr("0123456789", *c
) && *c
!= 0);
2489 if (!strchr("0123456789", *c
) || *c
== 0)
2493 y
= 10.0 * y
+ (*c
- '0');
2494 shift
= 10.0 * shift
;
2496 } while (strchr("0123456789", *c
) && *c
!= 0);
2499 if (IN_SET(*c
, 'e', 'E')) {
2504 exponent_negative
= true;
2506 } else if (*c
== '+')
2509 if (!strchr("0123456789", *c
) || *c
== 0)
2513 exponent
= 10.0 * exponent
+ (*c
- '0');
2515 } while (strchr("0123456789", *c
) && *c
!= 0);
2521 ret
->real
= ((negative
? -1.0 : 1.0) * (x
+ (y
/ shift
))) * exp10l((exponent_negative
? -1.0 : 1.0) * exponent
);
2522 return JSON_TOKEN_REAL
;
2523 } else if (negative
) {
2525 return JSON_TOKEN_INTEGER
;
2528 return JSON_TOKEN_UNSIGNED
;
2535 JsonValue
*ret_value
,
2536 unsigned *ret_line
, /* 'ret_line' returns the line at the beginning of this token */
2537 unsigned *ret_column
,
2539 unsigned *line
, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2542 unsigned start_line
, start_column
;
2543 const char *start
, *c
;
2563 t
= PTR_TO_INT(*state
);
2564 if (t
== STATE_NULL
) {
2570 /* Skip over the whitespace */
2571 n
= strspn(*p
, WHITESPACE
);
2572 inc_lines_columns(line
, column
, *p
, n
);
2575 /* Remember where we started processing this token */
2578 start_column
= *column
;
2582 *ret_value
= JSON_VALUE_NULL
;
2593 *state
= INT_TO_PTR(STATE_VALUE
);
2594 r
= JSON_TOKEN_OBJECT_OPEN
;
2597 } else if (*c
== '}') {
2599 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2600 r
= JSON_TOKEN_OBJECT_CLOSE
;
2603 } else if (*c
== '[') {
2605 *state
= INT_TO_PTR(STATE_VALUE
);
2606 r
= JSON_TOKEN_ARRAY_OPEN
;
2609 } else if (*c
== ']') {
2611 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2612 r
= JSON_TOKEN_ARRAY_CLOSE
;
2615 } else if (*c
== '"') {
2617 r
= json_parse_string(&c
, ret_string
);
2621 *ret_value
= JSON_VALUE_NULL
;
2622 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2625 } else if (strchr("-0123456789", *c
)) {
2627 r
= json_parse_number(&c
, ret_value
);
2632 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2635 } else if (startswith(c
, "true")) {
2637 ret_value
->boolean
= true;
2639 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2640 r
= JSON_TOKEN_BOOLEAN
;
2643 } else if (startswith(c
, "false")) {
2645 ret_value
->boolean
= false;
2647 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2648 r
= JSON_TOKEN_BOOLEAN
;
2651 } else if (startswith(c
, "null")) {
2653 *ret_value
= JSON_VALUE_NULL
;
2655 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2656 r
= JSON_TOKEN_NULL
;
2663 case STATE_VALUE_POST
:
2667 *state
= INT_TO_PTR(STATE_VALUE
);
2668 r
= JSON_TOKEN_COLON
;
2671 } else if (*c
== ',') {
2673 *state
= INT_TO_PTR(STATE_VALUE
);
2674 r
= JSON_TOKEN_COMMA
;
2677 } else if (*c
== '}') {
2679 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2680 r
= JSON_TOKEN_OBJECT_CLOSE
;
2683 } else if (*c
== ']') {
2685 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2686 r
= JSON_TOKEN_ARRAY_CLOSE
;
2693 assert_not_reached("Unexpected tokenizer state");
2698 *ret_value
= JSON_VALUE_NULL
;
2701 inc_lines_columns(line
, column
, start
, c
- start
);
2704 *ret_line
= start_line
;
2705 *ret_column
= start_column
;
2710 typedef enum JsonExpect
{
2711 /* The following values are used by json_parse() */
2714 EXPECT_OBJECT_FIRST_KEY
,
2715 EXPECT_OBJECT_NEXT_KEY
,
2716 EXPECT_OBJECT_COLON
,
2717 EXPECT_OBJECT_VALUE
,
2718 EXPECT_OBJECT_COMMA
,
2719 EXPECT_ARRAY_FIRST_ELEMENT
,
2720 EXPECT_ARRAY_NEXT_ELEMENT
,
2723 /* And these are used by json_build() */
2724 EXPECT_ARRAY_ELEMENT
,
2728 typedef struct JsonStack
{
2730 JsonVariant
**elements
;
2731 size_t n_elements
, n_elements_allocated
;
2732 unsigned line_before
;
2733 unsigned column_before
;
2734 size_t n_suppress
; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2737 static void json_stack_release(JsonStack
*s
) {
2740 json_variant_unref_many(s
->elements
, s
->n_elements
);
2741 s
->elements
= mfree(s
->elements
);
2744 static int json_parse_internal(
2747 JsonParseFlags flags
,
2751 bool continue_end
) {
2753 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2754 unsigned line_buffer
= 0, column_buffer
= 0;
2755 void *tokenizer_state
= NULL
;
2756 JsonStack
*stack
= NULL
;
2760 assert_return(input
, -EINVAL
);
2761 assert_return(ret
, -EINVAL
);
2765 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2768 stack
[0] = (JsonStack
) {
2769 .expect
= EXPECT_TOPLEVEL
,
2773 line
= &line_buffer
;
2775 column
= &column_buffer
;
2778 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
2779 _cleanup_free_
char *string
= NULL
;
2780 unsigned line_token
, column_token
;
2785 assert(n_stack
> 0);
2786 current
= stack
+ n_stack
- 1;
2788 if (continue_end
&& current
->expect
== EXPECT_END
)
2791 token
= json_tokenize(&p
, &string
, &value
, &line_token
, &column_token
, &tokenizer_state
, line
, column
);
2799 case JSON_TOKEN_END
:
2800 if (current
->expect
!= EXPECT_END
) {
2805 assert(current
->n_elements
== 1);
2806 assert(n_stack
== 1);
2809 case JSON_TOKEN_COLON
:
2811 if (current
->expect
!= EXPECT_OBJECT_COLON
) {
2816 current
->expect
= EXPECT_OBJECT_VALUE
;
2819 case JSON_TOKEN_COMMA
:
2821 if (current
->expect
== EXPECT_OBJECT_COMMA
)
2822 current
->expect
= EXPECT_OBJECT_NEXT_KEY
;
2823 else if (current
->expect
== EXPECT_ARRAY_COMMA
)
2824 current
->expect
= EXPECT_ARRAY_NEXT_ELEMENT
;
2832 case JSON_TOKEN_OBJECT_OPEN
:
2834 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2839 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2843 current
= stack
+ n_stack
- 1;
2845 /* Prepare the expect for when we return from the child */
2846 if (current
->expect
== EXPECT_TOPLEVEL
)
2847 current
->expect
= EXPECT_END
;
2848 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2849 current
->expect
= EXPECT_OBJECT_COMMA
;
2851 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2852 current
->expect
= EXPECT_ARRAY_COMMA
;
2855 stack
[n_stack
++] = (JsonStack
) {
2856 .expect
= EXPECT_OBJECT_FIRST_KEY
,
2857 .line_before
= line_token
,
2858 .column_before
= column_token
,
2861 current
= stack
+ n_stack
- 1;
2864 case JSON_TOKEN_OBJECT_CLOSE
:
2865 if (!IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_COMMA
)) {
2870 assert(n_stack
> 1);
2872 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
2876 line_token
= current
->line_before
;
2877 column_token
= current
->column_before
;
2879 json_stack_release(current
);
2880 n_stack
--, current
--;
2884 case JSON_TOKEN_ARRAY_OPEN
:
2885 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2890 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2894 current
= stack
+ n_stack
- 1;
2896 /* Prepare the expect for when we return from the child */
2897 if (current
->expect
== EXPECT_TOPLEVEL
)
2898 current
->expect
= EXPECT_END
;
2899 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2900 current
->expect
= EXPECT_OBJECT_COMMA
;
2902 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2903 current
->expect
= EXPECT_ARRAY_COMMA
;
2906 stack
[n_stack
++] = (JsonStack
) {
2907 .expect
= EXPECT_ARRAY_FIRST_ELEMENT
,
2908 .line_before
= line_token
,
2909 .column_before
= column_token
,
2914 case JSON_TOKEN_ARRAY_CLOSE
:
2915 if (!IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_COMMA
)) {
2920 assert(n_stack
> 1);
2922 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2926 line_token
= current
->line_before
;
2927 column_token
= current
->column_before
;
2929 json_stack_release(current
);
2930 n_stack
--, current
--;
2933 case JSON_TOKEN_STRING
:
2934 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
)) {
2939 r
= json_variant_new_string(&add
, string
);
2943 if (current
->expect
== EXPECT_TOPLEVEL
)
2944 current
->expect
= EXPECT_END
;
2945 else if (IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_NEXT_KEY
))
2946 current
->expect
= EXPECT_OBJECT_COLON
;
2947 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2948 current
->expect
= EXPECT_OBJECT_COMMA
;
2950 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2951 current
->expect
= EXPECT_ARRAY_COMMA
;
2956 case JSON_TOKEN_REAL
:
2957 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2962 r
= json_variant_new_real(&add
, value
.real
);
2966 if (current
->expect
== EXPECT_TOPLEVEL
)
2967 current
->expect
= EXPECT_END
;
2968 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2969 current
->expect
= EXPECT_OBJECT_COMMA
;
2971 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2972 current
->expect
= EXPECT_ARRAY_COMMA
;
2977 case JSON_TOKEN_INTEGER
:
2978 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2983 r
= json_variant_new_integer(&add
, value
.integer
);
2987 if (current
->expect
== EXPECT_TOPLEVEL
)
2988 current
->expect
= EXPECT_END
;
2989 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2990 current
->expect
= EXPECT_OBJECT_COMMA
;
2992 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2993 current
->expect
= EXPECT_ARRAY_COMMA
;
2998 case JSON_TOKEN_UNSIGNED
:
2999 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3004 r
= json_variant_new_unsigned(&add
, value
.unsig
);
3008 if (current
->expect
== EXPECT_TOPLEVEL
)
3009 current
->expect
= EXPECT_END
;
3010 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3011 current
->expect
= EXPECT_OBJECT_COMMA
;
3013 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3014 current
->expect
= EXPECT_ARRAY_COMMA
;
3019 case JSON_TOKEN_BOOLEAN
:
3020 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3025 r
= json_variant_new_boolean(&add
, value
.boolean
);
3029 if (current
->expect
== EXPECT_TOPLEVEL
)
3030 current
->expect
= EXPECT_END
;
3031 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3032 current
->expect
= EXPECT_OBJECT_COMMA
;
3034 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3035 current
->expect
= EXPECT_ARRAY_COMMA
;
3040 case JSON_TOKEN_NULL
:
3041 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
3046 r
= json_variant_new_null(&add
);
3050 if (current
->expect
== EXPECT_TOPLEVEL
)
3051 current
->expect
= EXPECT_END
;
3052 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3053 current
->expect
= EXPECT_OBJECT_COMMA
;
3055 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
3056 current
->expect
= EXPECT_ARRAY_COMMA
;
3062 assert_not_reached("Unexpected token");
3066 /* If we are asked to make this parsed object sensitive, then let's apply this
3067 * immediately after allocating each variant, so that when we abort half-way
3068 * everything we already allocated that is then freed is correctly marked. */
3069 if (FLAGS_SET(flags
, JSON_PARSE_SENSITIVE
))
3070 json_variant_sensitive(add
);
3072 (void) json_variant_set_source(&add
, source
, line_token
, column_token
);
3074 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3079 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3084 assert(n_stack
== 1);
3085 assert(stack
[0].n_elements
== 1);
3087 *ret
= json_variant_ref(stack
[0].elements
[0]);
3092 for (i
= 0; i
< n_stack
; i
++)
3093 json_stack_release(stack
+ i
);
3100 int json_parse(const char *input
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3101 return json_parse_internal(&input
, NULL
, flags
, ret
, ret_line
, ret_column
, false);
3104 int json_parse_continue(const char **p
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3105 return json_parse_internal(p
, NULL
, flags
, ret
, ret_line
, ret_column
, true);
3108 int json_parse_file_at(FILE *f
, int dir_fd
, const char *path
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3109 _cleanup_(json_source_unrefp
) JsonSource
*source
= NULL
;
3110 _cleanup_free_
char *text
= NULL
;
3115 r
= read_full_stream(f
, &text
, NULL
);
3117 r
= read_full_file_full(dir_fd
, path
, 0, &text
, NULL
);
3124 source
= json_source_new(path
);
3130 return json_parse_internal(&p
, source
, flags
, ret
, ret_line
, ret_column
, false);
3133 int json_buildv(JsonVariant
**ret
, va_list ap
) {
3134 JsonStack
*stack
= NULL
;
3135 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
3138 assert_return(ret
, -EINVAL
);
3140 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
3143 stack
[0] = (JsonStack
) {
3144 .expect
= EXPECT_TOPLEVEL
,
3148 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
3149 size_t n_subtract
= 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
3150 * have been added to the current variant */
3154 assert(n_stack
> 0);
3155 current
= stack
+ n_stack
- 1;
3157 if (current
->expect
== EXPECT_END
)
3160 command
= va_arg(ap
, int);
3164 case _JSON_BUILD_STRING
: {
3167 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3172 p
= va_arg(ap
, const char *);
3174 if (current
->n_suppress
== 0) {
3175 r
= json_variant_new_string(&add
, p
);
3182 if (current
->expect
== EXPECT_TOPLEVEL
)
3183 current
->expect
= EXPECT_END
;
3184 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3185 current
->expect
= EXPECT_OBJECT_KEY
;
3187 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3192 case _JSON_BUILD_INTEGER
: {
3195 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3200 j
= va_arg(ap
, intmax_t);
3202 if (current
->n_suppress
== 0) {
3203 r
= json_variant_new_integer(&add
, j
);
3210 if (current
->expect
== EXPECT_TOPLEVEL
)
3211 current
->expect
= EXPECT_END
;
3212 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3213 current
->expect
= EXPECT_OBJECT_KEY
;
3215 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3220 case _JSON_BUILD_UNSIGNED
: {
3223 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3228 j
= va_arg(ap
, uintmax_t);
3230 if (current
->n_suppress
== 0) {
3231 r
= json_variant_new_unsigned(&add
, j
);
3238 if (current
->expect
== EXPECT_TOPLEVEL
)
3239 current
->expect
= EXPECT_END
;
3240 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3241 current
->expect
= EXPECT_OBJECT_KEY
;
3243 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3248 case _JSON_BUILD_REAL
: {
3251 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3256 d
= va_arg(ap
, long double);
3258 if (current
->n_suppress
== 0) {
3259 r
= json_variant_new_real(&add
, d
);
3266 if (current
->expect
== EXPECT_TOPLEVEL
)
3267 current
->expect
= EXPECT_END
;
3268 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3269 current
->expect
= EXPECT_OBJECT_KEY
;
3271 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3276 case _JSON_BUILD_BOOLEAN
: {
3279 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3284 b
= va_arg(ap
, int);
3286 if (current
->n_suppress
== 0) {
3287 r
= json_variant_new_boolean(&add
, b
);
3294 if (current
->expect
== EXPECT_TOPLEVEL
)
3295 current
->expect
= EXPECT_END
;
3296 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3297 current
->expect
= EXPECT_OBJECT_KEY
;
3299 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3304 case _JSON_BUILD_NULL
:
3306 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3311 if (current
->n_suppress
== 0) {
3312 r
= json_variant_new_null(&add
);
3319 if (current
->expect
== EXPECT_TOPLEVEL
)
3320 current
->expect
= EXPECT_END
;
3321 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3322 current
->expect
= EXPECT_OBJECT_KEY
;
3324 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3328 case _JSON_BUILD_VARIANT
:
3330 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3335 /* Note that we don't care for current->n_suppress here, after all the variant is already
3336 * allocated anyway... */
3337 add
= va_arg(ap
, JsonVariant
*);
3339 add
= JSON_VARIANT_MAGIC_NULL
;
3341 json_variant_ref(add
);
3345 if (current
->expect
== EXPECT_TOPLEVEL
)
3346 current
->expect
= EXPECT_END
;
3347 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3348 current
->expect
= EXPECT_OBJECT_KEY
;
3350 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3354 case _JSON_BUILD_LITERAL
: {
3357 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3362 l
= va_arg(ap
, const char *);
3365 /* Note that we don't care for current->n_suppress here, we should generate parsing
3366 * errors even in suppressed object properties */
3368 r
= json_parse(l
, 0, &add
, NULL
, NULL
);
3372 add
= JSON_VARIANT_MAGIC_NULL
;
3376 if (current
->expect
== EXPECT_TOPLEVEL
)
3377 current
->expect
= EXPECT_END
;
3378 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3379 current
->expect
= EXPECT_OBJECT_KEY
;
3381 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3386 case _JSON_BUILD_ARRAY_BEGIN
:
3388 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3393 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
3397 current
= stack
+ n_stack
- 1;
3399 if (current
->expect
== EXPECT_TOPLEVEL
)
3400 current
->expect
= EXPECT_END
;
3401 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3402 current
->expect
= EXPECT_OBJECT_KEY
;
3404 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3406 stack
[n_stack
++] = (JsonStack
) {
3407 .expect
= EXPECT_ARRAY_ELEMENT
,
3408 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3409 * new array, then we should
3410 * also suppress all array
3416 case _JSON_BUILD_ARRAY_END
:
3417 if (current
->expect
!= EXPECT_ARRAY_ELEMENT
) {
3422 assert(n_stack
> 1);
3424 if (current
->n_suppress
== 0) {
3425 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
3432 json_stack_release(current
);
3433 n_stack
--, current
--;
3437 case _JSON_BUILD_STRV
: {
3440 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3445 l
= va_arg(ap
, char **);
3447 if (current
->n_suppress
== 0) {
3448 r
= json_variant_new_array_strv(&add
, l
);
3455 if (current
->expect
== EXPECT_TOPLEVEL
)
3456 current
->expect
= EXPECT_END
;
3457 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3458 current
->expect
= EXPECT_OBJECT_KEY
;
3460 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3465 case _JSON_BUILD_OBJECT_BEGIN
:
3467 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3472 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
3476 current
= stack
+ n_stack
- 1;
3478 if (current
->expect
== EXPECT_TOPLEVEL
)
3479 current
->expect
= EXPECT_END
;
3480 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3481 current
->expect
= EXPECT_OBJECT_KEY
;
3483 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3485 stack
[n_stack
++] = (JsonStack
) {
3486 .expect
= EXPECT_OBJECT_KEY
,
3487 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3488 * new object, then we should
3489 * also suppress all object
3495 case _JSON_BUILD_OBJECT_END
:
3497 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3502 assert(n_stack
> 1);
3504 if (current
->n_suppress
== 0) {
3505 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
3512 json_stack_release(current
);
3513 n_stack
--, current
--;
3517 case _JSON_BUILD_PAIR
: {
3520 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3525 n
= va_arg(ap
, const char *);
3527 if (current
->n_suppress
== 0) {
3528 r
= json_variant_new_string(&add
, n
);
3535 current
->expect
= EXPECT_OBJECT_VALUE
;
3539 case _JSON_BUILD_PAIR_CONDITION
: {
3543 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3548 b
= va_arg(ap
, int);
3549 n
= va_arg(ap
, const char *);
3551 if (b
&& current
->n_suppress
== 0) {
3552 r
= json_variant_new_string(&add
, n
);
3557 n_subtract
= 1; /* we generated one item */
3559 if (!b
&& current
->n_suppress
!= (size_t) -1)
3560 current
->n_suppress
+= 2; /* Suppress this one and the next item */
3562 current
->expect
= EXPECT_OBJECT_VALUE
;
3566 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3567 if (add
&& current
->n_suppress
== 0) {
3568 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3573 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3576 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3577 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3578 * on this stack level */
3579 if (current
->n_suppress
!= (size_t) -1) {
3580 if (current
->n_suppress
<= n_subtract
) /* Saturated */
3581 current
->n_suppress
= 0;
3583 current
->n_suppress
-= n_subtract
;
3588 assert(n_stack
== 1);
3589 assert(stack
[0].n_elements
== 1);
3591 *ret
= json_variant_ref(stack
[0].elements
[0]);
3595 for (i
= 0; i
< n_stack
; i
++)
3596 json_stack_release(stack
+ i
);
3603 int json_build(JsonVariant
**ret
, ...) {
3608 r
= json_buildv(ret
, ap
);
3614 int json_log_internal(
3615 JsonVariant
*variant
,
3621 const char *format
, ...) {
3625 unsigned source_line
, source_column
;
3626 char buffer
[LINE_MAX
];
3631 errno
= ERRNO_VALUE(error
);
3633 va_start(ap
, format
);
3634 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
3638 r
= json_variant_get_source(variant
, &source
, &source_line
, &source_column
);
3647 if (source
&& source_line
> 0 && source_column
> 0)
3648 return log_struct_internal(
3649 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3652 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3653 "CONFIG_FILE=%s", source
,
3654 "CONFIG_LINE=%u", source_line
,
3655 "CONFIG_COLUMN=%u", source_column
,
3656 LOG_MESSAGE("%s:%u:%u: %s", source
, source_line
, source_column
, buffer
),
3659 return log_struct_internal(
3660 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3663 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3664 LOG_MESSAGE("%s", buffer
),
3668 int json_dispatch(JsonVariant
*v
, const JsonDispatch table
[], JsonDispatchCallback bad
, JsonDispatchFlags flags
, void *userdata
) {
3669 const JsonDispatch
*p
;
3674 if (!json_variant_is_object(v
)) {
3675 json_log(v
, flags
, 0, "JSON variant is not an object.");
3677 if (flags
& JSON_PERMISSIVE
)
3683 for (p
= table
, m
= 0; p
->name
; p
++)
3686 found
= newa0(bool, m
);
3688 n
= json_variant_elements(v
);
3689 for (i
= 0; i
< n
; i
+= 2) {
3690 JsonVariant
*key
, *value
;
3692 assert_se(key
= json_variant_by_index(v
, i
));
3693 assert_se(value
= json_variant_by_index(v
, i
+1));
3695 for (p
= table
; p
->name
; p
++)
3696 if (p
->name
== (const char*) -1 ||
3697 streq_ptr(json_variant_string(key
), p
->name
))
3700 if (p
->name
) { /* Found a matching entry! :-) */
3701 JsonDispatchFlags merged_flags
;
3703 merged_flags
= flags
| p
->flags
;
3705 if (p
->type
!= _JSON_VARIANT_TYPE_INVALID
&&
3706 !json_variant_has_type(value
, p
->type
)) {
3708 json_log(value
, merged_flags
, 0,
3709 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key
),
3710 json_variant_type_to_string(json_variant_type(value
)), json_variant_type_to_string(p
->type
));
3712 if (merged_flags
& JSON_PERMISSIVE
)
3718 if (found
[p
-table
]) {
3719 json_log(value
, merged_flags
, 0, "Duplicate object field '%s'.", json_variant_string(key
));
3721 if (merged_flags
& JSON_PERMISSIVE
)
3727 found
[p
-table
] = true;
3730 r
= p
->callback(json_variant_string(key
), value
, merged_flags
, (uint8_t*) userdata
+ p
->offset
);
3732 if (merged_flags
& JSON_PERMISSIVE
)
3741 } else { /* Didn't find a matching entry! :-( */
3744 r
= bad(json_variant_string(key
), value
, flags
, userdata
);
3746 if (flags
& JSON_PERMISSIVE
)
3754 json_log(value
, flags
, 0, "Unexpected object field '%s'.", json_variant_string(key
));
3756 if (flags
& JSON_PERMISSIVE
)
3759 return -EADDRNOTAVAIL
;
3764 for (p
= table
; p
->name
; p
++) {
3765 JsonDispatchFlags merged_flags
= p
->flags
| flags
;
3767 if ((merged_flags
& JSON_MANDATORY
) && !found
[p
-table
]) {
3768 json_log(v
, merged_flags
, 0, "Missing object field '%s'.", p
->name
);
3770 if ((merged_flags
& JSON_PERMISSIVE
))
3780 int json_dispatch_boolean(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3786 if (!json_variant_is_boolean(variant
))
3787 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3789 *b
= json_variant_boolean(variant
);
3793 int json_dispatch_tristate(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3799 if (!json_variant_is_boolean(variant
))
3800 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3802 *b
= json_variant_boolean(variant
);
3806 int json_dispatch_integer(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3807 intmax_t *i
= userdata
;
3812 if (!json_variant_is_integer(variant
))
3813 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3815 *i
= json_variant_integer(variant
);
3819 int json_dispatch_unsigned(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3820 uintmax_t *u
= userdata
;
3825 if (!json_variant_is_unsigned(variant
))
3826 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3828 *u
= json_variant_unsigned(variant
);
3832 int json_dispatch_uint32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3833 uint32_t *u
= userdata
;
3838 if (!json_variant_is_unsigned(variant
))
3839 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3841 if (json_variant_unsigned(variant
) > UINT32_MAX
)
3842 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3844 *u
= (uint32_t) json_variant_unsigned(variant
);
3848 int json_dispatch_int32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3849 int32_t *i
= userdata
;
3854 if (!json_variant_is_integer(variant
))
3855 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3857 if (json_variant_integer(variant
) < INT32_MIN
|| json_variant_integer(variant
) > INT32_MAX
)
3858 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3860 *i
= (int32_t) json_variant_integer(variant
);
3864 int json_dispatch_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3865 char **s
= userdata
;
3871 if (json_variant_is_null(variant
)) {
3876 if (!json_variant_is_string(variant
))
3877 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
3879 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(variant
)))
3880 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
3882 r
= free_and_strdup(s
, json_variant_string(variant
));
3884 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
3889 int json_dispatch_strv(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3890 _cleanup_strv_free_
char **l
= NULL
;
3891 char ***s
= userdata
;
3898 if (json_variant_is_null(variant
)) {
3903 /* Let's be flexible here: accept a single string in place of a single-item array */
3904 if (json_variant_is_string(variant
)) {
3905 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(variant
)))
3906 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
3908 l
= strv_new(json_variant_string(variant
));
3912 strv_free_and_replace(*s
, l
);
3916 if (!json_variant_is_array(variant
))
3917 return json_log(variant
, SYNTHETIC_ERRNO(EINVAL
), flags
, "JSON field '%s' is not an array.", strna(name
));
3919 JSON_VARIANT_ARRAY_FOREACH(e
, variant
) {
3920 if (!json_variant_is_string(e
))
3921 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON array element is not a string.");
3923 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(e
)))
3924 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
3926 r
= strv_extend(&l
, json_variant_string(e
));
3928 return json_log(e
, flags
, r
, "Failed to append array element: %m");
3931 strv_free_and_replace(*s
, l
);
3935 int json_dispatch_variant(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3936 JsonVariant
**p
= userdata
;
3941 json_variant_unref(*p
);
3942 *p
= json_variant_ref(variant
);
3947 static int json_cmp_strings(const void *x
, const void *y
) {
3948 JsonVariant
*const *a
= x
, *const *b
= y
;
3950 if (!json_variant_is_string(*a
) || !json_variant_is_string(*b
))
3953 return strcmp(json_variant_string(*a
), json_variant_string(*b
));
3956 int json_variant_sort(JsonVariant
**v
) {
3957 _cleanup_free_ JsonVariant
**a
= NULL
;
3958 JsonVariant
*n
= NULL
;
3964 if (json_variant_is_sorted(*v
))
3967 if (!json_variant_is_object(*v
))
3968 return -EMEDIUMTYPE
;
3970 /* Sorts they key/value pairs in an object variant */
3972 m
= json_variant_elements(*v
);
3973 a
= new(JsonVariant
*, m
);
3977 for (i
= 0; i
< m
; i
++)
3978 a
[i
] = json_variant_by_index(*v
, i
);
3980 qsort(a
, m
/2, sizeof(JsonVariant
*)*2, json_cmp_strings
);
3982 r
= json_variant_new_object(&n
, a
, m
);
3985 if (!n
->sorted
) /* Check if this worked. This will fail if there are multiple identical keys used. */
3988 json_variant_unref(*v
);
3994 int json_variant_normalize(JsonVariant
**v
) {
3995 _cleanup_free_ JsonVariant
**a
= NULL
;
3996 JsonVariant
*n
= NULL
;
4002 if (json_variant_is_normalized(*v
))
4005 if (!json_variant_is_object(*v
) && !json_variant_is_array(*v
))
4006 return -EMEDIUMTYPE
;
4008 /* Sorts the key/value pairs in an object variant anywhere down the tree in the specified variant */
4010 m
= json_variant_elements(*v
);
4011 a
= new(JsonVariant
*, m
);
4015 for (i
= 0; i
< m
; i
++) {
4016 a
[i
] = json_variant_ref(json_variant_by_index(*v
, i
));
4018 r
= json_variant_normalize(a
+ i
);
4023 qsort(a
, m
/2, sizeof(JsonVariant
*)*2, json_cmp_strings
);
4025 if (json_variant_is_object(*v
))
4026 r
= json_variant_new_object(&n
, a
, m
);
4028 assert(json_variant_is_array(*v
));
4029 r
= json_variant_new_array(&n
, a
, m
);
4033 if (!n
->normalized
) { /* Let's see if normalization worked. It will fail if there are multiple
4034 * identical keys used in the same object anywhere, or if there are floating
4035 * point numbers used (see below) */
4040 json_variant_unref(*v
);
4046 for (j
= 0; j
< i
; j
++)
4047 json_variant_unref(a
[j
]);
4052 bool json_variant_is_normalized(JsonVariant
*v
) {
4054 /* For now, let's consider anything containing numbers not expressible as integers as
4055 * non-normalized. That's because we cannot sensibly compare them due to accuracy issues, nor even
4056 * store them if they are too large. */
4057 if (json_variant_is_real(v
) && !json_variant_is_integer(v
) && !json_variant_is_unsigned(v
))
4060 /* The concept only applies to variants that include other variants, i.e. objects and arrays. All
4061 * others are normalized anyway. */
4062 if (!json_variant_is_object(v
) && !json_variant_is_array(v
))
4065 /* Empty objects/arrays don't include any other variant, hence are always normalized too */
4066 if (json_variant_elements(v
) == 0)
4069 return v
->normalized
; /* For everything else there's an explicit boolean we maintain */
4072 bool json_variant_is_sorted(JsonVariant
*v
) {
4074 /* Returns true if all key/value pairs of an object are properly sorted. Note that this only applies
4075 * to objects, not arrays. */
4077 if (!json_variant_is_object(v
))
4079 if (json_variant_elements(v
) <= 1)
4085 static const char* const json_variant_type_table
[_JSON_VARIANT_TYPE_MAX
] = {
4086 [JSON_VARIANT_STRING
] = "string",
4087 [JSON_VARIANT_INTEGER
] = "integer",
4088 [JSON_VARIANT_UNSIGNED
] = "unsigned",
4089 [JSON_VARIANT_REAL
] = "real",
4090 [JSON_VARIANT_NUMBER
] = "number",
4091 [JSON_VARIANT_BOOLEAN
] = "boolean",
4092 [JSON_VARIANT_ARRAY
] = "array",
4093 [JSON_VARIANT_OBJECT
] = "object",
4094 [JSON_VARIANT_NULL
] = "null",
4097 DEFINE_STRING_TABLE_LOOKUP(json_variant_type
, JsonVariantType
);