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 static void json_variant_set(JsonVariant
*a
, JsonVariant
*b
) {
417 b
= json_variant_dereference(b
);
419 a
->type
= JSON_VARIANT_NULL
;
423 a
->type
= json_variant_type(b
);
426 case JSON_VARIANT_INTEGER
:
427 a
->value
.integer
= json_variant_integer(b
);
430 case JSON_VARIANT_UNSIGNED
:
431 a
->value
.unsig
= json_variant_unsigned(b
);
434 case JSON_VARIANT_REAL
:
435 a
->value
.real
= json_variant_real(b
);
438 case JSON_VARIANT_BOOLEAN
:
439 a
->value
.boolean
= json_variant_boolean(b
);
442 case JSON_VARIANT_STRING
: {
445 assert_se(s
= json_variant_string(b
));
447 /* Short strings we can store inline */
448 if (strnlen(s
, INLINE_STRING_MAX
+1) <= INLINE_STRING_MAX
) {
449 strcpy(a
->string
, s
);
453 /* For longer strings, use a reference… */
457 case JSON_VARIANT_ARRAY
:
458 case JSON_VARIANT_OBJECT
:
459 a
->is_reference
= true;
460 a
->reference
= json_variant_ref(json_variant_conservative_formalize(b
));
463 case JSON_VARIANT_NULL
:
467 assert_not_reached("Unexpected variant type");
471 static void json_variant_copy_source(JsonVariant
*v
, JsonVariant
*from
) {
475 if (!json_variant_is_regular(from
))
478 v
->line
= from
->line
;
479 v
->column
= from
->column
;
480 v
->source
= json_source_ref(from
->source
);
483 int json_variant_new_array(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
484 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
485 bool normalized
= true;
487 assert_return(ret
, -EINVAL
);
489 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
492 assert_return(array
, -EINVAL
);
494 v
= new(JsonVariant
, n
+ 1);
500 .type
= JSON_VARIANT_ARRAY
,
503 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
504 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
505 *c
= array
[v
->n_elements
];
508 d
= json_variant_depth(c
);
509 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
519 json_variant_set(w
, c
);
520 json_variant_copy_source(w
, c
);
522 if (!json_variant_is_normalized(c
))
526 v
->normalized
= normalized
;
532 int json_variant_new_array_bytes(JsonVariant
**ret
, const void *p
, size_t n
) {
536 assert_return(ret
, -EINVAL
);
538 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
541 assert_return(p
, -EINVAL
);
543 v
= new(JsonVariant
, n
+ 1);
549 .type
= JSON_VARIANT_ARRAY
,
554 for (i
= 0; i
< n
; i
++) {
555 JsonVariant
*w
= v
+ 1 + i
;
560 .type
= JSON_VARIANT_UNSIGNED
,
561 .value
.unsig
= ((const uint8_t*) p
)[i
],
565 v
->normalized
= true;
571 int json_variant_new_array_strv(JsonVariant
**ret
, char **l
) {
572 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
580 *ret
= JSON_VARIANT_MAGIC_EMPTY_ARRAY
;
584 v
= new(JsonVariant
, n
+ 1);
590 .type
= JSON_VARIANT_ARRAY
,
594 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
595 JsonVariant
*w
= v
+ 1 + v
->n_elements
;
601 .type
= JSON_VARIANT_STRING
,
604 k
= strlen(l
[v
->n_elements
]);
606 if (k
> INLINE_STRING_MAX
) {
607 /* If string is too long, store it as reference. */
609 r
= json_variant_new_string(&w
->reference
, l
[v
->n_elements
]);
613 w
->is_reference
= true;
615 memcpy(w
->string
, l
[v
->n_elements
], k
+1);
618 v
->normalized
= true;
624 int json_variant_new_object(JsonVariant
**ret
, JsonVariant
**array
, size_t n
) {
625 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
626 const char *prev
= NULL
;
627 bool sorted
= true, normalized
= true;
629 assert_return(ret
, -EINVAL
);
631 *ret
= JSON_VARIANT_MAGIC_EMPTY_OBJECT
;
634 assert_return(array
, -EINVAL
);
635 assert_return(n
% 2 == 0, -EINVAL
);
637 v
= new(JsonVariant
, n
+ 1);
643 .type
= JSON_VARIANT_OBJECT
,
646 for (v
->n_elements
= 0; v
->n_elements
< n
; v
->n_elements
++) {
647 JsonVariant
*w
= v
+ 1 + v
->n_elements
,
648 *c
= array
[v
->n_elements
];
651 if ((v
->n_elements
& 1) == 0) {
654 if (!json_variant_is_string(c
))
655 return -EINVAL
; /* Every second one needs to be a string, as it is the key name */
657 assert_se(k
= json_variant_string(c
));
659 if (prev
&& strcmp(k
, prev
) <= 0)
660 sorted
= normalized
= false;
663 } else if (!json_variant_is_normalized(c
))
666 d
= json_variant_depth(c
);
667 if (d
>= DEPTH_MAX
) /* Refuse too deep nesting */
677 json_variant_set(w
, c
);
678 json_variant_copy_source(w
, c
);
681 v
->normalized
= normalized
;
688 static size_t json_variant_size(JsonVariant
* v
) {
690 if (!json_variant_is_regular(v
))
694 return offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*);
698 case JSON_VARIANT_STRING
:
699 return offsetof(JsonVariant
, string
) + strlen(v
->string
) + 1;
701 case JSON_VARIANT_REAL
:
702 return offsetof(JsonVariant
, value
) + sizeof(long double);
704 case JSON_VARIANT_UNSIGNED
:
705 return offsetof(JsonVariant
, value
) + sizeof(uintmax_t);
707 case JSON_VARIANT_INTEGER
:
708 return offsetof(JsonVariant
, value
) + sizeof(intmax_t);
710 case JSON_VARIANT_BOOLEAN
:
711 return offsetof(JsonVariant
, value
) + sizeof(bool);
713 case JSON_VARIANT_ARRAY
:
714 case JSON_VARIANT_OBJECT
:
715 return offsetof(JsonVariant
, n_elements
) + sizeof(size_t);
717 case JSON_VARIANT_NULL
:
718 return offsetof(JsonVariant
, value
);
721 assert_not_reached("unexpected type");
725 static void json_variant_free_inner(JsonVariant
*v
, bool force_sensitive
) {
730 if (!json_variant_is_regular(v
))
733 json_source_unref(v
->source
);
735 sensitive
= v
->sensitive
|| force_sensitive
;
737 if (v
->is_reference
) {
739 json_variant_sensitive(v
->reference
);
741 json_variant_unref(v
->reference
);
745 if (IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
)) {
748 for (i
= 0; i
< v
->n_elements
; i
++)
749 json_variant_free_inner(v
+ 1 + i
, sensitive
);
753 explicit_bzero_safe(v
, json_variant_size(v
));
756 JsonVariant
*json_variant_ref(JsonVariant
*v
) {
759 if (!json_variant_is_regular(v
))
763 json_variant_ref(v
->parent
); /* ref the compounding variant instead */
765 assert(v
->n_ref
> 0);
772 JsonVariant
*json_variant_unref(JsonVariant
*v
) {
775 if (!json_variant_is_regular(v
))
779 json_variant_unref(v
->parent
);
781 assert(v
->n_ref
> 0);
785 json_variant_free_inner(v
, false);
793 void json_variant_unref_many(JsonVariant
**array
, size_t n
) {
796 assert(array
|| n
== 0);
798 for (i
= 0; i
< n
; i
++)
799 json_variant_unref(array
[i
]);
802 const char *json_variant_string(JsonVariant
*v
) {
805 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
807 if (json_variant_is_magic(v
))
809 if (json_variant_is_const_string(v
)) {
810 uintptr_t p
= (uintptr_t) v
;
812 assert((p
& 1) != 0);
813 return (const char*) (p
^ 1U);
817 return json_variant_string(v
->reference
);
818 if (v
->type
!= JSON_VARIANT_STRING
)
824 log_debug("Non-string JSON variant requested as string, returning NULL.");
828 bool json_variant_boolean(JsonVariant
*v
) {
831 if (v
== JSON_VARIANT_MAGIC_TRUE
)
833 if (v
== JSON_VARIANT_MAGIC_FALSE
)
835 if (!json_variant_is_regular(v
))
837 if (v
->type
!= JSON_VARIANT_BOOLEAN
)
840 return json_variant_boolean(v
->reference
);
842 return v
->value
.boolean
;
845 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
849 intmax_t json_variant_integer(JsonVariant
*v
) {
852 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
853 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
854 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
856 if (!json_variant_is_regular(v
))
859 return json_variant_integer(v
->reference
);
863 case JSON_VARIANT_INTEGER
:
864 return v
->value
.integer
;
866 case JSON_VARIANT_UNSIGNED
:
867 if (v
->value
.unsig
<= INTMAX_MAX
)
868 return (intmax_t) v
->value
.unsig
;
870 log_debug("Unsigned integer %ju requested as signed integer and out of range, returning 0.", v
->value
.unsig
);
873 case JSON_VARIANT_REAL
: {
876 converted
= (intmax_t) v
->value
.real
;
878 #pragma GCC diagnostic push
879 #pragma GCC diagnostic ignored "-Wfloat-equal"
880 if ((long double) converted
== v
->value
.real
)
881 #pragma GCC diagnostic pop
884 log_debug("Real %Lg requested as integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
893 log_debug("Non-integer JSON variant requested as integer, returning 0.");
897 uintmax_t json_variant_unsigned(JsonVariant
*v
) {
900 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
901 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
902 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
904 if (!json_variant_is_regular(v
))
907 return json_variant_integer(v
->reference
);
911 case JSON_VARIANT_INTEGER
:
912 if (v
->value
.integer
>= 0)
913 return (uintmax_t) v
->value
.integer
;
915 log_debug("Signed integer %ju requested as unsigned integer and out of range, returning 0.", v
->value
.integer
);
918 case JSON_VARIANT_UNSIGNED
:
919 return v
->value
.unsig
;
921 case JSON_VARIANT_REAL
: {
924 converted
= (uintmax_t) v
->value
.real
;
926 #pragma GCC diagnostic push
927 #pragma GCC diagnostic ignored "-Wfloat-equal"
928 if ((long double) converted
== v
->value
.real
)
929 #pragma GCC diagnostic pop
932 log_debug("Real %Lg requested as unsigned integer, and cannot be converted losslessly, returning 0.", v
->value
.real
);
941 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
945 long double json_variant_real(JsonVariant
*v
) {
948 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
949 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
950 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
952 if (!json_variant_is_regular(v
))
955 return json_variant_real(v
->reference
);
959 case JSON_VARIANT_REAL
:
960 return v
->value
.real
;
962 case JSON_VARIANT_INTEGER
: {
963 long double converted
;
965 converted
= (long double) v
->value
.integer
;
967 if ((intmax_t) converted
== v
->value
.integer
)
970 log_debug("Signed integer %ji requested as real, and cannot be converted losslessly, returning 0.", v
->value
.integer
);
974 case JSON_VARIANT_UNSIGNED
: {
975 long double converted
;
977 converted
= (long double) v
->value
.unsig
;
979 if ((uintmax_t) converted
== v
->value
.unsig
)
982 log_debug("Unsigned integer %ju requested as real, and cannot be converted losslessly, returning 0.", v
->value
.unsig
);
991 log_debug("Non-integer JSON variant requested as integer, returning 0.");
995 bool json_variant_is_negative(JsonVariant
*v
) {
998 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
||
999 v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
||
1000 v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
1002 if (!json_variant_is_regular(v
))
1004 if (v
->is_reference
)
1005 return json_variant_is_negative(v
->reference
);
1007 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
1008 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
1013 case JSON_VARIANT_REAL
:
1014 return v
->value
.real
< 0;
1016 case JSON_VARIANT_INTEGER
:
1017 return v
->value
.integer
< 0;
1019 case JSON_VARIANT_UNSIGNED
:
1027 log_debug("Non-integer JSON variant tested for negativity, returning false.");
1031 bool json_variant_is_blank_object(JsonVariant
*v
) {
1032 /* Returns true if the specified object is null or empty */
1034 json_variant_is_null(v
) ||
1035 (json_variant_is_object(v
) && json_variant_elements(v
) == 0);
1038 bool json_variant_is_blank_array(JsonVariant
*v
) {
1040 json_variant_is_null(v
) ||
1041 (json_variant_is_array(v
) && json_variant_elements(v
) == 0);
1044 JsonVariantType
json_variant_type(JsonVariant
*v
) {
1047 return _JSON_VARIANT_TYPE_INVALID
;
1049 if (json_variant_is_const_string(v
))
1050 return JSON_VARIANT_STRING
;
1052 if (v
== JSON_VARIANT_MAGIC_TRUE
|| v
== JSON_VARIANT_MAGIC_FALSE
)
1053 return JSON_VARIANT_BOOLEAN
;
1055 if (v
== JSON_VARIANT_MAGIC_NULL
)
1056 return JSON_VARIANT_NULL
;
1058 if (v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
)
1059 return JSON_VARIANT_INTEGER
;
1061 if (v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
)
1062 return JSON_VARIANT_UNSIGNED
;
1064 if (v
== JSON_VARIANT_MAGIC_ZERO_REAL
)
1065 return JSON_VARIANT_REAL
;
1067 if (v
== JSON_VARIANT_MAGIC_EMPTY_STRING
)
1068 return JSON_VARIANT_STRING
;
1070 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
)
1071 return JSON_VARIANT_ARRAY
;
1073 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1074 return JSON_VARIANT_OBJECT
;
1079 bool json_variant_has_type(JsonVariant
*v
, JsonVariantType type
) {
1082 v
= json_variant_dereference(v
);
1086 rt
= json_variant_type(v
);
1090 /* If it's a const string, then it only can be a string, and if it is not, it's not */
1091 if (json_variant_is_const_string(v
))
1094 /* All three magic zeroes qualify as integer, unsigned and as real */
1095 if ((v
== JSON_VARIANT_MAGIC_ZERO_INTEGER
|| v
== JSON_VARIANT_MAGIC_ZERO_UNSIGNED
|| v
== JSON_VARIANT_MAGIC_ZERO_REAL
) &&
1096 IN_SET(type
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
, JSON_VARIANT_NUMBER
))
1099 /* All other magic variant types are only equal to themselves */
1100 if (json_variant_is_magic(v
))
1103 /* Handle the "number" pseudo type */
1104 if (type
== JSON_VARIANT_NUMBER
)
1105 return IN_SET(rt
, JSON_VARIANT_INTEGER
, JSON_VARIANT_UNSIGNED
, JSON_VARIANT_REAL
);
1107 /* Integer conversions are OK in many cases */
1108 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_UNSIGNED
)
1109 return v
->value
.integer
>= 0;
1110 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_INTEGER
)
1111 return v
->value
.unsig
<= INTMAX_MAX
;
1113 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1114 if (rt
== JSON_VARIANT_INTEGER
&& type
== JSON_VARIANT_REAL
)
1115 return (intmax_t) (long double) v
->value
.integer
== v
->value
.integer
;
1116 if (rt
== JSON_VARIANT_UNSIGNED
&& type
== JSON_VARIANT_REAL
)
1117 return (uintmax_t) (long double) v
->value
.unsig
== v
->value
.unsig
;
1119 #pragma GCC diagnostic push
1120 #pragma GCC diagnostic ignored "-Wfloat-equal"
1121 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1122 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_INTEGER
)
1123 return (long double) (intmax_t) v
->value
.real
== v
->value
.real
;
1124 if (rt
== JSON_VARIANT_REAL
&& type
== JSON_VARIANT_UNSIGNED
)
1125 return (long double) (uintmax_t) v
->value
.real
== v
->value
.real
;
1126 #pragma GCC diagnostic pop
1131 size_t json_variant_elements(JsonVariant
*v
) {
1134 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1135 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1137 if (!json_variant_is_regular(v
))
1139 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1141 if (v
->is_reference
)
1142 return json_variant_elements(v
->reference
);
1144 return v
->n_elements
;
1147 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1151 JsonVariant
*json_variant_by_index(JsonVariant
*v
, size_t idx
) {
1154 if (v
== JSON_VARIANT_MAGIC_EMPTY_ARRAY
||
1155 v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1157 if (!json_variant_is_regular(v
))
1159 if (!IN_SET(v
->type
, JSON_VARIANT_ARRAY
, JSON_VARIANT_OBJECT
))
1161 if (v
->is_reference
)
1162 return json_variant_by_index(v
->reference
, idx
);
1163 if (idx
>= v
->n_elements
)
1166 return json_variant_conservative_formalize(v
+ 1 + idx
);
1169 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1173 JsonVariant
*json_variant_by_key_full(JsonVariant
*v
, const char *key
, JsonVariant
**ret_key
) {
1180 if (v
== JSON_VARIANT_MAGIC_EMPTY_OBJECT
)
1182 if (!json_variant_is_regular(v
))
1184 if (v
->type
!= JSON_VARIANT_OBJECT
)
1186 if (v
->is_reference
)
1187 return json_variant_by_key(v
->reference
, key
);
1190 size_t a
= 0, b
= v
->n_elements
/2;
1192 /* If the variant is sorted we can use bisection to find the entry we need in O(log(n)) time */
1200 p
= json_variant_dereference(v
+ 1 + i
*2);
1202 assert_se(f
= json_variant_string(p
));
1207 *ret_key
= json_variant_conservative_formalize(v
+ 1 + i
*2);
1209 return json_variant_conservative_formalize(v
+ 1 + i
*2 + 1);
1219 /* The variant is not sorted, hence search for the field linearly */
1220 for (i
= 0; i
< v
->n_elements
; i
+= 2) {
1223 p
= json_variant_dereference(v
+ 1 + i
);
1225 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1228 if (streq(json_variant_string(p
), key
)) {
1231 *ret_key
= json_variant_conservative_formalize(v
+ 1 + i
);
1233 return json_variant_conservative_formalize(v
+ 1 + i
+ 1);
1244 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1251 JsonVariant
*json_variant_by_key(JsonVariant
*v
, const char *key
) {
1252 return json_variant_by_key_full(v
, key
, NULL
);
1255 bool json_variant_equal(JsonVariant
*a
, JsonVariant
*b
) {
1258 a
= json_variant_formalize(a
);
1259 b
= json_variant_formalize(b
);
1264 t
= json_variant_type(a
);
1265 if (!json_variant_has_type(b
, t
))
1270 case JSON_VARIANT_STRING
:
1271 return streq(json_variant_string(a
), json_variant_string(b
));
1273 case JSON_VARIANT_INTEGER
:
1274 return json_variant_integer(a
) == json_variant_integer(b
);
1276 case JSON_VARIANT_UNSIGNED
:
1277 return json_variant_unsigned(a
) == json_variant_unsigned(b
);
1279 case JSON_VARIANT_REAL
:
1280 #pragma GCC diagnostic push
1281 #pragma GCC diagnostic ignored "-Wfloat-equal"
1282 return json_variant_real(a
) == json_variant_real(b
);
1283 #pragma GCC diagnostic pop
1285 case JSON_VARIANT_BOOLEAN
:
1286 return json_variant_boolean(a
) == json_variant_boolean(b
);
1288 case JSON_VARIANT_NULL
:
1291 case JSON_VARIANT_ARRAY
: {
1294 n
= json_variant_elements(a
);
1295 if (n
!= json_variant_elements(b
))
1298 for (i
= 0; i
< n
; i
++) {
1299 if (!json_variant_equal(json_variant_by_index(a
, i
), json_variant_by_index(b
, i
)))
1306 case JSON_VARIANT_OBJECT
: {
1309 n
= json_variant_elements(a
);
1310 if (n
!= json_variant_elements(b
))
1313 /* Iterate through all keys in 'a' */
1314 for (i
= 0; i
< n
; i
+= 2) {
1318 /* Match them against all keys in 'b' */
1319 for (j
= 0; j
< n
; j
+= 2) {
1322 key_b
= json_variant_by_index(b
, j
);
1324 /* During the first iteration unmark everything */
1326 key_b
->is_marked
= false;
1327 else if (key_b
->is_marked
) /* In later iterations if we already marked something, don't bother with it again */
1333 if (json_variant_equal(json_variant_by_index(a
, i
), key_b
) &&
1334 json_variant_equal(json_variant_by_index(a
, i
+1), json_variant_by_index(b
, j
+1))) {
1335 /* Key and values match! */
1336 key_b
->is_marked
= found
= true;
1338 /* In the first iteration we continue the inner loop since we want to mark
1339 * everything, otherwise exit the loop quickly after we found what we were
1354 assert_not_reached("Unknown variant type.");
1358 void json_variant_sensitive(JsonVariant
*v
) {
1361 /* Marks a variant as "sensitive", so that it is erased from memory when it is destroyed. This is a
1362 * one-way operation: as soon as it is marked this way it remains marked this way until it's
1363 * destoryed. A magic variant is never sensitive though, even when asked, since it's too
1364 * basic. Similar, const string variant are never sensitive either, after all they are included in
1365 * the source code as they are, which is not suitable for inclusion of secrets.
1367 * Note that this flag has a recursive effect: when we destroy an object or array we'll propagate the
1368 * flag to all contained variants. And if those are then destroyed this is propagated further down,
1371 v
= json_variant_formalize(v
);
1372 if (!json_variant_is_regular(v
))
1375 v
->sensitive
= true;
1378 int json_variant_get_source(JsonVariant
*v
, const char **ret_source
, unsigned *ret_line
, unsigned *ret_column
) {
1379 assert_return(v
, -EINVAL
);
1382 *ret_source
= json_variant_is_regular(v
) && v
->source
? v
->source
->name
: NULL
;
1385 *ret_line
= json_variant_is_regular(v
) ? v
->line
: 0;
1388 *ret_column
= json_variant_is_regular(v
) ? v
->column
: 0;
1393 static int print_source(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, bool whitespace
) {
1396 if (!FLAGS_SET(flags
, JSON_FORMAT_SOURCE
|JSON_FORMAT_PRETTY
))
1399 if (!json_variant_is_regular(v
))
1402 if (!v
->source
&& v
->line
== 0 && v
->column
== 0)
1405 /* The max width we need to format the line numbers for this source file */
1406 w
= (v
->source
&& v
->source
->max_line
> 0) ?
1407 DECIMAL_STR_WIDTH(v
->source
->max_line
) :
1408 DECIMAL_STR_MAX(unsigned)-1;
1409 k
= (v
->source
&& v
->source
->max_column
> 0) ?
1410 DECIMAL_STR_WIDTH(v
->source
->max_column
) :
1411 DECIMAL_STR_MAX(unsigned) -1;
1416 n
= 1 + (v
->source
? strlen(v
->source
->name
) : 0) +
1417 ((v
->source
&& (v
->line
> 0 || v
->column
> 0)) ? 1 : 0) +
1418 (v
->line
> 0 ? w
: 0) +
1419 (((v
->source
|| v
->line
> 0) && v
->column
> 0) ? 1 : 0) +
1420 (v
->column
> 0 ? k
: 0) +
1423 for (i
= 0; i
< n
; i
++)
1429 fputs(v
->source
->name
, f
);
1430 if (v
->source
&& (v
->line
> 0 || v
->column
> 0))
1433 fprintf(f
, "%*u", (int) w
, v
->line
);
1434 if ((v
->source
|| v
->line
> 0) || v
->column
> 0)
1437 fprintf(f
, "%*u", (int) k
, v
->column
);
1446 static int json_format(FILE *f
, JsonVariant
*v
, JsonFormatFlags flags
, const char *prefix
) {
1452 switch (json_variant_type(v
)) {
1454 case JSON_VARIANT_REAL
: {
1457 loc
= newlocale(LC_NUMERIC_MASK
, "C", (locale_t
) 0);
1458 if (loc
== (locale_t
) 0)
1461 if (flags
& JSON_FORMAT_COLOR
)
1462 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1464 fprintf(f
, "%.*Le", DECIMAL_DIG
, json_variant_real(v
));
1466 if (flags
& JSON_FORMAT_COLOR
)
1467 fputs(ANSI_NORMAL
, f
);
1473 case JSON_VARIANT_INTEGER
:
1474 if (flags
& JSON_FORMAT_COLOR
)
1475 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1477 fprintf(f
, "%" PRIdMAX
, json_variant_integer(v
));
1479 if (flags
& JSON_FORMAT_COLOR
)
1480 fputs(ANSI_NORMAL
, f
);
1483 case JSON_VARIANT_UNSIGNED
:
1484 if (flags
& JSON_FORMAT_COLOR
)
1485 fputs(ANSI_HIGHLIGHT_BLUE
, f
);
1487 fprintf(f
, "%" PRIuMAX
, json_variant_unsigned(v
));
1489 if (flags
& JSON_FORMAT_COLOR
)
1490 fputs(ANSI_NORMAL
, f
);
1493 case JSON_VARIANT_BOOLEAN
:
1495 if (flags
& JSON_FORMAT_COLOR
)
1496 fputs(ANSI_HIGHLIGHT
, f
);
1498 if (json_variant_boolean(v
))
1503 if (flags
& JSON_FORMAT_COLOR
)
1504 fputs(ANSI_NORMAL
, f
);
1508 case JSON_VARIANT_NULL
:
1509 if (flags
& JSON_FORMAT_COLOR
)
1510 fputs(ANSI_HIGHLIGHT
, f
);
1514 if (flags
& JSON_FORMAT_COLOR
)
1515 fputs(ANSI_NORMAL
, f
);
1518 case JSON_VARIANT_STRING
: {
1523 if (flags
& JSON_FORMAT_COLOR
)
1524 fputs(ANSI_GREEN
, f
);
1526 for (q
= json_variant_string(v
); *q
; q
++) {
1559 if ((signed char) *q
>= 0 && *q
< ' ')
1560 fprintf(f
, "\\u%04x", *q
);
1567 if (flags
& JSON_FORMAT_COLOR
)
1568 fputs(ANSI_NORMAL
, f
);
1574 case JSON_VARIANT_ARRAY
: {
1577 n
= json_variant_elements(v
);
1582 _cleanup_free_
char *joined
= NULL
;
1583 const char *prefix2
;
1585 if (flags
& JSON_FORMAT_PRETTY
) {
1586 joined
= strjoin(strempty(prefix
), "\t");
1593 prefix2
= strempty(prefix
);
1597 for (i
= 0; i
< n
; i
++) {
1600 assert_se(e
= json_variant_by_index(v
, i
));
1603 if (flags
& JSON_FORMAT_PRETTY
)
1609 if (flags
& JSON_FORMAT_PRETTY
) {
1610 print_source(f
, e
, flags
, false);
1614 r
= json_format(f
, e
, flags
, prefix2
);
1619 if (flags
& JSON_FORMAT_PRETTY
) {
1621 print_source(f
, v
, flags
, true);
1622 fputs(strempty(prefix
), f
);
1630 case JSON_VARIANT_OBJECT
: {
1633 n
= json_variant_elements(v
);
1638 _cleanup_free_
char *joined
= NULL
;
1639 const char *prefix2
;
1641 if (flags
& JSON_FORMAT_PRETTY
) {
1642 joined
= strjoin(strempty(prefix
), "\t");
1649 prefix2
= strempty(prefix
);
1653 for (i
= 0; i
< n
; i
+= 2) {
1656 e
= json_variant_by_index(v
, i
);
1659 if (flags
& JSON_FORMAT_PRETTY
)
1665 if (flags
& JSON_FORMAT_PRETTY
) {
1666 print_source(f
, e
, flags
, false);
1670 r
= json_format(f
, e
, flags
, prefix2
);
1674 fputs(flags
& JSON_FORMAT_PRETTY
? " : " : ":", f
);
1676 r
= json_format(f
, json_variant_by_index(v
, i
+1), flags
, prefix2
);
1681 if (flags
& JSON_FORMAT_PRETTY
) {
1683 print_source(f
, v
, flags
, true);
1684 fputs(strempty(prefix
), f
);
1693 assert_not_reached("Unexpected variant type.");
1699 int json_variant_format(JsonVariant
*v
, JsonFormatFlags flags
, char **ret
) {
1700 _cleanup_free_
char *s
= NULL
;
1704 /* Returns the length of the generated string (without the terminating NUL),
1705 * or negative on error. */
1707 assert_return(v
, -EINVAL
);
1708 assert_return(ret
, -EINVAL
);
1711 _cleanup_fclose_
FILE *f
= NULL
;
1713 f
= open_memstream_unlocked(&s
, &sz
);
1717 json_variant_dump(v
, flags
, f
, NULL
);
1719 /* Add terminating 0, so that the output buffer is a valid string. */
1722 r
= fflush_and_check(f
);
1730 return (int) sz
- 1;
1733 void json_variant_dump(JsonVariant
*v
, JsonFormatFlags flags
, FILE *f
, const char *prefix
) {
1740 print_source(f
, v
, flags
, false);
1742 if (((flags
& (JSON_FORMAT_COLOR_AUTO
|JSON_FORMAT_COLOR
)) == JSON_FORMAT_COLOR_AUTO
) && colors_enabled())
1743 flags
|= JSON_FORMAT_COLOR
;
1745 if (flags
& JSON_FORMAT_SSE
)
1747 if (flags
& JSON_FORMAT_SEQ
)
1748 fputc('\x1e', f
); /* ASCII Record Separator */
1750 json_format(f
, v
, flags
, prefix
);
1752 if (flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_SEQ
|JSON_FORMAT_SSE
|JSON_FORMAT_NEWLINE
))
1754 if (flags
& JSON_FORMAT_SSE
)
1755 fputc('\n', f
); /* In case of SSE add a second newline */
1758 int json_variant_filter(JsonVariant
**v
, char **to_remove
) {
1759 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
1760 _cleanup_free_ JsonVariant
**array
= NULL
;
1761 size_t i
, n
= 0, k
= 0;
1766 if (json_variant_is_blank_object(*v
))
1768 if (!json_variant_is_object(*v
))
1771 if (strv_isempty(to_remove
))
1774 for (i
= 0; i
< json_variant_elements(*v
); i
+= 2) {
1777 p
= json_variant_by_index(*v
, i
);
1778 if (!json_variant_has_type(p
, JSON_VARIANT_STRING
))
1781 if (strv_contains(to_remove
, json_variant_string(p
))) {
1783 array
= new(JsonVariant
*, json_variant_elements(*v
) - 2);
1787 for (k
= 0; k
< i
; k
++)
1788 array
[k
] = json_variant_by_index(*v
, k
);
1794 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1801 r
= json_variant_new_object(&w
, array
, k
);
1805 json_variant_unref(*v
);
1811 int json_variant_set_field(JsonVariant
**v
, const char *field
, JsonVariant
*value
) {
1812 _cleanup_(json_variant_unrefp
) JsonVariant
*field_variant
= NULL
, *w
= NULL
;
1813 _cleanup_free_ JsonVariant
**array
= NULL
;
1820 if (json_variant_is_blank_object(*v
)) {
1821 array
= new(JsonVariant
*, 2);
1826 if (!json_variant_is_object(*v
))
1829 for (i
= 0; i
< json_variant_elements(*v
); i
+= 2) {
1832 p
= json_variant_by_index(*v
, i
);
1833 if (!json_variant_is_string(p
))
1836 if (streq(json_variant_string(p
), field
)) {
1839 array
= new(JsonVariant
*, json_variant_elements(*v
));
1843 for (k
= 0; k
< i
; k
++)
1844 array
[k
] = json_variant_by_index(*v
, k
);
1849 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1854 array
= new(JsonVariant
*, json_variant_elements(*v
) + 2);
1858 for (k
= 0; k
< json_variant_elements(*v
); k
++)
1859 array
[k
] = json_variant_by_index(*v
, k
);
1863 r
= json_variant_new_string(&field_variant
, field
);
1867 array
[k
++] = field_variant
;
1870 r
= json_variant_new_object(&w
, array
, k
);
1874 json_variant_unref(*v
);
1880 int json_variant_set_field_string(JsonVariant
**v
, const char *field
, const char *value
) {
1881 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1884 r
= json_variant_new_string(&m
, value
);
1888 return json_variant_set_field(v
, field
, m
);
1891 int json_variant_set_field_unsigned(JsonVariant
**v
, const char *field
, uintmax_t u
) {
1892 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1895 r
= json_variant_new_unsigned(&m
, u
);
1899 return json_variant_set_field(v
, field
, m
);
1902 int json_variant_merge(JsonVariant
**v
, JsonVariant
*m
) {
1903 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
1904 _cleanup_free_ JsonVariant
**array
= NULL
;
1905 size_t v_elements
, m_elements
, i
, k
;
1906 bool v_blank
, m_blank
;
1909 m
= json_variant_dereference(m
);
1911 v_blank
= json_variant_is_blank_object(*v
);
1912 m_blank
= json_variant_is_blank_object(m
);
1914 if (!v_blank
&& !json_variant_is_object(*v
))
1916 if (!m_blank
&& !json_variant_is_object(m
))
1920 return 0; /* nothing to do */
1923 json_variant_unref(*v
);
1924 *v
= json_variant_ref(m
);
1928 v_elements
= json_variant_elements(*v
);
1929 m_elements
= json_variant_elements(m
);
1930 if (v_elements
> SIZE_MAX
- m_elements
) /* overflow check */
1933 array
= new(JsonVariant
*, v_elements
+ m_elements
);
1938 for (i
= 0; i
< v_elements
; i
+= 2) {
1941 u
= json_variant_by_index(*v
, i
);
1942 if (!json_variant_is_string(u
))
1945 if (json_variant_by_key(m
, json_variant_string(u
)))
1946 continue; /* skip if exists in second variant */
1949 array
[k
++] = json_variant_by_index(*v
, i
+ 1);
1952 for (i
= 0; i
< m_elements
; i
++)
1953 array
[k
++] = json_variant_by_index(m
, i
);
1955 r
= json_variant_new_object(&w
, array
, k
);
1959 json_variant_unref(*v
);
1965 int json_variant_strv(JsonVariant
*v
, char ***ret
) {
1973 if (!v
|| json_variant_is_null(v
)) {
1982 if (!json_variant_is_array(v
))
1985 sensitive
= v
->sensitive
;
1987 n
= json_variant_elements(v
);
1988 l
= new(char*, n
+1);
1992 for (i
= 0; i
< n
; i
++) {
1995 assert_se(e
= json_variant_by_index(v
, i
));
1996 sensitive
= sensitive
|| e
->sensitive
;
1998 if (!json_variant_is_string(e
)) {
2004 l
[i
] = strdup(json_variant_string(e
));
2025 static int json_variant_copy(JsonVariant
**nv
, JsonVariant
*v
) {
2035 /* Let's copy the simple types literally, and the larger types by references */
2036 t
= json_variant_type(v
);
2038 case JSON_VARIANT_INTEGER
:
2039 k
= sizeof(intmax_t);
2040 value
.integer
= json_variant_integer(v
);
2044 case JSON_VARIANT_UNSIGNED
:
2045 k
= sizeof(uintmax_t);
2046 value
.unsig
= json_variant_unsigned(v
);
2050 case JSON_VARIANT_REAL
:
2051 k
= sizeof(long double);
2052 value
.real
= json_variant_real(v
);
2056 case JSON_VARIANT_BOOLEAN
:
2058 value
.boolean
= json_variant_boolean(v
);
2062 case JSON_VARIANT_NULL
:
2067 case JSON_VARIANT_STRING
:
2068 source
= json_variant_string(v
);
2069 k
= strnlen(source
, INLINE_STRING_MAX
+ 1);
2070 if (k
<= INLINE_STRING_MAX
) {
2078 /* Everything else copy by reference */
2080 c
= malloc0(MAX(sizeof(JsonVariant
),
2081 offsetof(JsonVariant
, reference
) + sizeof(JsonVariant
*)));
2087 c
->is_reference
= true;
2088 c
->reference
= json_variant_ref(json_variant_formalize(v
));
2094 c
= malloc0(MAX(sizeof(JsonVariant
),
2095 offsetof(JsonVariant
, value
) + k
));
2102 memcpy_safe(&c
->value
, source
, k
);
2108 static bool json_single_ref(JsonVariant
*v
) {
2110 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
2112 if (!json_variant_is_regular(v
))
2116 return json_single_ref(v
->parent
);
2118 assert(v
->n_ref
> 0);
2119 return v
->n_ref
== 1;
2122 static int json_variant_set_source(JsonVariant
**v
, JsonSource
*source
, unsigned line
, unsigned column
) {
2128 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole referencer of
2129 * the object. If not, allocates a new object, possibly a surrogate for the original one */
2134 if (source
&& line
> source
->max_line
)
2135 source
->max_line
= line
;
2136 if (source
&& column
> source
->max_column
)
2137 source
->max_column
= column
;
2139 if (!json_variant_is_regular(*v
)) {
2141 if (!source
&& line
== 0 && column
== 0)
2145 if (json_source_equal((*v
)->source
, source
) &&
2146 (*v
)->line
== line
&&
2147 (*v
)->column
== column
)
2150 if (json_single_ref(*v
)) { /* Sole reference? */
2151 json_source_unref((*v
)->source
);
2152 (*v
)->source
= json_source_ref(source
);
2154 (*v
)->column
= column
;
2159 r
= json_variant_copy(&w
, *v
);
2163 assert(json_variant_is_regular(w
));
2164 assert(!w
->is_embedded
);
2165 assert(w
->n_ref
== 1);
2168 w
->source
= json_source_ref(source
);
2172 json_variant_unref(*v
);
2178 static void inc_lines_columns(unsigned *line
, unsigned *column
, const char *s
, size_t n
) {
2181 assert(s
|| n
== 0);
2187 } else if ((signed char) *s
>= 0 && *s
< 127) /* Process ASCII chars quickly */
2192 w
= utf8_encoded_valid_unichar(s
, n
);
2193 if (w
< 0) /* count invalid unichars as normal characters */
2195 else if ((size_t) w
> n
) /* never read more than the specified number of characters */
2210 static int unhex_ucs2(const char *c
, uint16_t *ret
) {
2217 aa
= unhexchar(c
[0]);
2221 bb
= unhexchar(c
[1]);
2225 cc
= unhexchar(c
[2]);
2229 dd
= unhexchar(c
[3]);
2233 x
= ((uint16_t) aa
<< 12) |
2234 ((uint16_t) bb
<< 8) |
2235 ((uint16_t) cc
<< 4) |
2246 static int json_parse_string(const char **p
, char **ret
) {
2247 _cleanup_free_
char *s
= NULL
;
2248 size_t n
= 0, allocated
= 0;
2269 /* Check for control characters 0x00..0x1f */
2270 if (*c
> 0 && *c
< ' ')
2273 /* Check for control character 0x7f */
2288 return JSON_TOKEN_STRING
;
2298 if (IN_SET(*c
, '"', '\\', '/'))
2310 else if (*c
== 'u') {
2314 r
= unhex_ucs2(c
+ 1, &x
);
2320 if (!GREEDY_REALLOC(s
, allocated
, n
+ 5))
2323 if (!utf16_is_surrogate(x
))
2324 n
+= utf8_encode_unichar(s
+ n
, (char32_t
) x
);
2325 else if (utf16_is_trailing_surrogate(x
))
2330 if (c
[0] != '\\' || c
[1] != 'u')
2333 r
= unhex_ucs2(c
+ 2, &y
);
2339 if (!utf16_is_trailing_surrogate(y
))
2342 n
+= utf8_encode_unichar(s
+ n
, utf16_surrogate_pair_to_unichar(x
, y
));
2349 if (!GREEDY_REALLOC(s
, allocated
, n
+ 2))
2357 len
= utf8_encoded_valid_unichar(c
, (size_t) -1);
2361 if (!GREEDY_REALLOC(s
, allocated
, n
+ len
+ 1))
2364 memcpy(s
+ n
, c
, len
);
2370 static int json_parse_number(const char **p
, JsonValue
*ret
) {
2371 bool negative
= false, exponent_negative
= false, is_real
= false;
2372 long double x
= 0.0, y
= 0.0, exponent
= 0.0, shift
= 1.0;
2391 if (!strchr("123456789", *c
) || *c
== 0)
2398 if (i
< INTMAX_MIN
/ 10) /* overflow */
2401 intmax_t t
= 10 * i
;
2403 if (t
< INTMAX_MIN
+ (*c
- '0')) /* overflow */
2409 if (u
> UINTMAX_MAX
/ 10) /* overflow */
2412 uintmax_t t
= 10 * u
;
2414 if (t
> UINTMAX_MAX
- (*c
- '0')) /* overflow */
2422 x
= 10.0 * x
+ (*c
- '0');
2425 } while (strchr("0123456789", *c
) && *c
!= 0);
2432 if (!strchr("0123456789", *c
) || *c
== 0)
2436 y
= 10.0 * y
+ (*c
- '0');
2437 shift
= 10.0 * shift
;
2439 } while (strchr("0123456789", *c
) && *c
!= 0);
2442 if (IN_SET(*c
, 'e', 'E')) {
2447 exponent_negative
= true;
2449 } else if (*c
== '+')
2452 if (!strchr("0123456789", *c
) || *c
== 0)
2456 exponent
= 10.0 * exponent
+ (*c
- '0');
2458 } while (strchr("0123456789", *c
) && *c
!= 0);
2464 ret
->real
= ((negative
? -1.0 : 1.0) * (x
+ (y
/ shift
))) * exp10l((exponent_negative
? -1.0 : 1.0) * exponent
);
2465 return JSON_TOKEN_REAL
;
2466 } else if (negative
) {
2468 return JSON_TOKEN_INTEGER
;
2471 return JSON_TOKEN_UNSIGNED
;
2478 JsonValue
*ret_value
,
2479 unsigned *ret_line
, /* 'ret_line' returns the line at the beginning of this token */
2480 unsigned *ret_column
,
2482 unsigned *line
, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2485 unsigned start_line
, start_column
;
2486 const char *start
, *c
;
2506 t
= PTR_TO_INT(*state
);
2507 if (t
== STATE_NULL
) {
2513 /* Skip over the whitespace */
2514 n
= strspn(*p
, WHITESPACE
);
2515 inc_lines_columns(line
, column
, *p
, n
);
2518 /* Remember where we started processing this token */
2521 start_column
= *column
;
2525 *ret_value
= JSON_VALUE_NULL
;
2536 *state
= INT_TO_PTR(STATE_VALUE
);
2537 r
= JSON_TOKEN_OBJECT_OPEN
;
2540 } else if (*c
== '}') {
2542 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2543 r
= JSON_TOKEN_OBJECT_CLOSE
;
2546 } else if (*c
== '[') {
2548 *state
= INT_TO_PTR(STATE_VALUE
);
2549 r
= JSON_TOKEN_ARRAY_OPEN
;
2552 } else if (*c
== ']') {
2554 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2555 r
= JSON_TOKEN_ARRAY_CLOSE
;
2558 } else if (*c
== '"') {
2560 r
= json_parse_string(&c
, ret_string
);
2564 *ret_value
= JSON_VALUE_NULL
;
2565 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2568 } else if (strchr("-0123456789", *c
)) {
2570 r
= json_parse_number(&c
, ret_value
);
2575 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2578 } else if (startswith(c
, "true")) {
2580 ret_value
->boolean
= true;
2582 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2583 r
= JSON_TOKEN_BOOLEAN
;
2586 } else if (startswith(c
, "false")) {
2588 ret_value
->boolean
= false;
2590 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2591 r
= JSON_TOKEN_BOOLEAN
;
2594 } else if (startswith(c
, "null")) {
2596 *ret_value
= JSON_VALUE_NULL
;
2598 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2599 r
= JSON_TOKEN_NULL
;
2606 case STATE_VALUE_POST
:
2610 *state
= INT_TO_PTR(STATE_VALUE
);
2611 r
= JSON_TOKEN_COLON
;
2614 } else if (*c
== ',') {
2616 *state
= INT_TO_PTR(STATE_VALUE
);
2617 r
= JSON_TOKEN_COMMA
;
2620 } else if (*c
== '}') {
2622 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2623 r
= JSON_TOKEN_OBJECT_CLOSE
;
2626 } else if (*c
== ']') {
2628 *state
= INT_TO_PTR(STATE_VALUE_POST
);
2629 r
= JSON_TOKEN_ARRAY_CLOSE
;
2636 assert_not_reached("Unexpected tokenizer state");
2641 *ret_value
= JSON_VALUE_NULL
;
2644 inc_lines_columns(line
, column
, start
, c
- start
);
2647 *ret_line
= start_line
;
2648 *ret_column
= start_column
;
2653 typedef enum JsonExpect
{
2654 /* The following values are used by json_parse() */
2657 EXPECT_OBJECT_FIRST_KEY
,
2658 EXPECT_OBJECT_NEXT_KEY
,
2659 EXPECT_OBJECT_COLON
,
2660 EXPECT_OBJECT_VALUE
,
2661 EXPECT_OBJECT_COMMA
,
2662 EXPECT_ARRAY_FIRST_ELEMENT
,
2663 EXPECT_ARRAY_NEXT_ELEMENT
,
2666 /* And these are used by json_build() */
2667 EXPECT_ARRAY_ELEMENT
,
2671 typedef struct JsonStack
{
2673 JsonVariant
**elements
;
2674 size_t n_elements
, n_elements_allocated
;
2675 unsigned line_before
;
2676 unsigned column_before
;
2677 size_t n_suppress
; /* When building: if > 0, suppress this many subsequent elements. If == (size_t) -1, suppress all subsequent elements */
2680 static void json_stack_release(JsonStack
*s
) {
2683 json_variant_unref_many(s
->elements
, s
->n_elements
);
2684 s
->elements
= mfree(s
->elements
);
2687 static int json_parse_internal(
2690 JsonParseFlags flags
,
2694 bool continue_end
) {
2696 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
2697 unsigned line_buffer
= 0, column_buffer
= 0;
2698 void *tokenizer_state
= NULL
;
2699 JsonStack
*stack
= NULL
;
2703 assert_return(input
, -EINVAL
);
2704 assert_return(ret
, -EINVAL
);
2708 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
2711 stack
[0] = (JsonStack
) {
2712 .expect
= EXPECT_TOPLEVEL
,
2716 line
= &line_buffer
;
2718 column
= &column_buffer
;
2721 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
2722 _cleanup_free_
char *string
= NULL
;
2723 unsigned line_token
, column_token
;
2728 assert(n_stack
> 0);
2729 current
= stack
+ n_stack
- 1;
2731 if (continue_end
&& current
->expect
== EXPECT_END
)
2734 token
= json_tokenize(&p
, &string
, &value
, &line_token
, &column_token
, &tokenizer_state
, line
, column
);
2742 case JSON_TOKEN_END
:
2743 if (current
->expect
!= EXPECT_END
) {
2748 assert(current
->n_elements
== 1);
2749 assert(n_stack
== 1);
2752 case JSON_TOKEN_COLON
:
2754 if (current
->expect
!= EXPECT_OBJECT_COLON
) {
2759 current
->expect
= EXPECT_OBJECT_VALUE
;
2762 case JSON_TOKEN_COMMA
:
2764 if (current
->expect
== EXPECT_OBJECT_COMMA
)
2765 current
->expect
= EXPECT_OBJECT_NEXT_KEY
;
2766 else if (current
->expect
== EXPECT_ARRAY_COMMA
)
2767 current
->expect
= EXPECT_ARRAY_NEXT_ELEMENT
;
2775 case JSON_TOKEN_OBJECT_OPEN
:
2777 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2782 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2786 current
= stack
+ n_stack
- 1;
2788 /* Prepare the expect for when we return from the child */
2789 if (current
->expect
== EXPECT_TOPLEVEL
)
2790 current
->expect
= EXPECT_END
;
2791 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2792 current
->expect
= EXPECT_OBJECT_COMMA
;
2794 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2795 current
->expect
= EXPECT_ARRAY_COMMA
;
2798 stack
[n_stack
++] = (JsonStack
) {
2799 .expect
= EXPECT_OBJECT_FIRST_KEY
,
2800 .line_before
= line_token
,
2801 .column_before
= column_token
,
2804 current
= stack
+ n_stack
- 1;
2807 case JSON_TOKEN_OBJECT_CLOSE
:
2808 if (!IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_COMMA
)) {
2813 assert(n_stack
> 1);
2815 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
2819 line_token
= current
->line_before
;
2820 column_token
= current
->column_before
;
2822 json_stack_release(current
);
2823 n_stack
--, current
--;
2827 case JSON_TOKEN_ARRAY_OPEN
:
2828 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2833 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
2837 current
= stack
+ n_stack
- 1;
2839 /* Prepare the expect for when we return from the child */
2840 if (current
->expect
== EXPECT_TOPLEVEL
)
2841 current
->expect
= EXPECT_END
;
2842 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2843 current
->expect
= EXPECT_OBJECT_COMMA
;
2845 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2846 current
->expect
= EXPECT_ARRAY_COMMA
;
2849 stack
[n_stack
++] = (JsonStack
) {
2850 .expect
= EXPECT_ARRAY_FIRST_ELEMENT
,
2851 .line_before
= line_token
,
2852 .column_before
= column_token
,
2857 case JSON_TOKEN_ARRAY_CLOSE
:
2858 if (!IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_COMMA
)) {
2863 assert(n_stack
> 1);
2865 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
2869 line_token
= current
->line_before
;
2870 column_token
= current
->column_before
;
2872 json_stack_release(current
);
2873 n_stack
--, current
--;
2876 case JSON_TOKEN_STRING
:
2877 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
)) {
2882 r
= json_variant_new_string(&add
, string
);
2886 if (current
->expect
== EXPECT_TOPLEVEL
)
2887 current
->expect
= EXPECT_END
;
2888 else if (IN_SET(current
->expect
, EXPECT_OBJECT_FIRST_KEY
, EXPECT_OBJECT_NEXT_KEY
))
2889 current
->expect
= EXPECT_OBJECT_COLON
;
2890 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2891 current
->expect
= EXPECT_OBJECT_COMMA
;
2893 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2894 current
->expect
= EXPECT_ARRAY_COMMA
;
2899 case JSON_TOKEN_REAL
:
2900 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2905 r
= json_variant_new_real(&add
, value
.real
);
2909 if (current
->expect
== EXPECT_TOPLEVEL
)
2910 current
->expect
= EXPECT_END
;
2911 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2912 current
->expect
= EXPECT_OBJECT_COMMA
;
2914 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2915 current
->expect
= EXPECT_ARRAY_COMMA
;
2920 case JSON_TOKEN_INTEGER
:
2921 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2926 r
= json_variant_new_integer(&add
, value
.integer
);
2930 if (current
->expect
== EXPECT_TOPLEVEL
)
2931 current
->expect
= EXPECT_END
;
2932 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2933 current
->expect
= EXPECT_OBJECT_COMMA
;
2935 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2936 current
->expect
= EXPECT_ARRAY_COMMA
;
2941 case JSON_TOKEN_UNSIGNED
:
2942 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2947 r
= json_variant_new_unsigned(&add
, value
.unsig
);
2951 if (current
->expect
== EXPECT_TOPLEVEL
)
2952 current
->expect
= EXPECT_END
;
2953 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2954 current
->expect
= EXPECT_OBJECT_COMMA
;
2956 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2957 current
->expect
= EXPECT_ARRAY_COMMA
;
2962 case JSON_TOKEN_BOOLEAN
:
2963 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2968 r
= json_variant_new_boolean(&add
, value
.boolean
);
2972 if (current
->expect
== EXPECT_TOPLEVEL
)
2973 current
->expect
= EXPECT_END
;
2974 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2975 current
->expect
= EXPECT_OBJECT_COMMA
;
2977 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2978 current
->expect
= EXPECT_ARRAY_COMMA
;
2983 case JSON_TOKEN_NULL
:
2984 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
)) {
2989 r
= json_variant_new_null(&add
);
2993 if (current
->expect
== EXPECT_TOPLEVEL
)
2994 current
->expect
= EXPECT_END
;
2995 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
2996 current
->expect
= EXPECT_OBJECT_COMMA
;
2998 assert(IN_SET(current
->expect
, EXPECT_ARRAY_FIRST_ELEMENT
, EXPECT_ARRAY_NEXT_ELEMENT
));
2999 current
->expect
= EXPECT_ARRAY_COMMA
;
3005 assert_not_reached("Unexpected token");
3009 /* If we are asked to make this parsed object sensitive, then let's apply this
3010 * immediately after allocating each variant, so that when we abort half-way
3011 * everything we already allocated that is then freed is correctly marked. */
3012 if (FLAGS_SET(flags
, JSON_PARSE_SENSITIVE
))
3013 json_variant_sensitive(add
);
3015 (void) json_variant_set_source(&add
, source
, line_token
, column_token
);
3017 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3022 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3027 assert(n_stack
== 1);
3028 assert(stack
[0].n_elements
== 1);
3030 *ret
= json_variant_ref(stack
[0].elements
[0]);
3035 for (i
= 0; i
< n_stack
; i
++)
3036 json_stack_release(stack
+ i
);
3043 int json_parse(const char *input
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3044 return json_parse_internal(&input
, NULL
, flags
, ret
, ret_line
, ret_column
, false);
3047 int json_parse_continue(const char **p
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3048 return json_parse_internal(p
, NULL
, flags
, ret
, ret_line
, ret_column
, true);
3051 int json_parse_file_at(FILE *f
, int dir_fd
, const char *path
, JsonParseFlags flags
, JsonVariant
**ret
, unsigned *ret_line
, unsigned *ret_column
) {
3052 _cleanup_(json_source_unrefp
) JsonSource
*source
= NULL
;
3053 _cleanup_free_
char *text
= NULL
;
3058 r
= read_full_stream(f
, &text
, NULL
);
3060 r
= read_full_file_full(dir_fd
, path
, 0, &text
, NULL
);
3067 source
= json_source_new(path
);
3073 return json_parse_internal(&p
, source
, flags
, ret
, ret_line
, ret_column
, false);
3076 int json_buildv(JsonVariant
**ret
, va_list ap
) {
3077 JsonStack
*stack
= NULL
;
3078 size_t n_stack
= 1, n_stack_allocated
= 0, i
;
3081 assert_return(ret
, -EINVAL
);
3083 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
))
3086 stack
[0] = (JsonStack
) {
3087 .expect
= EXPECT_TOPLEVEL
,
3091 _cleanup_(json_variant_unrefp
) JsonVariant
*add
= NULL
;
3092 size_t n_subtract
= 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
3093 * have been added to the current variant */
3097 assert(n_stack
> 0);
3098 current
= stack
+ n_stack
- 1;
3100 if (current
->expect
== EXPECT_END
)
3103 command
= va_arg(ap
, int);
3107 case _JSON_BUILD_STRING
: {
3110 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3115 p
= va_arg(ap
, const char *);
3117 if (current
->n_suppress
== 0) {
3118 r
= json_variant_new_string(&add
, p
);
3125 if (current
->expect
== EXPECT_TOPLEVEL
)
3126 current
->expect
= EXPECT_END
;
3127 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3128 current
->expect
= EXPECT_OBJECT_KEY
;
3130 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3135 case _JSON_BUILD_INTEGER
: {
3138 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3143 j
= va_arg(ap
, intmax_t);
3145 if (current
->n_suppress
== 0) {
3146 r
= json_variant_new_integer(&add
, j
);
3153 if (current
->expect
== EXPECT_TOPLEVEL
)
3154 current
->expect
= EXPECT_END
;
3155 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3156 current
->expect
= EXPECT_OBJECT_KEY
;
3158 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3163 case _JSON_BUILD_UNSIGNED
: {
3166 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3171 j
= va_arg(ap
, uintmax_t);
3173 if (current
->n_suppress
== 0) {
3174 r
= json_variant_new_unsigned(&add
, j
);
3181 if (current
->expect
== EXPECT_TOPLEVEL
)
3182 current
->expect
= EXPECT_END
;
3183 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3184 current
->expect
= EXPECT_OBJECT_KEY
;
3186 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3191 case _JSON_BUILD_REAL
: {
3194 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3199 d
= va_arg(ap
, long double);
3201 if (current
->n_suppress
== 0) {
3202 r
= json_variant_new_real(&add
, d
);
3209 if (current
->expect
== EXPECT_TOPLEVEL
)
3210 current
->expect
= EXPECT_END
;
3211 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3212 current
->expect
= EXPECT_OBJECT_KEY
;
3214 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3219 case _JSON_BUILD_BOOLEAN
: {
3222 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3227 b
= va_arg(ap
, int);
3229 if (current
->n_suppress
== 0) {
3230 r
= json_variant_new_boolean(&add
, b
);
3237 if (current
->expect
== EXPECT_TOPLEVEL
)
3238 current
->expect
= EXPECT_END
;
3239 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3240 current
->expect
= EXPECT_OBJECT_KEY
;
3242 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3247 case _JSON_BUILD_NULL
:
3249 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3254 if (current
->n_suppress
== 0) {
3255 r
= json_variant_new_null(&add
);
3262 if (current
->expect
== EXPECT_TOPLEVEL
)
3263 current
->expect
= EXPECT_END
;
3264 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3265 current
->expect
= EXPECT_OBJECT_KEY
;
3267 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3271 case _JSON_BUILD_VARIANT
:
3273 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3278 /* Note that we don't care for current->n_suppress here, after all the variant is already
3279 * allocated anyway... */
3280 add
= va_arg(ap
, JsonVariant
*);
3282 add
= JSON_VARIANT_MAGIC_NULL
;
3284 json_variant_ref(add
);
3288 if (current
->expect
== EXPECT_TOPLEVEL
)
3289 current
->expect
= EXPECT_END
;
3290 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3291 current
->expect
= EXPECT_OBJECT_KEY
;
3293 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3297 case _JSON_BUILD_LITERAL
: {
3300 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3305 l
= va_arg(ap
, const char *);
3308 /* Note that we don't care for current->n_suppress here, we should generate parsing
3309 * errors even in suppressed object properties */
3311 r
= json_parse(l
, 0, &add
, NULL
, NULL
);
3315 add
= JSON_VARIANT_MAGIC_NULL
;
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
);
3329 case _JSON_BUILD_ARRAY_BEGIN
:
3331 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3336 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
3340 current
= stack
+ n_stack
- 1;
3342 if (current
->expect
== EXPECT_TOPLEVEL
)
3343 current
->expect
= EXPECT_END
;
3344 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3345 current
->expect
= EXPECT_OBJECT_KEY
;
3347 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3349 stack
[n_stack
++] = (JsonStack
) {
3350 .expect
= EXPECT_ARRAY_ELEMENT
,
3351 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3352 * new array, then we should
3353 * also suppress all array
3359 case _JSON_BUILD_ARRAY_END
:
3360 if (current
->expect
!= EXPECT_ARRAY_ELEMENT
) {
3365 assert(n_stack
> 1);
3367 if (current
->n_suppress
== 0) {
3368 r
= json_variant_new_array(&add
, current
->elements
, current
->n_elements
);
3375 json_stack_release(current
);
3376 n_stack
--, current
--;
3380 case _JSON_BUILD_STRV
: {
3383 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3388 l
= va_arg(ap
, char **);
3390 if (current
->n_suppress
== 0) {
3391 r
= json_variant_new_array_strv(&add
, l
);
3398 if (current
->expect
== EXPECT_TOPLEVEL
)
3399 current
->expect
= EXPECT_END
;
3400 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3401 current
->expect
= EXPECT_OBJECT_KEY
;
3403 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3408 case _JSON_BUILD_OBJECT_BEGIN
:
3410 if (!IN_SET(current
->expect
, EXPECT_TOPLEVEL
, EXPECT_OBJECT_VALUE
, EXPECT_ARRAY_ELEMENT
)) {
3415 if (!GREEDY_REALLOC(stack
, n_stack_allocated
, n_stack
+1)) {
3419 current
= stack
+ n_stack
- 1;
3421 if (current
->expect
== EXPECT_TOPLEVEL
)
3422 current
->expect
= EXPECT_END
;
3423 else if (current
->expect
== EXPECT_OBJECT_VALUE
)
3424 current
->expect
= EXPECT_OBJECT_KEY
;
3426 assert(current
->expect
== EXPECT_ARRAY_ELEMENT
);
3428 stack
[n_stack
++] = (JsonStack
) {
3429 .expect
= EXPECT_OBJECT_KEY
,
3430 .n_suppress
= current
->n_suppress
!= 0 ? (size_t) -1 : 0, /* if we shall suppress the
3431 * new object, then we should
3432 * also suppress all object
3438 case _JSON_BUILD_OBJECT_END
:
3440 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3445 assert(n_stack
> 1);
3447 if (current
->n_suppress
== 0) {
3448 r
= json_variant_new_object(&add
, current
->elements
, current
->n_elements
);
3455 json_stack_release(current
);
3456 n_stack
--, current
--;
3460 case _JSON_BUILD_PAIR
: {
3463 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3468 n
= va_arg(ap
, const char *);
3470 if (current
->n_suppress
== 0) {
3471 r
= json_variant_new_string(&add
, n
);
3478 current
->expect
= EXPECT_OBJECT_VALUE
;
3482 case _JSON_BUILD_PAIR_CONDITION
: {
3486 if (current
->expect
!= EXPECT_OBJECT_KEY
) {
3491 b
= va_arg(ap
, int);
3492 n
= va_arg(ap
, const char *);
3494 if (b
&& current
->n_suppress
== 0) {
3495 r
= json_variant_new_string(&add
, n
);
3500 n_subtract
= 1; /* we generated one item */
3502 if (!b
&& current
->n_suppress
!= (size_t) -1)
3503 current
->n_suppress
+= 2; /* Suppress this one and the next item */
3505 current
->expect
= EXPECT_OBJECT_VALUE
;
3509 /* If a variant was generated, add it to our current variant, but only if we are not supposed to suppress additions */
3510 if (add
&& current
->n_suppress
== 0) {
3511 if (!GREEDY_REALLOC(current
->elements
, current
->n_elements_allocated
, current
->n_elements
+ 1)) {
3516 current
->elements
[current
->n_elements
++] = TAKE_PTR(add
);
3519 /* If we are supposed to suppress items, let's subtract how many items where generated from that
3520 * counter. Except if the counter is (size_t) -1, i.e. we shall suppress an infinite number of elements
3521 * on this stack level */
3522 if (current
->n_suppress
!= (size_t) -1) {
3523 if (current
->n_suppress
<= n_subtract
) /* Saturated */
3524 current
->n_suppress
= 0;
3526 current
->n_suppress
-= n_subtract
;
3531 assert(n_stack
== 1);
3532 assert(stack
[0].n_elements
== 1);
3534 *ret
= json_variant_ref(stack
[0].elements
[0]);
3538 for (i
= 0; i
< n_stack
; i
++)
3539 json_stack_release(stack
+ i
);
3546 int json_build(JsonVariant
**ret
, ...) {
3551 r
= json_buildv(ret
, ap
);
3557 int json_log_internal(
3558 JsonVariant
*variant
,
3564 const char *format
, ...) {
3568 unsigned source_line
, source_column
;
3569 char buffer
[LINE_MAX
];
3574 errno
= ERRNO_VALUE(error
);
3576 va_start(ap
, format
);
3577 (void) vsnprintf(buffer
, sizeof buffer
, format
, ap
);
3581 r
= json_variant_get_source(variant
, &source
, &source_line
, &source_column
);
3590 if (source
&& source_line
> 0 && source_column
> 0)
3591 return log_struct_internal(
3592 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3595 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3596 "CONFIG_FILE=%s", source
,
3597 "CONFIG_LINE=%u", source_line
,
3598 "CONFIG_COLUMN=%u", source_column
,
3599 LOG_MESSAGE("%s:%u:%u: %s", source
, source_line
, source_column
, buffer
),
3602 return log_struct_internal(
3603 LOG_REALM_PLUS_LEVEL(LOG_REALM_SYSTEMD
, level
),
3606 "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR
,
3607 LOG_MESSAGE("%s", buffer
),
3611 int json_dispatch(JsonVariant
*v
, const JsonDispatch table
[], JsonDispatchCallback bad
, JsonDispatchFlags flags
, void *userdata
) {
3612 const JsonDispatch
*p
;
3617 if (!json_variant_is_object(v
)) {
3618 json_log(v
, flags
, 0, "JSON variant is not an object.");
3620 if (flags
& JSON_PERMISSIVE
)
3626 for (p
= table
, m
= 0; p
->name
; p
++)
3629 found
= newa0(bool, m
);
3631 n
= json_variant_elements(v
);
3632 for (i
= 0; i
< n
; i
+= 2) {
3633 JsonVariant
*key
, *value
;
3635 assert_se(key
= json_variant_by_index(v
, i
));
3636 assert_se(value
= json_variant_by_index(v
, i
+1));
3638 for (p
= table
; p
->name
; p
++)
3639 if (p
->name
== (const char*) -1 ||
3640 streq_ptr(json_variant_string(key
), p
->name
))
3643 if (p
->name
) { /* Found a matching entry! :-) */
3644 JsonDispatchFlags merged_flags
;
3646 merged_flags
= flags
| p
->flags
;
3648 if (p
->type
!= _JSON_VARIANT_TYPE_INVALID
&&
3649 !json_variant_has_type(value
, p
->type
)) {
3651 json_log(value
, merged_flags
, 0,
3652 "Object field '%s' has wrong type %s, expected %s.", json_variant_string(key
),
3653 json_variant_type_to_string(json_variant_type(value
)), json_variant_type_to_string(p
->type
));
3655 if (merged_flags
& JSON_PERMISSIVE
)
3661 if (found
[p
-table
]) {
3662 json_log(value
, merged_flags
, 0, "Duplicate object field '%s'.", json_variant_string(key
));
3664 if (merged_flags
& JSON_PERMISSIVE
)
3670 found
[p
-table
] = true;
3673 r
= p
->callback(json_variant_string(key
), value
, merged_flags
, (uint8_t*) userdata
+ p
->offset
);
3675 if (merged_flags
& JSON_PERMISSIVE
)
3684 } else { /* Didn't find a matching entry! :-( */
3687 r
= bad(json_variant_string(key
), value
, flags
, userdata
);
3689 if (flags
& JSON_PERMISSIVE
)
3697 json_log(value
, flags
, 0, "Unexpected object field '%s'.", json_variant_string(key
));
3699 if (flags
& JSON_PERMISSIVE
)
3702 return -EADDRNOTAVAIL
;
3707 for (p
= table
; p
->name
; p
++) {
3708 JsonDispatchFlags merged_flags
= p
->flags
| flags
;
3710 if ((merged_flags
& JSON_MANDATORY
) && !found
[p
-table
]) {
3711 json_log(v
, merged_flags
, 0, "Missing object field '%s'.", p
->name
);
3713 if ((merged_flags
& JSON_PERMISSIVE
))
3723 int json_dispatch_boolean(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3729 if (!json_variant_is_boolean(variant
))
3730 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3732 *b
= json_variant_boolean(variant
);
3736 int json_dispatch_tristate(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3742 if (!json_variant_is_boolean(variant
))
3743 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a boolean.", strna(name
));
3745 *b
= json_variant_boolean(variant
);
3749 int json_dispatch_integer(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3750 intmax_t *i
= userdata
;
3755 if (!json_variant_is_integer(variant
))
3756 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3758 *i
= json_variant_integer(variant
);
3762 int json_dispatch_unsigned(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3763 uintmax_t *u
= userdata
;
3768 if (!json_variant_is_unsigned(variant
))
3769 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3771 *u
= json_variant_unsigned(variant
);
3775 int json_dispatch_uint32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3776 uint32_t *u
= userdata
;
3781 if (!json_variant_is_unsigned(variant
))
3782 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an unsigned integer.", strna(name
));
3784 if (json_variant_unsigned(variant
) > UINT32_MAX
)
3785 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3787 *u
= (uint32_t) json_variant_unsigned(variant
);
3791 int json_dispatch_int32(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3792 int32_t *i
= userdata
;
3797 if (!json_variant_is_integer(variant
))
3798 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not an integer.", strna(name
));
3800 if (json_variant_integer(variant
) < INT32_MIN
|| json_variant_integer(variant
) > INT32_MAX
)
3801 return json_log(variant
, flags
, SYNTHETIC_ERRNO(ERANGE
), "JSON field '%s' out of bounds.", strna(name
));
3803 *i
= (int32_t) json_variant_integer(variant
);
3807 int json_dispatch_string(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3808 char **s
= userdata
;
3814 if (json_variant_is_null(variant
)) {
3819 if (!json_variant_is_string(variant
))
3820 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' is not a string.", strna(name
));
3822 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(variant
)))
3823 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
3825 r
= free_and_strdup(s
, json_variant_string(variant
));
3827 return json_log(variant
, flags
, r
, "Failed to allocate string: %m");
3832 int json_dispatch_strv(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3833 _cleanup_strv_free_
char **l
= NULL
;
3834 char ***s
= userdata
;
3841 if (json_variant_is_null(variant
)) {
3846 /* Let's be flexible here: accept a single string in place of a single-item array */
3847 if (json_variant_is_string(variant
)) {
3848 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(variant
)))
3849 return json_log(variant
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
3851 l
= strv_new(json_variant_string(variant
));
3855 strv_free_and_replace(*s
, l
);
3859 if (!json_variant_is_array(variant
))
3860 return json_log(variant
, SYNTHETIC_ERRNO(EINVAL
), flags
, "JSON field '%s' is not an array.", strna(name
));
3862 JSON_VARIANT_ARRAY_FOREACH(e
, variant
) {
3863 if (!json_variant_is_string(e
))
3864 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON array element is not a string.");
3866 if ((flags
& JSON_SAFE
) && !string_is_safe(json_variant_string(e
)))
3867 return json_log(e
, flags
, SYNTHETIC_ERRNO(EINVAL
), "JSON field '%s' contains unsafe characters, refusing.", strna(name
));
3869 r
= strv_extend(&l
, json_variant_string(e
));
3871 return json_log(e
, flags
, r
, "Failed to append array element: %m");
3874 strv_free_and_replace(*s
, l
);
3878 int json_dispatch_variant(const char *name
, JsonVariant
*variant
, JsonDispatchFlags flags
, void *userdata
) {
3879 JsonVariant
**p
= userdata
;
3884 json_variant_unref(*p
);
3885 *p
= json_variant_ref(variant
);
3890 static int json_cmp_strings(const void *x
, const void *y
) {
3891 JsonVariant
*const *a
= x
, *const *b
= y
;
3893 if (!json_variant_is_string(*a
) || !json_variant_is_string(*b
))
3896 return strcmp(json_variant_string(*a
), json_variant_string(*b
));
3899 int json_variant_sort(JsonVariant
**v
) {
3900 _cleanup_free_ JsonVariant
**a
= NULL
;
3901 JsonVariant
*n
= NULL
;
3907 if (json_variant_is_sorted(*v
))
3910 if (!json_variant_is_object(*v
))
3911 return -EMEDIUMTYPE
;
3913 /* Sorts they key/value pairs in an object variant */
3915 m
= json_variant_elements(*v
);
3916 a
= new(JsonVariant
*, m
);
3920 for (i
= 0; i
< m
; i
++)
3921 a
[i
] = json_variant_by_index(*v
, i
);
3923 qsort(a
, m
/2, sizeof(JsonVariant
*)*2, json_cmp_strings
);
3925 r
= json_variant_new_object(&n
, a
, m
);
3928 if (!n
->sorted
) /* Check if this worked. This will fail if there are multiple identical keys used. */
3931 json_variant_unref(*v
);
3937 int json_variant_normalize(JsonVariant
**v
) {
3938 _cleanup_free_ JsonVariant
**a
= NULL
;
3939 JsonVariant
*n
= NULL
;
3945 if (json_variant_is_normalized(*v
))
3948 if (!json_variant_is_object(*v
) && !json_variant_is_array(*v
))
3949 return -EMEDIUMTYPE
;
3951 /* Sorts the key/value pairs in an object variant anywhere down the tree in the specified variant */
3953 m
= json_variant_elements(*v
);
3954 a
= new(JsonVariant
*, m
);
3958 for (i
= 0; i
< m
; i
++) {
3959 a
[i
] = json_variant_ref(json_variant_by_index(*v
, i
));
3961 r
= json_variant_normalize(a
+ i
);
3966 qsort(a
, m
/2, sizeof(JsonVariant
*)*2, json_cmp_strings
);
3968 if (json_variant_is_object(*v
))
3969 r
= json_variant_new_object(&n
, a
, m
);
3971 assert(json_variant_is_array(*v
));
3972 r
= json_variant_new_array(&n
, a
, m
);
3976 if (!n
->normalized
) { /* Let's see if normalization worked. It will fail if there are multiple
3977 * identical keys used in the same object anywhere, or if there are floating
3978 * point numbers used (see below) */
3983 json_variant_unref(*v
);
3989 for (j
= 0; j
< i
; j
++)
3990 json_variant_unref(a
[j
]);
3995 bool json_variant_is_normalized(JsonVariant
*v
) {
3997 /* For now, let's consider anything containing numbers not expressible as integers as
3998 * non-normalized. That's because we cannot sensibly compare them due to accuracy issues, nor even
3999 * store them if they are too large. */
4000 if (json_variant_is_real(v
) && !json_variant_is_integer(v
) && !json_variant_is_unsigned(v
))
4003 /* The concept only applies to variants that include other variants, i.e. objects and arrays. All
4004 * others are normalized anyway. */
4005 if (!json_variant_is_object(v
) && !json_variant_is_array(v
))
4008 /* Empty objects/arrays don't include any other variant, hence are always normalized too */
4009 if (json_variant_elements(v
) == 0)
4012 return v
->normalized
; /* For everything else there's an explicit boolean we maintain */
4015 bool json_variant_is_sorted(JsonVariant
*v
) {
4017 /* Returns true if all key/value pairs of an object are properly sorted. Note that this only applies
4018 * to objects, not arrays. */
4020 if (!json_variant_is_object(v
))
4022 if (json_variant_elements(v
) <= 1)
4028 static const char* const json_variant_type_table
[_JSON_VARIANT_TYPE_MAX
] = {
4029 [JSON_VARIANT_STRING
] = "string",
4030 [JSON_VARIANT_INTEGER
] = "integer",
4031 [JSON_VARIANT_UNSIGNED
] = "unsigned",
4032 [JSON_VARIANT_REAL
] = "real",
4033 [JSON_VARIANT_NUMBER
] = "number",
4034 [JSON_VARIANT_BOOLEAN
] = "boolean",
4035 [JSON_VARIANT_ARRAY
] = "array",
4036 [JSON_VARIANT_OBJECT
] = "object",
4037 [JSON_VARIANT_NULL
] = "null",
4040 DEFINE_STRING_TABLE_LOOKUP(json_variant_type
, JsonVariantType
);