Debian Codegraph @

src/libsystemd/sd-json/sd-json.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <locale.h>
4 #include <stdlib.h>
5
6 #include "sd-json.h"
7 #include "sd-messages.h"
8
9 #include "alloc-util.h"
10 #include "ansi-color.h"
11 #include "env-util.h"
12 #include "errno-util.h"
13 #include "escape.h"
14 #include "ether-addr-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "float.h"
18 #include "hexdecoct.h"
19 #include "in-addr-util.h"
20 #include "json-internal.h"
21 #include "json-util.h"
22 #include "log.h"
23 #include "math-util.h"
24 #include "memory-util.h"
25 #include "memstream-util.h"
26 #include "ordered-set.h"
27 #include "parse-util.h"
28 #include "pidref.h"
29 #include "ratelimit.h"
30 #include "signal-util.h"
31 #include "string-table.h"
32 #include "string-util.h"
33 #include "strv.h"
34 #include "terminal-util.h"
35 #include "time-util.h"
36 #include "user-util.h"
37 #include "utf8.h"
38
39 /* Refuse putting together variants with a larger depth than 2K by default (as a protection against overflowing stacks
40 * if code processes JSON objects recursively. Note that we store the depth in an uint16_t, hence make sure this
41 * remains under 2^16.
42 *
43 * The value first was 16k, but it was discovered to be too high on llvm/x86-64. See also:
44 * https://github.com/systemd/systemd/issues/10738
45 *
46 * The value then was 4k, but it was discovered to be too high on s390x/aarch64. See also:
47 * https://github.com/systemd/systemd/issues/14396 */
48
49 #define DEPTH_MAX (2U*1024U)
50 assert_cc(DEPTH_MAX <= UINT16_MAX);
51
52 typedef struct JsonSource {
53 /* When we parse from a file or similar, encodes the filename, to indicate the source of a json variant */
54 unsigned n_ref;
55 unsigned max_line;
56 unsigned max_column;
57 char name[];
58 } JsonSource;
59
60 /* On x86-64 this whole structure should have a size of 5 * 64 bit = 40 bytes */
61 struct sd_json_variant {
62 union {
63 /* We either maintain a reference counter for this variant itself, or we are embedded into an
64 * array/object, in which case only that surrounding object is ref-counted. (If 'embedded' is false,
65 * see below.) */
66 unsigned n_ref;
67
68 /* If this sd_json_variant is part of an array/object, then this field points to the surrounding
69 * JSON_VARIANT_ARRAY/JSON_VARIANT_OBJECT object. (If 'embedded' is true, see below.) */
70 sd_json_variant *parent;
71 };
72
73 /* If this was parsed from some file or buffer, this stores where from, as well as the source line/column */
74 JsonSource *source;
75 unsigned line, column;
76
77 /* The current 'depth' of the sd_json_variant, i.e. how many levels of member variants this has */
78 uint16_t depth;
79
80 signed int type:8; /* actually sd_json_variant_type_t, but reduced to 8bit size (we used "signed int"
81 * rather than just "int", since apparently compilers are free to pick signedness
82 * otherwise. We don't really care about the signedess, we care more about whether
83 * the enum can be converted to this, but we never use the negative values of
84 * sd_json_variant_type_t here.) */
85
86 /* A marker whether this variant is embedded into in array/object or not. If true, the 'parent' pointer above
87 * is valid. If false, the 'n_ref' field above is valid instead. */
88 bool is_embedded:1;
89
90 /* In some conditions (for example, if this object is part of an array of strings or objects), we don't store
91 * any data inline, but instead simply reference an external object and act as surrogate of it. In that case
92 * this bool is set, and the external object is referenced through the .reference field below. */
93 bool is_reference:1;
94
95 /* While comparing two arrays, we use this for marking what we already have seen */
96 bool is_marked:1;
97
98 /* Erase from memory when freeing */
99 bool sensitive:1;
100
101 /* True if we know that any referenced json object is marked sensitive */
102 bool recursive_sensitive:1;
103
104 /* If this is an object the fields are strictly ordered by name */
105 bool sorted:1;
106
107 /* If in addition to this object all objects referenced by it are also ordered strictly by name */
108 bool normalized:1;
109
110 union {
111 /* For simple types we store the value in-line. */
112 JsonValue value;
113
114 /* For objects and arrays we store the number of elements immediately following */
115 size_t n_elements;
116
117 /* If is_reference as indicated above is set, this is where the reference object is actually stored. */
118 sd_json_variant *reference;
119
120 /* Strings are placed immediately after the structure. Note that when this is a sd_json_variant
121 * embedded into an array we might encode strings up to INLINE_STRING_LENGTH characters
122 * directly inside the element, while longer strings are stored as references. When this
123 * object is not embedded into an array, but stand-alone, we allocate the right size for the
124 * whole structure, i.e. the array might be much larger than INLINE_STRING_LENGTH. */
125 DECLARE_FLEX_ARRAY(char, string);
126 };
127 };
128
129 /* Inside string arrays we have a series of sd_json_variant structures one after the other. In this case, strings longer
130 * than INLINE_STRING_MAX are stored as references, and all shorter ones inline. (This means — on x86-64 — strings up
131 * to 7 chars are stored within the array elements, and all others in separate allocations) */
132 #define INLINE_STRING_MAX (sizeof(sd_json_variant) - offsetof(sd_json_variant, string) - 1U)
133
134 /* Let's make sure this structure isn't increased in size accidentally. This check is only for our most relevant arch
135 * (x86-64). */
136 #if defined(__x86_64__) && __SIZEOF_POINTER__ == 8 && !defined(__EDG__)
137 assert_cc(sizeof(sd_json_variant) == 40U);
138 assert_cc(INLINE_STRING_MAX == 7U);
139 #endif
140
141 static JsonSource* json_source_new(const char *name) {
142 JsonSource *s;
143
144 assert(name);
145
146 s = malloc(offsetof(JsonSource, name) + strlen(name) + 1);
147 if (!s)
148 return NULL;
149
150 *s = (JsonSource) {
151 .n_ref = 1,
152 };
153 strcpy(s->name, name);
154
155 return s;
156 }
157
158 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(JsonSource, json_source, mfree);
159
160 static bool json_source_equal(JsonSource *a, JsonSource *b) {
161 if (a == b)
162 return true;
163
164 if (!a || !b)
165 return false;
166
167 return streq(a->name, b->name);
168 }
169
170 DEFINE_TRIVIAL_CLEANUP_FUNC(JsonSource*, json_source_unref);
171
172 /* There are four kind of sd_json_variant* pointers:
173 *
174 * 1. NULL
175 * 2. A 'regular' one, i.e. pointing to malloc() memory
176 * 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.
177 * 4. A 'const string' one, i.e. a pointer to a const string.
178 *
179 * The four kinds of pointers can be discerned like this:
180 *
181 * Detecting #1 is easy, just compare with NULL. Detecting #3 is similarly easy: all magic pointers are below
182 * _JSON_VARIANT_MAGIC_MAX (which is pretty low, within the first memory page, which is special on Linux and other
183 * 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,
184 * otherwise #4. This makes use of the fact that malloc() will return "maximum aligned" memory, which definitely
185 * means the pointer is even. This means we can use the uneven pointers to reference static strings, as long as we
186 * make sure that all static strings used like this are aligned to 2 (or higher), and that we mask the bit on
187 * access. The JSON_VARIANT_STRING_CONST() macro encodes strings as sd_json_variant* pointers, with the bit set. */
188
189 static bool json_variant_is_magic(const sd_json_variant *v) {
190 if (!v)
191 return false;
192
193 return v < _JSON_VARIANT_MAGIC_MAX;
194 }
195
196 static bool json_variant_is_const_string(const sd_json_variant *v) {
197
198 if (v < _JSON_VARIANT_MAGIC_MAX)
199 return false;
200
201 /* A proper sd_json_variant is aligned to whatever malloc() aligns things too, which is definitely not uneven. We
202 * hence use all uneven pointers as indicators for const strings. */
203
204 return (((uintptr_t) v) & 1) != 0;
205 }
206
207 static bool json_variant_is_regular(const sd_json_variant *v) {
208
209 if (v < _JSON_VARIANT_MAGIC_MAX)
210 return false;
211
212 return (((uintptr_t) v) & 1) == 0;
213 }
214
215 static sd_json_variant* json_variant_dereference(sd_json_variant *v) {
216
217 /* Recursively dereference variants that are references to other variants */
218
219 if (!v)
220 return NULL;
221
222 if (!json_variant_is_regular(v))
223 return v;
224
225 if (!v->is_reference)
226 return v;
227
228 return json_variant_dereference(v->reference);
229 }
230
231 static uint16_t json_variant_depth(sd_json_variant *v) {
232
233 v = json_variant_dereference(v);
234 if (!v)
235 return 0;
236
237 if (!json_variant_is_regular(v))
238 return 0;
239
240 return v->depth;
241 }
242
243 static sd_json_variant* json_variant_formalize(sd_json_variant *v) {
244
245 /* Converts json variant pointers to their normalized form, i.e. fully dereferenced and wherever
246 * possible converted to the "magic" version if there is one */
247
248 if (!v)
249 return NULL;
250
251 v = json_variant_dereference(v);
252
253 switch (sd_json_variant_type(v)) {
254
255 case SD_JSON_VARIANT_BOOLEAN:
256 return sd_json_variant_boolean(v) ? JSON_VARIANT_MAGIC_TRUE : JSON_VARIANT_MAGIC_FALSE;
257
258 case SD_JSON_VARIANT_NULL:
259 return JSON_VARIANT_MAGIC_NULL;
260
261 case SD_JSON_VARIANT_INTEGER:
262 return sd_json_variant_integer(v) == 0 ? JSON_VARIANT_MAGIC_ZERO_INTEGER : v;
263
264 case SD_JSON_VARIANT_UNSIGNED:
265 return sd_json_variant_unsigned(v) == 0 ? JSON_VARIANT_MAGIC_ZERO_UNSIGNED : v;
266
267 case SD_JSON_VARIANT_REAL:
268 return iszero_safe(sd_json_variant_real(v)) ? JSON_VARIANT_MAGIC_ZERO_REAL : v;
269
270 case SD_JSON_VARIANT_STRING:
271 return isempty(sd_json_variant_string(v)) ? JSON_VARIANT_MAGIC_EMPTY_STRING : v;
272
273 case SD_JSON_VARIANT_ARRAY:
274 return sd_json_variant_elements(v) == 0 ? JSON_VARIANT_MAGIC_EMPTY_ARRAY : v;
275
276 case SD_JSON_VARIANT_OBJECT:
277 return sd_json_variant_elements(v) == 0 ? JSON_VARIANT_MAGIC_EMPTY_OBJECT : v;
278
279 default:
280 return v;
281 }
282 }
283
284 static sd_json_variant* json_variant_conservative_formalize(sd_json_variant *v) {
285
286 /* Much like json_variant_formalize(), but won't simplify if the variant has a source/line location
287 * attached to it, in order not to lose context */
288
289 if (!v)
290 return NULL;
291
292 if (!json_variant_is_regular(v))
293 return v;
294
295 if (v->source || v->line > 0 || v->column > 0)
296 return v;
297
298 return json_variant_formalize(v);
299 }
300
301 static int json_variant_new(sd_json_variant **ret, sd_json_variant_type_t type, size_t space) {
302 sd_json_variant *v;
303
304 assert_return(ret, -EINVAL);
305
306 v = malloc0(MAX(sizeof(sd_json_variant),
307 offsetof(sd_json_variant, value) + space));
308 if (!v)
309 return -ENOMEM;
310
311 v->n_ref = 1;
312 v->type = type;
313
314 *ret = v;
315 return 0;
316 }
317
318 _public_ int sd_json_variant_new_integer(sd_json_variant **ret, int64_t i) {
319 sd_json_variant *v;
320 int r;
321
322 assert_return(ret, -EINVAL);
323
324 if (i == 0) {
325 *ret = JSON_VARIANT_MAGIC_ZERO_INTEGER;
326 return 0;
327 }
328
329 r = json_variant_new(&v, SD_JSON_VARIANT_INTEGER, sizeof(i));
330 if (r < 0)
331 return r;
332
333 v->value.integer = i;
334 *ret = v;
335
336 return 0;
337 }
338
339 _public_ int sd_json_variant_new_unsigned(sd_json_variant **ret, uint64_t u) {
340 sd_json_variant *v;
341 int r;
342
343 assert_return(ret, -EINVAL);
344 if (u == 0) {
345 *ret = JSON_VARIANT_MAGIC_ZERO_UNSIGNED;
346 return 0;
347 }
348
349 r = json_variant_new(&v, SD_JSON_VARIANT_UNSIGNED, sizeof(u));
350 if (r < 0)
351 return r;
352
353 v->value.unsig = u;
354 *ret = v;
355
356 return 0;
357 }
358
359 _public_ int sd_json_variant_new_real(sd_json_variant **ret, double d) {
360 sd_json_variant *v;
361 int r;
362
363 assert_return(ret, -EINVAL);
364
365 r = fpclassify(d);
366 switch (r) {
367 case FP_NAN:
368 case FP_INFINITE:
369 /* JSON doesn't know NaN, +Infinity or -Infinity. Let's silently convert to 'null'. */
370 *ret = JSON_VARIANT_MAGIC_NULL;
371 return 0;
372
373 case FP_ZERO:
374 *ret = JSON_VARIANT_MAGIC_ZERO_REAL;
375 return 0;
376 }
377
378 r = json_variant_new(&v, SD_JSON_VARIANT_REAL, sizeof(d));
379 if (r < 0)
380 return r;
381
382 v->value.real = d;
383 *ret = v;
384
385 return 0;
386 }
387
388 _public_ int sd_json_variant_new_boolean(sd_json_variant **ret, int b) {
389 assert_return(ret, -EINVAL);
390
391 if (b)
392 *ret = JSON_VARIANT_MAGIC_TRUE;
393 else
394 *ret = JSON_VARIANT_MAGIC_FALSE;
395
396 return 0;
397 }
398
399 _public_ int sd_json_variant_new_null(sd_json_variant **ret) {
400 assert_return(ret, -EINVAL);
401
402 *ret = JSON_VARIANT_MAGIC_NULL;
403 return 0;
404 }
405
406 _public_ int sd_json_variant_new_stringn(sd_json_variant **ret, const char *s, size_t n) {
407 sd_json_variant *v;
408 int r;
409
410 assert_return(ret, -EINVAL);
411 if (!s) {
412 assert_return(IN_SET(n, 0, SIZE_MAX), -EINVAL);
413 return sd_json_variant_new_null(ret);
414 }
415 if (n == SIZE_MAX) /* determine length automatically */
416 n = strlen(s);
417 else if (memchr(s, 0, n)) /* don't allow embedded NUL, as we can't express that in JSON */
418 return -EINVAL;
419 if (n == 0) {
420 *ret = JSON_VARIANT_MAGIC_EMPTY_STRING;
421 return 0;
422 }
423
424 if (!utf8_is_valid_n(s, n)) /* JSON strings must be valid UTF-8 */
425 return -EUCLEAN;
426
427 r = json_variant_new(&v, SD_JSON_VARIANT_STRING, n + 1);
428 if (r < 0)
429 return r;
430
431 memcpy(v->string, s, n);
432 v->string[n] = 0;
433
434 *ret = v;
435 return 0;
436 }
437
438 _public_ int sd_json_variant_new_string(sd_json_variant **ret, const char *s) {
439 return sd_json_variant_new_stringn(ret, s, SIZE_MAX);
440 }
441
442 _public_ int sd_json_variant_new_base64(sd_json_variant **ret, const void *p, size_t n) {
443 _cleanup_free_ char *s = NULL;
444 ssize_t k;
445
446 assert_return(ret, -EINVAL);
447 assert_return(n == 0 || p, -EINVAL);
448
449 k = base64mem(p, n, &s);
450 if (k < 0)
451 return k;
452
453 return sd_json_variant_new_stringn(ret, s, k);
454 }
455
456 _public_ int sd_json_variant_new_base32hex(sd_json_variant **ret, const void *p, size_t n) {
457 _cleanup_free_ char *s = NULL;
458
459 assert_return(ret, -EINVAL);
460 assert_return(n == 0 || p, -EINVAL);
461
462 s = base32hexmem(p, n, false);
463 if (!s)
464 return -ENOMEM;
465
466 return sd_json_variant_new_string(ret, s);
467 }
468
469 _public_ int sd_json_variant_new_hex(sd_json_variant **ret, const void *p, size_t n) {
470 _cleanup_free_ char *s = NULL;
471
472 assert_return(ret, -EINVAL);
473 assert_return(n == 0 || p, -EINVAL);
474
475 s = hexmem(p, n);
476 if (!s)
477 return -ENOMEM;
478
479 return sd_json_variant_new_stringn(ret, s, n*2);
480 }
481
482 _public_ int sd_json_variant_new_octescape(sd_json_variant **ret, const void *p, size_t n) {
483 _cleanup_free_ char *s = NULL;
484
485 assert_return(ret, -EINVAL);
486 assert_return(n == 0 || p, -EINVAL);
487
488 s = octescape(p, n);
489 if (!s)
490 return -ENOMEM;
491
492 return sd_json_variant_new_string(ret, s);
493 }
494
495 _public_ int sd_json_variant_new_id128(sd_json_variant **ret, sd_id128_t id) {
496 return sd_json_variant_new_string(ret, SD_ID128_TO_STRING(id));
497 }
498
499 _public_ int sd_json_variant_new_uuid(sd_json_variant **ret, sd_id128_t id) {
500 return sd_json_variant_new_string(ret, SD_ID128_TO_UUID_STRING(id));
501 }
502
503 static void json_variant_set(sd_json_variant *a, sd_json_variant *b) {
504 assert(a);
505
506 b = json_variant_dereference(b);
507 if (!b) {
508 a->type = SD_JSON_VARIANT_NULL;
509 return;
510 }
511
512 a->type = sd_json_variant_type(b);
513 switch (a->type) {
514
515 case SD_JSON_VARIANT_INTEGER:
516 a->value.integer = sd_json_variant_integer(b);
517 break;
518
519 case SD_JSON_VARIANT_UNSIGNED:
520 a->value.unsig = sd_json_variant_unsigned(b);
521 break;
522
523 case SD_JSON_VARIANT_REAL:
524 a->value.real = sd_json_variant_real(b);
525 break;
526
527 case SD_JSON_VARIANT_BOOLEAN:
528 a->value.boolean = sd_json_variant_boolean(b);
529 break;
530
531 case SD_JSON_VARIANT_STRING: {
532 const char *s;
533
534 assert_se(s = sd_json_variant_string(b));
535
536 /* Short strings we can store inline */
537 if (strnlen(s, INLINE_STRING_MAX+1) <= INLINE_STRING_MAX) {
538 strcpy(a->string, s);
539 break;
540 }
541
542 /* For longer strings, use a reference… */
543 _fallthrough_;
544 }
545
546 case SD_JSON_VARIANT_ARRAY:
547 case SD_JSON_VARIANT_OBJECT:
548 a->is_reference = true;
549 a->reference = sd_json_variant_ref(json_variant_conservative_formalize(b));
550 break;
551
552 case SD_JSON_VARIANT_NULL:
553 break;
554
555 default:
556 assert_not_reached();
557 }
558 }
559
560 static void json_variant_copy_source(sd_json_variant *v, sd_json_variant *from) {
561 assert(v);
562
563 if (!json_variant_is_regular(from))
564 return;
565
566 v->line = from->line;
567 v->column = from->column;
568 v->source = json_source_ref(from->source);
569 }
570
571 static int json_variant_array_put_element(sd_json_variant *array, sd_json_variant *element) {
572 assert(array);
573 sd_json_variant *w = array + 1 + array->n_elements;
574
575 uint16_t d = json_variant_depth(element);
576 if (d >= DEPTH_MAX) /* Refuse too deep nesting */
577 return -ELNRNG;
578 if (d >= array->depth)
579 array->depth = d + 1;
580 array->n_elements++;
581
582 *w = (sd_json_variant) {
583 .is_embedded = true,
584 .parent = array,
585 };
586
587 json_variant_set(w, element);
588 json_variant_copy_source(w, element);
589
590 if (!sd_json_variant_is_normalized(element))
591 array->normalized = false;
592
593 return 0;
594 }
595
596 _public_ int sd_json_variant_new_array(sd_json_variant **ret, sd_json_variant **array, size_t n) {
597 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
598 int r;
599
600 assert_return(ret, -EINVAL);
601 if (n == 0) {
602 *ret = JSON_VARIANT_MAGIC_EMPTY_ARRAY;
603 return 0;
604 }
605 assert_return(array, -EINVAL);
606
607 v = new(sd_json_variant, n + 1);
608 if (!v)
609 return -ENOMEM;
610
611 *v = (sd_json_variant) {
612 .n_ref = 1,
613 .type = SD_JSON_VARIANT_ARRAY,
614 .normalized = true,
615 };
616
617 while (v->n_elements < n) {
618 r = json_variant_array_put_element(v, array[v->n_elements]);
619 if (r < 0)
620 return r;
621 }
622
623 *ret = TAKE_PTR(v);
624 return 0;
625 }
626
627 _public_ int sd_json_variant_new_array_bytes(sd_json_variant **ret, const void *p, size_t n) {
628 assert_return(ret, -EINVAL);
629 if (n == 0) {
630 *ret = JSON_VARIANT_MAGIC_EMPTY_ARRAY;
631 return 0;
632 }
633 assert_return(p, -EINVAL);
634
635 sd_json_variant *v = new(sd_json_variant, n + 1);
636 if (!v)
637 return -ENOMEM;
638
639 *v = (sd_json_variant) {
640 .n_ref = 1,
641 .type = SD_JSON_VARIANT_ARRAY,
642 .n_elements = n,
643 .depth = 1,
644 };
645
646 for (size_t i = 0; i < n; i++) {
647 sd_json_variant *w = v + 1 + i;
648
649 *w = (sd_json_variant) {
650 .is_embedded = true,
651 .parent = v,
652 .type = SD_JSON_VARIANT_UNSIGNED,
653 .value.unsig = ((const uint8_t*) p)[i],
654 };
655 }
656
657 v->normalized = true;
658
659 *ret = v;
660 return 0;
661 }
662
663 _public_ int sd_json_variant_new_array_strv(sd_json_variant **ret, char **l) {
664 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
665 size_t n;
666 int r;
667
668 assert_return(ret, -EINVAL);
669
670 n = strv_length(l);
671 if (n == 0) {
672 *ret = JSON_VARIANT_MAGIC_EMPTY_ARRAY;
673 return 0;
674 }
675
676 v = new(sd_json_variant, n + 1);
677 if (!v)
678 return -ENOMEM;
679
680 *v = (sd_json_variant) {
681 .n_ref = 1,
682 .type = SD_JSON_VARIANT_ARRAY,
683 .depth = 1,
684 };
685
686 for (v->n_elements = 0; v->n_elements < n; v->n_elements++) {
687 sd_json_variant *w = v + 1 + v->n_elements;
688 size_t k;
689
690 *w = (sd_json_variant) {
691 .is_embedded = true,
692 .parent = v,
693 .type = SD_JSON_VARIANT_STRING,
694 };
695
696 k = strlen(l[v->n_elements]);
697
698 if (k > INLINE_STRING_MAX) {
699 /* If string is too long, store it as reference. */
700
701 r = sd_json_variant_new_string(&w->reference, l[v->n_elements]);
702 if (r < 0)
703 return r;
704
705 w->is_reference = true;
706 } else {
707 if (!utf8_is_valid_n(l[v->n_elements], k)) /* JSON strings must be valid UTF-8 */
708 return -EUCLEAN;
709
710 memcpy(w->string, l[v->n_elements], k+1);
711 }
712 }
713
714 v->normalized = true;
715
716 *ret = TAKE_PTR(v);
717 return 0;
718 }
719
720 _public_ int sd_json_variant_new_object(sd_json_variant **ret, sd_json_variant **array, size_t n) {
721 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
722 const char *prev = NULL;
723 bool sorted = true, normalized = true;
724
725 assert_return(ret, -EINVAL);
726 if (n == 0) {
727 *ret = JSON_VARIANT_MAGIC_EMPTY_OBJECT;
728 return 0;
729 }
730 assert_return(array, -EINVAL);
731 assert_return(n % 2 == 0, -EINVAL);
732
733 v = new(sd_json_variant, n + 1);
734 if (!v)
735 return -ENOMEM;
736
737 *v = (sd_json_variant) {
738 .n_ref = 1,
739 .type = SD_JSON_VARIANT_OBJECT,
740 };
741
742 for (v->n_elements = 0; v->n_elements < n; v->n_elements++) {
743 sd_json_variant *w = v + 1 + v->n_elements,
744 *c = array[v->n_elements];
745 uint16_t d;
746
747 if ((v->n_elements & 1) == 0) {
748 const char *k;
749
750 if (!sd_json_variant_is_string(c))
751 return -EINVAL; /* Every second one needs to be a string, as it is the key name */
752
753 assert_se(k = sd_json_variant_string(c));
754
755 if (prev && strcmp(k, prev) <= 0)
756 sorted = normalized = false;
757
758 prev = k;
759 } else if (!sd_json_variant_is_normalized(c))
760 normalized = false;
761
762 d = json_variant_depth(c);
763 if (d >= DEPTH_MAX) /* Refuse too deep nesting */
764 return -ELNRNG;
765 if (d >= v->depth)
766 v->depth = d + 1;
767
768 *w = (sd_json_variant) {
769 .is_embedded = true,
770 .parent = v,
771 };
772
773 json_variant_set(w, c);
774 json_variant_copy_source(w, c);
775 }
776
777 v->normalized = normalized;
778 v->sorted = sorted;
779
780 *ret = TAKE_PTR(v);
781 return 0;
782 }
783
784 static size_t json_variant_size(sd_json_variant* v) {
785 if (!json_variant_is_regular(v))
786 return 0;
787
788 if (v->is_reference)
789 return offsetof(sd_json_variant, reference) + sizeof(sd_json_variant*);
790
791 switch (v->type) {
792
793 case SD_JSON_VARIANT_STRING:
794 return offsetof(sd_json_variant, string) + strlen(v->string) + 1;
795
796 case SD_JSON_VARIANT_REAL:
797 return offsetof(sd_json_variant, value) + sizeof(double);
798
799 case SD_JSON_VARIANT_UNSIGNED:
800 return offsetof(sd_json_variant, value) + sizeof(uint64_t);
801
802 case SD_JSON_VARIANT_INTEGER:
803 return offsetof(sd_json_variant, value) + sizeof(int64_t);
804
805 case SD_JSON_VARIANT_BOOLEAN:
806 return offsetof(sd_json_variant, value) + sizeof(bool);
807
808 case SD_JSON_VARIANT_ARRAY:
809 case SD_JSON_VARIANT_OBJECT:
810 return offsetof(sd_json_variant, n_elements) + sizeof(size_t);
811
812 case SD_JSON_VARIANT_NULL:
813 return offsetof(sd_json_variant, value);
814
815 default:
816 assert_not_reached();
817 }
818 }
819
820 static void json_variant_free_inner(sd_json_variant *v, bool force_sensitive) {
821 bool sensitive;
822
823 assert(v);
824
825 if (!json_variant_is_regular(v))
826 return;
827
828 json_source_unref(v->source);
829
830 sensitive = v->sensitive || force_sensitive;
831
832 if (v->is_reference) {
833 if (sensitive)
834 sd_json_variant_sensitive(v->reference);
835
836 sd_json_variant_unref(v->reference);
837 return;
838 }
839
840 if (IN_SET(v->type, SD_JSON_VARIANT_ARRAY, SD_JSON_VARIANT_OBJECT))
841 for (size_t i = 0; i < v->n_elements; i++)
842 json_variant_free_inner(v + 1 + i, sensitive);
843
844 if (sensitive)
845 explicit_bzero_safe(v, json_variant_size(v));
846 }
847
848 static unsigned json_variant_n_ref(const sd_json_variant *v) {
849 /* Return the number of references to v.
850 * 0 => NULL or not a regular object or embedded.
851 * >0 => number of references
852 */
853
854 if (!v || !json_variant_is_regular(v) || v->is_embedded)
855 return 0;
856
857 assert(v->n_ref > 0);
858 return v->n_ref;
859 }
860
861 _public_ sd_json_variant *sd_json_variant_ref(sd_json_variant *v) {
862 if (!v)
863 return NULL;
864 if (!json_variant_is_regular(v))
865 return v;
866
867 if (v->is_embedded)
868 sd_json_variant_ref(v->parent); /* ref the compounding variant instead */
869 else {
870 assert(v->n_ref > 0);
871 v->n_ref++;
872 }
873
874 return v;
875 }
876
877 _public_ sd_json_variant *sd_json_variant_unref(sd_json_variant *v) {
878 if (!v)
879 return NULL;
880 if (!json_variant_is_regular(v))
881 return NULL;
882
883 if (v->is_embedded)
884 sd_json_variant_unref(v->parent);
885 else {
886 assert(v->n_ref > 0);
887 v->n_ref--;
888
889 if (v->n_ref == 0) {
890 json_variant_free_inner(v, false);
891 free(v);
892 }
893 }
894
895 return NULL;
896 }
897
898 _public_ void sd_json_variant_unref_many(sd_json_variant **array, size_t n) {
899 FOREACH_ARRAY(v, array, n)
900 sd_json_variant_unref(*v);
901
902 free(array);
903 }
904
905 _public_ const char* sd_json_variant_string(sd_json_variant *v) {
906 if (!v)
907 return NULL;
908 if (v == JSON_VARIANT_MAGIC_EMPTY_STRING)
909 return "";
910 if (json_variant_is_magic(v))
911 goto mismatch;
912 if (json_variant_is_const_string(v)) {
913 uintptr_t p = (uintptr_t) v;
914
915 assert((p & 1) != 0);
916 return (const char*) (p ^ 1U);
917 }
918
919 if (v->is_reference)
920 return sd_json_variant_string(v->reference);
921 if (v->type != SD_JSON_VARIANT_STRING)
922 goto mismatch;
923
924 return v->string;
925
926 mismatch:
927 log_debug("Non-string JSON variant requested as string, returning NULL.");
928 return NULL;
929 }
930
931 _public_ int sd_json_variant_boolean(sd_json_variant *v) {
932 if (!v)
933 goto mismatch;
934 if (v == JSON_VARIANT_MAGIC_TRUE)
935 return true;
936 if (v == JSON_VARIANT_MAGIC_FALSE)
937 return false;
938 if (!json_variant_is_regular(v))
939 goto mismatch;
940 if (v->type != SD_JSON_VARIANT_BOOLEAN)
941 goto mismatch;
942 if (v->is_reference)
943 return sd_json_variant_boolean(v->reference);
944
945 return v->value.boolean;
946
947 mismatch:
948 log_debug("Non-boolean JSON variant requested as boolean, returning false.");
949 return false;
950 }
951
952 _public_ int64_t sd_json_variant_integer(sd_json_variant *v) {
953 if (!v)
954 goto mismatch;
955 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
956 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
957 v == JSON_VARIANT_MAGIC_ZERO_REAL)
958 return 0;
959 if (!json_variant_is_regular(v))
960 goto mismatch;
961 if (v->is_reference)
962 return sd_json_variant_integer(v->reference);
963
964 switch (v->type) {
965
966 case SD_JSON_VARIANT_INTEGER:
967 return v->value.integer;
968
969 case SD_JSON_VARIANT_UNSIGNED:
970 if (v->value.unsig <= INT64_MAX)
971 return (int64_t) v->value.unsig;
972
973 log_debug("Unsigned integer %" PRIu64 " requested as signed integer and out of range, returning 0.", v->value.unsig);
974 return 0;
975
976 case SD_JSON_VARIANT_REAL: {
977 int64_t converted;
978
979 converted = (int64_t) v->value.real;
980
981 if (fp_equal((double) converted, v->value.real))
982 return converted;
983
984 log_debug("Real %g requested as integer, and cannot be converted losslessly, returning 0.", v->value.real);
985 return 0;
986 }
987
988 default:
989 ;
990 }
991
992 mismatch:
993 log_debug("Non-integer JSON variant requested as integer, returning 0.");
994 return 0;
995 }
996
997 _public_ uint64_t sd_json_variant_unsigned(sd_json_variant *v) {
998 if (!v)
999 goto mismatch;
1000 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
1001 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
1002 v == JSON_VARIANT_MAGIC_ZERO_REAL)
1003 return 0;
1004 if (!json_variant_is_regular(v))
1005 goto mismatch;
1006 if (v->is_reference)
1007 return sd_json_variant_unsigned(v->reference);
1008
1009 switch (v->type) {
1010
1011 case SD_JSON_VARIANT_INTEGER:
1012 if (v->value.integer >= 0)
1013 return (uint64_t) v->value.integer;
1014
1015 log_debug("Signed integer %" PRIi64 " requested as unsigned integer and out of range, returning 0.", v->value.integer);
1016 return 0;
1017
1018 case SD_JSON_VARIANT_UNSIGNED:
1019 return v->value.unsig;
1020
1021 case SD_JSON_VARIANT_REAL: {
1022 uint64_t converted;
1023
1024 converted = (uint64_t) v->value.real;
1025
1026 if (fp_equal((double) converted, v->value.real))
1027 return converted;
1028
1029 log_debug("Real %g requested as unsigned integer, and cannot be converted losslessly, returning 0.", v->value.real);
1030 return 0;
1031 }
1032
1033 default:
1034 ;
1035 }
1036
1037 mismatch:
1038 log_debug("Non-integer JSON variant requested as unsigned, returning 0.");
1039 return 0;
1040 }
1041
1042 _public_ double sd_json_variant_real(sd_json_variant *v) {
1043 if (!v)
1044 return 0.0;
1045 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
1046 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
1047 v == JSON_VARIANT_MAGIC_ZERO_REAL)
1048 return 0.0;
1049 if (!json_variant_is_regular(v))
1050 goto mismatch;
1051 if (v->is_reference)
1052 return sd_json_variant_real(v->reference);
1053
1054 switch (v->type) {
1055
1056 case SD_JSON_VARIANT_REAL:
1057 return v->value.real;
1058
1059 case SD_JSON_VARIANT_INTEGER: {
1060 double converted = (double) v->value.integer;
1061
1062 if ((int64_t) converted == v->value.integer)
1063 return converted;
1064
1065 log_debug("Signed integer %" PRIi64 " requested as real, and cannot be converted losslessly, returning 0.", v->value.integer);
1066 return 0.0;
1067 }
1068
1069 case SD_JSON_VARIANT_UNSIGNED: {
1070 double converted = (double) v->value.unsig;
1071
1072 if ((uint64_t) converted == v->value.unsig)
1073 return converted;
1074
1075 log_debug("Unsigned integer %" PRIu64 " requested as real, and cannot be converted losslessly, returning 0.", v->value.unsig);
1076 return 0.0;
1077 }
1078
1079 default:
1080 ;
1081 }
1082
1083 mismatch:
1084 log_debug("Non-integer JSON variant requested as integer, returning 0.");
1085 return 0.0;
1086 }
1087
1088 _public_ int sd_json_variant_is_negative(sd_json_variant *v) {
1089 if (!v)
1090 goto mismatch;
1091 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER ||
1092 v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED ||
1093 v == JSON_VARIANT_MAGIC_ZERO_REAL)
1094 return false;
1095 if (!json_variant_is_regular(v))
1096 goto mismatch;
1097 if (v->is_reference)
1098 return sd_json_variant_is_negative(v->reference);
1099
1100 /* This function is useful as checking whether numbers are negative is pretty complex since we have three types
1101 * of numbers. And some JSON code (OCI for example) uses negative numbers to mark "not defined" numeric
1102 * values. */
1103
1104 switch (v->type) {
1105
1106 case SD_JSON_VARIANT_REAL:
1107 return v->value.real < 0;
1108
1109 case SD_JSON_VARIANT_INTEGER:
1110 return v->value.integer < 0;
1111
1112 case SD_JSON_VARIANT_UNSIGNED:
1113 return false;
1114
1115 default:
1116 ;
1117 }
1118
1119 mismatch:
1120 log_debug("Non-integer JSON variant tested for negativity, returning false.");
1121 return false;
1122 }
1123
1124 _public_ int sd_json_variant_is_blank_object(sd_json_variant *v) {
1125 /* Returns true if the specified object is null or empty */
1126 return !v ||
1127 sd_json_variant_is_null(v) ||
1128 (sd_json_variant_is_object(v) && sd_json_variant_elements(v) == 0);
1129 }
1130
1131 _public_ int sd_json_variant_is_blank_array(sd_json_variant *v) {
1132 return !v ||
1133 sd_json_variant_is_null(v) ||
1134 (sd_json_variant_is_array(v) && sd_json_variant_elements(v) == 0);
1135 }
1136
1137 _public_ sd_json_variant_type_t sd_json_variant_type(sd_json_variant *v) {
1138
1139 if (!v)
1140 return _SD_JSON_VARIANT_TYPE_INVALID;
1141
1142 if (json_variant_is_const_string(v))
1143 return SD_JSON_VARIANT_STRING;
1144
1145 if (v == JSON_VARIANT_MAGIC_TRUE || v == JSON_VARIANT_MAGIC_FALSE)
1146 return SD_JSON_VARIANT_BOOLEAN;
1147
1148 if (v == JSON_VARIANT_MAGIC_NULL)
1149 return SD_JSON_VARIANT_NULL;
1150
1151 if (v == JSON_VARIANT_MAGIC_ZERO_INTEGER)
1152 return SD_JSON_VARIANT_INTEGER;
1153
1154 if (v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED)
1155 return SD_JSON_VARIANT_UNSIGNED;
1156
1157 if (v == JSON_VARIANT_MAGIC_ZERO_REAL)
1158 return SD_JSON_VARIANT_REAL;
1159
1160 if (v == JSON_VARIANT_MAGIC_EMPTY_STRING)
1161 return SD_JSON_VARIANT_STRING;
1162
1163 if (v == JSON_VARIANT_MAGIC_EMPTY_ARRAY)
1164 return SD_JSON_VARIANT_ARRAY;
1165
1166 if (v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
1167 return SD_JSON_VARIANT_OBJECT;
1168
1169 return v->type;
1170 }
1171
1172 _function_no_sanitize_float_cast_overflow_
1173 _public_ int sd_json_variant_has_type(sd_json_variant *v, sd_json_variant_type_t type) {
1174 sd_json_variant_type_t rt;
1175
1176 /* Note: we turn off ubsan float cast overflow detection for this function, since it would complain
1177 * about our float casts but we do them explicitly to detect conversion errors. */
1178
1179 v = json_variant_dereference(v);
1180 if (!v)
1181 return false;
1182
1183 rt = sd_json_variant_type(v);
1184 if (rt == type)
1185 return true;
1186
1187 /* If it's a const string, then it only can be a string, and if it is not, it's not */
1188 if (json_variant_is_const_string(v))
1189 return false;
1190
1191 /* All three magic zeroes qualify as integer, unsigned and as real */
1192 if ((v == JSON_VARIANT_MAGIC_ZERO_INTEGER || v == JSON_VARIANT_MAGIC_ZERO_UNSIGNED || v == JSON_VARIANT_MAGIC_ZERO_REAL) &&
1193 IN_SET(type, SD_JSON_VARIANT_INTEGER, SD_JSON_VARIANT_UNSIGNED, SD_JSON_VARIANT_REAL, SD_JSON_VARIANT_NUMBER))
1194 return true;
1195
1196 /* All other magic variant types are only equal to themselves */
1197 if (json_variant_is_magic(v))
1198 return false;
1199
1200 /* Handle the "number" pseudo type */
1201 if (type == SD_JSON_VARIANT_NUMBER)
1202 return IN_SET(rt, SD_JSON_VARIANT_INTEGER, SD_JSON_VARIANT_UNSIGNED, SD_JSON_VARIANT_REAL);
1203
1204 /* Integer conversions are OK in many cases */
1205 if (rt == SD_JSON_VARIANT_INTEGER && type == SD_JSON_VARIANT_UNSIGNED)
1206 return v->value.integer >= 0;
1207 if (rt == SD_JSON_VARIANT_UNSIGNED && type == SD_JSON_VARIANT_INTEGER)
1208 return v->value.unsig <= INT64_MAX;
1209
1210 /* Any integer that can be converted lossley to a real and back may also be considered a real */
1211 if (rt == SD_JSON_VARIANT_INTEGER && type == SD_JSON_VARIANT_REAL)
1212 return (int64_t) (double) v->value.integer == v->value.integer;
1213 if (rt == SD_JSON_VARIANT_UNSIGNED && type == SD_JSON_VARIANT_REAL)
1214 return (uint64_t) (double) v->value.unsig == v->value.unsig;
1215
1216 /* Any real that can be converted losslessly to an integer and back may also be considered an integer */
1217 if (rt == SD_JSON_VARIANT_REAL && type == SD_JSON_VARIANT_INTEGER)
1218 return fp_equal((double) (int64_t) v->value.real, v->value.real);
1219 if (rt == SD_JSON_VARIANT_REAL && type == SD_JSON_VARIANT_UNSIGNED)
1220 return fp_equal((double) (uint64_t) v->value.real, v->value.real);
1221
1222 return false;
1223 }
1224
1225 _public_ int sd_json_variant_is_string(sd_json_variant *v) {
1226 return sd_json_variant_has_type(v, SD_JSON_VARIANT_STRING);
1227 }
1228
1229 _public_ int sd_json_variant_is_integer(sd_json_variant *v) {
1230 return sd_json_variant_has_type(v, SD_JSON_VARIANT_INTEGER);
1231 }
1232
1233 _public_ int sd_json_variant_is_unsigned(sd_json_variant *v) {
1234 return sd_json_variant_has_type(v, SD_JSON_VARIANT_UNSIGNED);
1235 }
1236
1237 _public_ int sd_json_variant_is_real(sd_json_variant *v) {
1238 return sd_json_variant_has_type(v, SD_JSON_VARIANT_REAL);
1239 }
1240
1241 _public_ int sd_json_variant_is_number(sd_json_variant *v) {
1242 return sd_json_variant_has_type(v, SD_JSON_VARIANT_NUMBER);
1243 }
1244
1245 _public_ int sd_json_variant_is_boolean(sd_json_variant *v) {
1246 return sd_json_variant_has_type(v, SD_JSON_VARIANT_BOOLEAN);
1247 }
1248
1249 _public_ int sd_json_variant_is_array(sd_json_variant *v) {
1250 return sd_json_variant_has_type(v, SD_JSON_VARIANT_ARRAY);
1251 }
1252
1253 _public_ int sd_json_variant_is_object(sd_json_variant *v) {
1254 return sd_json_variant_has_type(v, SD_JSON_VARIANT_OBJECT);
1255 }
1256
1257 _public_ int sd_json_variant_is_null(sd_json_variant *v) {
1258 return sd_json_variant_has_type(v, SD_JSON_VARIANT_NULL);
1259 }
1260
1261 _public_ size_t sd_json_variant_elements(sd_json_variant *v) {
1262 if (!v)
1263 return 0;
1264 if (v == JSON_VARIANT_MAGIC_EMPTY_ARRAY ||
1265 v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
1266 return 0;
1267 if (!json_variant_is_regular(v))
1268 goto mismatch;
1269 if (!IN_SET(v->type, SD_JSON_VARIANT_ARRAY, SD_JSON_VARIANT_OBJECT))
1270 goto mismatch;
1271 if (v->is_reference)
1272 return sd_json_variant_elements(v->reference);
1273
1274 return v->n_elements;
1275
1276 mismatch:
1277 log_debug("Number of elements in non-array/non-object JSON variant requested, returning 0.");
1278 return 0;
1279 }
1280
1281 _public_ sd_json_variant *sd_json_variant_by_index(sd_json_variant *v, size_t index) {
1282 if (!v)
1283 return NULL;
1284 if (v == JSON_VARIANT_MAGIC_EMPTY_ARRAY ||
1285 v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
1286 return NULL;
1287 if (!json_variant_is_regular(v))
1288 goto mismatch;
1289 if (!IN_SET(v->type, SD_JSON_VARIANT_ARRAY, SD_JSON_VARIANT_OBJECT))
1290 goto mismatch;
1291 if (v->is_reference)
1292 return sd_json_variant_by_index(v->reference, index);
1293 if (index >= v->n_elements)
1294 return NULL;
1295
1296 return json_variant_conservative_formalize(v + 1 + index);
1297
1298 mismatch:
1299 log_debug("Element in non-array/non-object JSON variant requested by index, returning NULL.");
1300 return NULL;
1301 }
1302
1303 _public_ sd_json_variant *sd_json_variant_by_key_full(sd_json_variant *v, const char *key, sd_json_variant **ret_key) {
1304 if (!v)
1305 goto not_found;
1306 if (!key)
1307 goto not_found;
1308 if (v == JSON_VARIANT_MAGIC_EMPTY_OBJECT)
1309 goto not_found;
1310 if (!json_variant_is_regular(v))
1311 goto mismatch;
1312 if (v->type != SD_JSON_VARIANT_OBJECT)
1313 goto mismatch;
1314 if (v->is_reference)
1315 return sd_json_variant_by_key(v->reference, key);
1316
1317 if (v->sorted) {
1318 size_t a = 0, b = v->n_elements/2;
1319
1320 /* If the variant is sorted we can use bisection to find the entry we need in O(log(n)) time */
1321
1322 while (b > a) {
1323 sd_json_variant *p;
1324 const char *f;
1325 size_t i;
1326 int c;
1327
1328 i = (a + b) / 2;
1329 p = json_variant_dereference(v + 1 + i*2);
1330
1331 assert_se(f = sd_json_variant_string(p));
1332
1333 c = strcmp(key, f);
1334 if (c == 0) {
1335 if (ret_key)
1336 *ret_key = json_variant_conservative_formalize(v + 1 + i*2);
1337
1338 return json_variant_conservative_formalize(v + 1 + i*2 + 1);
1339 } else if (c < 0)
1340 b = i;
1341 else
1342 a = i + 1;
1343 }
1344
1345 goto not_found;
1346 }
1347
1348 /* The variant is not sorted, hence search for the field linearly */
1349 for (size_t i = 0; i < v->n_elements; i += 2) {
1350 sd_json_variant *p;
1351
1352 p = json_variant_dereference(v + 1 + i);
1353
1354 if (!sd_json_variant_has_type(p, SD_JSON_VARIANT_STRING))
1355 continue;
1356
1357 if (streq(sd_json_variant_string(p), key)) {
1358
1359 if (ret_key)
1360 *ret_key = json_variant_conservative_formalize(v + 1 + i);
1361
1362 return json_variant_conservative_formalize(v + 1 + i + 1);
1363 }
1364 }
1365
1366 not_found:
1367 if (ret_key)
1368 *ret_key = NULL;
1369
1370 return NULL;
1371
1372 mismatch:
1373 log_debug("Element in non-object JSON variant requested by key, returning NULL.");
1374 if (ret_key)
1375 *ret_key = NULL;
1376
1377 return NULL;
1378 }
1379
1380 _public_ sd_json_variant *sd_json_variant_by_key(sd_json_variant *v, const char *key) {
1381 return sd_json_variant_by_key_full(v, key, NULL);
1382 }
1383
1384 _public_ int sd_json_variant_equal(sd_json_variant *a, sd_json_variant *b) {
1385 sd_json_variant_type_t t;
1386
1387 a = json_variant_formalize(a);
1388 b = json_variant_formalize(b);
1389
1390 if (a == b)
1391 return true;
1392
1393 t = sd_json_variant_type(a);
1394 if (!sd_json_variant_has_type(b, t))
1395 return false;
1396
1397 switch (t) {
1398
1399 case SD_JSON_VARIANT_STRING:
1400 return streq(sd_json_variant_string(a), sd_json_variant_string(b));
1401
1402 case SD_JSON_VARIANT_INTEGER:
1403 return sd_json_variant_integer(a) == sd_json_variant_integer(b);
1404
1405 case SD_JSON_VARIANT_UNSIGNED:
1406 return sd_json_variant_unsigned(a) == sd_json_variant_unsigned(b);
1407
1408 case SD_JSON_VARIANT_REAL:
1409 return fp_equal(sd_json_variant_real(a), sd_json_variant_real(b));
1410
1411 case SD_JSON_VARIANT_BOOLEAN:
1412 return sd_json_variant_boolean(a) == sd_json_variant_boolean(b);
1413
1414 case SD_JSON_VARIANT_NULL:
1415 return true;
1416
1417 case SD_JSON_VARIANT_ARRAY: {
1418 size_t n = sd_json_variant_elements(a);
1419 if (n != sd_json_variant_elements(b))
1420 return false;
1421
1422 for (size_t i = 0; i < n; i++)
1423 if (!sd_json_variant_equal(sd_json_variant_by_index(a, i), sd_json_variant_by_index(b, i)))
1424 return false;
1425
1426 return true;
1427 }
1428
1429 case SD_JSON_VARIANT_OBJECT: {
1430 size_t n = sd_json_variant_elements(a);
1431 if (n != sd_json_variant_elements(b))
1432 return false;
1433
1434 /* Iterate through all keys in 'a' */
1435 for (size_t i = 0; i < n; i += 2) {
1436 bool found = false;
1437
1438 /* Match them against all keys in 'b' */
1439 for (size_t j = 0; j < n; j += 2) {
1440 sd_json_variant *key_b;
1441
1442 key_b = sd_json_variant_by_index(b, j);
1443
1444 /* During the first iteration unmark everything */
1445 if (i == 0)
1446 key_b->is_marked = false;
1447 else if (key_b->is_marked) /* In later iterations if we already marked something, don't bother with it again */
1448 continue;
1449
1450 if (found)
1451 continue;
1452
1453 if (sd_json_variant_equal(sd_json_variant_by_index(a, i), key_b) &&
1454 sd_json_variant_equal(sd_json_variant_by_index(a, i+1), sd_json_variant_by_index(b, j+1))) {
1455 /* Key and values match! */
1456 key_b->is_marked = found = true;
1457
1458 /* In the first iteration we continue the inner loop since we want to mark
1459 * everything, otherwise exit the loop quickly after we found what we were
1460 * looking for. */
1461 if (i != 0)
1462 break;
1463 }
1464 }
1465
1466 if (!found)
1467 return false;
1468 }
1469
1470 return true;
1471 }
1472
1473 default:
1474 assert_not_reached();
1475 }
1476 }
1477
1478 _public_ void sd_json_variant_sensitive(sd_json_variant *v) {
1479 if (!v)
1480 return;
1481
1482 /* Marks a variant as "sensitive", so that it is erased from memory when it is destroyed. This is a
1483 * one-way operation: as soon as it is marked this way it remains marked this way until it's
1484 * destroyed. A magic variant is never sensitive though, even when asked, since it's too
1485 * basic. Similar, const string variant are never sensitive either, after all they are included in
1486 * the source code as they are, which is not suitable for inclusion of secrets.
1487 *
1488 * Note that this flag has a recursive effect: when we destroy an object or array we'll propagate the
1489 * flag to all contained variants. And if those are then destroyed this is propagated further down,
1490 * and so on. */
1491
1492 v = json_variant_formalize(v);
1493 if (!json_variant_is_regular(v))
1494 return;
1495
1496 v->sensitive = true;
1497 }
1498
1499 _public_ int sd_json_variant_is_sensitive(sd_json_variant *v) {
1500 v = json_variant_formalize(v);
1501 if (!json_variant_is_regular(v))
1502 return false;
1503
1504 return v->sensitive;
1505 }
1506
1507 _public_ int sd_json_variant_is_sensitive_recursive(sd_json_variant *v) {
1508 if (!v)
1509 return false;
1510 if (sd_json_variant_is_sensitive(v))
1511 return true;
1512 if (!json_variant_is_regular(v))
1513 return false;
1514 if (v->recursive_sensitive) /* Already checked this before */
1515 return true;
1516 if (!IN_SET(v->type, SD_JSON_VARIANT_ARRAY, SD_JSON_VARIANT_OBJECT))
1517 return false;
1518 if (v->is_reference) {
1519 if (!sd_json_variant_is_sensitive_recursive(v->reference))
1520 return false;
1521
1522 return (v->recursive_sensitive = true);
1523 }
1524
1525 for (size_t i = 0; i < sd_json_variant_elements(v); i++)
1526 if (sd_json_variant_is_sensitive_recursive(sd_json_variant_by_index(v, i)))
1527 return (v->recursive_sensitive = true);
1528
1529 /* Note: we only cache the result here in case true, since we allow all elements down the tree to
1530 * have their sensitive flag toggled later on (but never off) */
1531 return false;
1532 }
1533
1534 static void json_variant_propagate_sensitive(sd_json_variant *from, sd_json_variant *to) {
1535 if (sd_json_variant_is_sensitive(from))
1536 sd_json_variant_sensitive(to);
1537 }
1538
1539 _public_ int sd_json_variant_get_source(sd_json_variant *v, const char **ret_source, unsigned *ret_line, unsigned *ret_column) {
1540 assert_return(v, -EINVAL);
1541
1542 if (ret_source)
1543 *ret_source = json_variant_is_regular(v) && v->source ? v->source->name : NULL;
1544
1545 if (ret_line)
1546 *ret_line = json_variant_is_regular(v) ? v->line : 0;
1547
1548 if (ret_column)
1549 *ret_column = json_variant_is_regular(v) ? v->column : 0;
1550
1551 return 0;
1552 }
1553
1554 static int print_source(FILE *f, sd_json_variant *v, sd_json_format_flags_t flags, bool whitespace) {
1555 size_t w, k;
1556
1557 if (!FLAGS_SET(flags, SD_JSON_FORMAT_SOURCE|SD_JSON_FORMAT_PRETTY))
1558 return 0;
1559
1560 if (!json_variant_is_regular(v))
1561 return 0;
1562
1563 if (!v->source && v->line == 0 && v->column == 0)
1564 return 0;
1565
1566 /* The max width we need to format the line numbers for this source file */
1567 w = (v->source && v->source->max_line > 0) ?
1568 DECIMAL_STR_WIDTH(v->source->max_line) :
1569 DECIMAL_STR_MAX(unsigned)-1;
1570 k = (v->source && v->source->max_column > 0) ?
1571 DECIMAL_STR_WIDTH(v->source->max_column) :
1572 DECIMAL_STR_MAX(unsigned) -1;
1573
1574 if (whitespace) {
1575 size_t n = 1 + (v->source ? strlen(v->source->name) : 0) +
1576 ((v->source && (v->line > 0 || v->column > 0)) ? 1 : 0) +
1577 (v->line > 0 ? w : 0) +
1578 (((v->source || v->line > 0) && v->column > 0) ? 1 : 0) +
1579 (v->column > 0 ? k : 0) +
1580 2;
1581
1582 for (size_t i = 0; i < n; i++)
1583 fputc(' ', f);
1584 } else {
1585 fputc('[', f);
1586
1587 if (v->source)
1588 fputs(v->source->name, f);
1589 if (v->source && (v->line > 0 || v->column > 0))
1590 fputc(':', f);
1591 if (v->line > 0)
1592 fprintf(f, "%*u", (int) w, v->line);
1593 if ((v->source || v->line > 0) || v->column > 0)
1594 fputc(':', f);
1595 if (v->column > 0)
1596 fprintf(f, "%*u", (int) k, v->column);
1597
1598 fputc(']', f);
1599 fputc(' ', f);
1600 }
1601
1602 return 0;
1603 }
1604
1605 static void json_format_string(FILE *f, const char *q, sd_json_format_flags_t flags) {
1606 assert(q);
1607
1608 fputc('"', f);
1609
1610 if (flags & SD_JSON_FORMAT_COLOR)
1611 fputs(ansi_green(), f);
1612
1613 for (; *q; q++)
1614 switch (*q) {
1615 case '"':
1616 fputs("\\\"", f);
1617 break;
1618
1619 case '\\':
1620 fputs("\\\\", f);
1621 break;
1622
1623 case '\b':
1624 fputs("\\b", f);
1625 break;
1626
1627 case '\f':
1628 fputs("\\f", f);
1629 break;
1630
1631 case '\n':
1632 fputs("\\n", f);
1633 break;
1634
1635 case '\r':
1636 fputs("\\r", f);
1637 break;
1638
1639 case '\t':
1640 fputs("\\t", f);
1641 break;
1642
1643 default:
1644 if ((signed char) *q >= 0 && *q < ' ')
1645 fprintf(f, "\\u%04x", (unsigned) *q);
1646 else
1647 fputc(*q, f);
1648 }
1649
1650 if (flags & SD_JSON_FORMAT_COLOR)
1651 fputs(ANSI_NORMAL, f);
1652
1653 fputc('"', f);
1654 }
1655
1656 static int json_format(FILE *f, sd_json_variant *v, sd_json_format_flags_t flags, const char *prefix) {
1657 int r;
1658
1659 assert(f);
1660 assert(v);
1661
1662 if (FLAGS_SET(flags, SD_JSON_FORMAT_CENSOR_SENSITIVE) && sd_json_variant_is_sensitive(v)) {
1663 if (flags & SD_JSON_FORMAT_COLOR)
1664 fputs(ansi_red(), f);
1665 fputs("\"<sensitive data>\"", f);
1666 if (flags & SD_JSON_FORMAT_COLOR)
1667 fputs(ANSI_NORMAL, f);
1668 return 0;
1669 }
1670
1671 switch (sd_json_variant_type(v)) {
1672
1673 case SD_JSON_VARIANT_REAL: {
1674 locale_t loc, old_loc;
1675
1676 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
1677 if (loc == (locale_t) 0)
1678 return -errno;
1679
1680 if (flags & SD_JSON_FORMAT_COLOR)
1681 fputs(ansi_highlight_blue(), f);
1682
1683 old_loc = uselocale(loc);
1684 fprintf(f, "%.*e", DECIMAL_DIG, sd_json_variant_real(v));
1685 uselocale(old_loc);
1686
1687 if (flags & SD_JSON_FORMAT_COLOR)
1688 fputs(ANSI_NORMAL, f);
1689
1690 freelocale(loc);
1691 break;
1692 }
1693
1694 case SD_JSON_VARIANT_INTEGER:
1695 if (flags & SD_JSON_FORMAT_COLOR)
1696 fputs(ansi_highlight_blue(), f);
1697
1698 fprintf(f, "%" PRIdMAX, sd_json_variant_integer(v));
1699
1700 if (flags & SD_JSON_FORMAT_COLOR)
1701 fputs(ANSI_NORMAL, f);
1702 break;
1703
1704 case SD_JSON_VARIANT_UNSIGNED:
1705 if (flags & SD_JSON_FORMAT_COLOR)
1706 fputs(ansi_highlight_blue(), f);
1707
1708 fprintf(f, "%" PRIuMAX, sd_json_variant_unsigned(v));
1709
1710 if (flags & SD_JSON_FORMAT_COLOR)
1711 fputs(ANSI_NORMAL, f);
1712 break;
1713
1714 case SD_JSON_VARIANT_BOOLEAN:
1715
1716 if (flags & SD_JSON_FORMAT_COLOR)
1717 fputs(ANSI_HIGHLIGHT, f);
1718
1719 if (sd_json_variant_boolean(v))
1720 fputs("true", f);
1721 else
1722 fputs("false", f);
1723
1724 if (flags & SD_JSON_FORMAT_COLOR)
1725 fputs(ANSI_NORMAL, f);
1726
1727 break;
1728
1729 case SD_JSON_VARIANT_NULL:
1730 if (flags & SD_JSON_FORMAT_COLOR)
1731 fputs(ANSI_HIGHLIGHT, f);
1732
1733 fputs("null", f);
1734
1735 if (flags & SD_JSON_FORMAT_COLOR)
1736 fputs(ANSI_NORMAL, f);
1737 break;
1738
1739 case SD_JSON_VARIANT_STRING:
1740 json_format_string(f, sd_json_variant_string(v), flags);
1741 break;
1742
1743 case SD_JSON_VARIANT_ARRAY: {
1744 size_t n = sd_json_variant_elements(v);
1745 if (n == 0)
1746 fputs("[]", f);
1747 else {
1748 _cleanup_free_ char *joined = NULL;
1749 const char *prefix2;
1750
1751 if (flags & SD_JSON_FORMAT_PRETTY) {
1752 joined = strjoin(strempty(prefix), "\t");
1753 if (!joined)
1754 return -ENOMEM;
1755
1756 prefix2 = joined;
1757 fputs("[\n", f);
1758 } else {
1759 prefix2 = strempty(prefix);
1760 fputc('[', f);
1761 }
1762
1763 for (size_t i = 0; i < n; i++) {
1764 sd_json_variant *e;
1765
1766 assert_se(e = sd_json_variant_by_index(v, i));
1767
1768 if (i > 0) {
1769 if (flags & SD_JSON_FORMAT_PRETTY)
1770 fputs(",\n", f);
1771 else
1772 fputc(',', f);
1773 }
1774
1775 if (flags & SD_JSON_FORMAT_PRETTY) {
1776 print_source(f, e, flags, false);
1777 fputs(prefix2, f);
1778 }
1779
1780 r = json_format(f, e, flags, prefix2);
1781 if (r < 0)
1782 return r;
1783 }
1784
1785 if (flags & SD_JSON_FORMAT_PRETTY) {
1786 fputc('\n', f);
1787 print_source(f, v, flags, true);
1788 fputs(strempty(prefix), f);
1789 }
1790
1791 fputc(']', f);
1792 }
1793 break;
1794 }
1795
1796 case SD_JSON_VARIANT_OBJECT: {
1797 size_t n = sd_json_variant_elements(v);
1798 if (n == 0)
1799 fputs("{}", f);
1800 else {
1801 _cleanup_free_ char *joined = NULL;
1802 const char *prefix2;
1803
1804 if (flags & SD_JSON_FORMAT_PRETTY) {
1805 joined = strjoin(strempty(prefix), "\t");
1806 if (!joined)
1807 return -ENOMEM;
1808
1809 prefix2 = joined;
1810 fputs("{\n", f);
1811 } else {
1812 prefix2 = strempty(prefix);
1813 fputc('{', f);
1814 }
1815
1816 for (size_t i = 0; i < n; i += 2) {
1817 sd_json_variant *e;
1818
1819 e = sd_json_variant_by_index(v, i);
1820
1821 if (i > 0) {
1822 if (flags & SD_JSON_FORMAT_PRETTY)
1823 fputs(",\n", f);
1824 else
1825 fputc(',', f);
1826 }
1827
1828 if (flags & SD_JSON_FORMAT_PRETTY) {
1829 print_source(f, e, flags, false);
1830 fputs(prefix2, f);
1831 }
1832
1833 r = json_format(f, e, flags, prefix2);
1834 if (r < 0)
1835 return r;
1836
1837 fputs(flags & SD_JSON_FORMAT_PRETTY ? " : " : ":", f);
1838
1839 r = json_format(f, sd_json_variant_by_index(v, i+1), flags, prefix2);
1840 if (r < 0)
1841 return r;
1842 }
1843
1844 if (flags & SD_JSON_FORMAT_PRETTY) {
1845 fputc('\n', f);
1846 print_source(f, v, flags, true);
1847 fputs(strempty(prefix), f);
1848 }
1849
1850 fputc('}', f);
1851 }
1852 break;
1853 }
1854
1855 default:
1856 assert_not_reached();
1857 }
1858
1859 return 0;
1860 }
1861
1862 _public_ int sd_json_variant_format(sd_json_variant *v, sd_json_format_flags_t flags, char **ret) {
1863 _cleanup_(memstream_done) MemStream m = {};
1864 size_t sz;
1865 FILE *f;
1866 int r;
1867
1868 /* Returns the length of the generated string (without the terminating NUL),
1869 * or negative on error. */
1870
1871 assert_return(v, -EINVAL);
1872 assert_return(ret, -EINVAL);
1873
1874 if (!sd_json_format_enabled(flags))
1875 return -ENOEXEC;
1876
1877 f = memstream_init(&m);
1878 if (!f)
1879 return -ENOMEM;
1880
1881 r = sd_json_variant_dump(v, flags, f, NULL);
1882 if (r < 0)
1883 return r;
1884
1885 r = memstream_finalize(&m, ret, &sz);
1886 if (r < 0)
1887 return r;
1888
1889 return sz;
1890 }
1891
1892 _public_ int sd_json_variant_dump(sd_json_variant *v, sd_json_format_flags_t flags, FILE *f, const char *prefix) {
1893 if (!v) {
1894 if (flags & SD_JSON_FORMAT_EMPTY_ARRAY)
1895 v = JSON_VARIANT_MAGIC_EMPTY_ARRAY;
1896 else
1897 return 0;
1898 }
1899
1900 if (!f)
1901 f = stdout;
1902
1903 print_source(f, v, flags, false);
1904
1905 if (((flags & (SD_JSON_FORMAT_COLOR_AUTO|SD_JSON_FORMAT_COLOR)) == SD_JSON_FORMAT_COLOR_AUTO) && colors_enabled())
1906 flags |= SD_JSON_FORMAT_COLOR;
1907
1908 if (((flags & (SD_JSON_FORMAT_PRETTY_AUTO|SD_JSON_FORMAT_PRETTY)) == SD_JSON_FORMAT_PRETTY_AUTO))
1909 flags |= on_tty() ? SD_JSON_FORMAT_PRETTY : SD_JSON_FORMAT_NEWLINE;
1910
1911 if (flags & SD_JSON_FORMAT_SSE)
1912 fputs("data: ", f);
1913 if (flags & SD_JSON_FORMAT_SEQ)
1914 fputc('\x1e', f); /* ASCII Record Separator */
1915
1916 json_format(f, v, flags, prefix);
1917
1918 if (flags & (SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_SEQ|SD_JSON_FORMAT_SSE|SD_JSON_FORMAT_NEWLINE))
1919 fputc('\n', f);
1920 if (flags & SD_JSON_FORMAT_SSE)
1921 fputc('\n', f); /* In case of SSE add a second newline */
1922
1923 if (flags & SD_JSON_FORMAT_FLUSH)
1924 return fflush_and_check(f);
1925 return 0;
1926 }
1927
1928 _public_ int sd_json_variant_filter(sd_json_variant **v, char **to_remove) {
1929 _cleanup_(sd_json_variant_unrefp) sd_json_variant *w = NULL;
1930 _cleanup_free_ sd_json_variant **array = NULL;
1931 size_t n = 0, k = 0;
1932 int r;
1933
1934 assert_return(v, -EINVAL);
1935
1936 if (sd_json_variant_is_blank_object(*v))
1937 return 0;
1938 if (!sd_json_variant_is_object(*v))
1939 return -EINVAL;
1940
1941 if (strv_isempty(to_remove))
1942 return 0;
1943
1944 for (size_t i = 0, m = sd_json_variant_elements(*v); i < m; i += 2) {
1945 sd_json_variant *p;
1946
1947 p = sd_json_variant_by_index(*v, i);
1948 if (!sd_json_variant_has_type(p, SD_JSON_VARIANT_STRING))
1949 return -EINVAL;
1950
1951 if (strv_contains(to_remove, sd_json_variant_string(p))) {
1952 if (!array) {
1953 /* Silence static analyzers */
1954 assert(m >= 2);
1955 array = new(sd_json_variant*, m - 2);
1956 if (!array)
1957 return -ENOMEM;
1958
1959 for (k = 0; k < i; k++)
1960 array[k] = sd_json_variant_by_index(*v, k);
1961 }
1962
1963 n++;
1964 } else if (array) {
1965 array[k++] = p;
1966 array[k++] = sd_json_variant_by_index(*v, i + 1);
1967 }
1968 }
1969
1970 if (n == 0)
1971 return 0;
1972
1973 r = sd_json_variant_new_object(&w, array, k);
1974 if (r < 0)
1975 return r;
1976
1977 json_variant_propagate_sensitive(*v, w);
1978 json_variant_unref_and_replace(*v, w);
1979
1980 return (int) n;
1981 }
1982
1983 _public_ int sd_json_variant_set_field(sd_json_variant **v, const char *field, sd_json_variant *value) {
1984 _cleanup_(sd_json_variant_unrefp) sd_json_variant *field_variant = NULL, *w = NULL;
1985 _cleanup_free_ sd_json_variant **array = NULL;
1986 size_t k = 0;
1987 int r;
1988
1989 assert_return(v, -EINVAL);
1990 assert_return(field, -EINVAL);
1991
1992 if (sd_json_variant_is_blank_object(*v)) {
1993 array = new(sd_json_variant*, 2);
1994 if (!array)
1995 return -ENOMEM;
1996
1997 } else {
1998 if (!sd_json_variant_is_object(*v))
1999 return -EINVAL;
2000
2001 for (size_t i = 0; i < sd_json_variant_elements(*v); i += 2) {
2002 sd_json_variant *p;
2003
2004 p = sd_json_variant_by_index(*v, i);
2005 if (!sd_json_variant_is_string(p))
2006 return -EINVAL;
2007
2008 if (streq(sd_json_variant_string(p), field)) {
2009
2010 if (!array) {
2011 array = new(sd_json_variant*, sd_json_variant_elements(*v));
2012 if (!array)
2013 return -ENOMEM;
2014
2015 for (k = 0; k < i; k++)
2016 array[k] = sd_json_variant_by_index(*v, k);
2017 }
2018
2019 } else if (array) {
2020 array[k++] = p;
2021 array[k++] = sd_json_variant_by_index(*v, i + 1);
2022 }
2023 }
2024
2025 if (!array) {
2026 array = new(sd_json_variant*, sd_json_variant_elements(*v) + 2);
2027 if (!array)
2028 return -ENOMEM;
2029
2030 for (k = 0; k < sd_json_variant_elements(*v); k++)
2031 array[k] = sd_json_variant_by_index(*v, k);
2032 }
2033 }
2034
2035 r = sd_json_variant_new_string(&field_variant, field);
2036 if (r < 0)
2037 return r;
2038
2039 array[k++] = field_variant;
2040 array[k++] = value;
2041
2042 r = sd_json_variant_new_object(&w, array, k);
2043 if (r < 0)
2044 return r;
2045
2046 json_variant_propagate_sensitive(*v, w);
2047 json_variant_unref_and_replace(*v, w);
2048
2049 return 1;
2050 }
2051
2052 _public_ int sd_json_variant_set_fieldb(sd_json_variant **v, const char *field, ...) {
2053 _cleanup_(sd_json_variant_unrefp) sd_json_variant *w = NULL;
2054 va_list ap;
2055 int r;
2056
2057 va_start(ap, field);
2058 r = sd_json_buildv(&w, ap);
2059 va_end(ap);
2060 if (r < 0)
2061 return r;
2062
2063 return sd_json_variant_set_field(v, field, w);
2064 }
2065
2066 _public_ int sd_json_variant_set_field_string(sd_json_variant **v, const char *field, const char *value) {
2067 _cleanup_(sd_json_variant_unrefp) sd_json_variant *m = NULL;
2068 int r;
2069
2070 r = sd_json_variant_new_string(&m, value);
2071 if (r < 0)
2072 return r;
2073
2074 return sd_json_variant_set_field(v, field, m);
2075 }
2076
2077 _public_ int sd_json_variant_set_field_id128(sd_json_variant **v, const char *field, sd_id128_t value) {
2078 return sd_json_variant_set_field_string(v, field, SD_ID128_TO_STRING(value));
2079 }
2080
2081 _public_ int sd_json_variant_set_field_uuid(sd_json_variant **v, const char *field, sd_id128_t value) {
2082 return sd_json_variant_set_field_string(v, field, SD_ID128_TO_UUID_STRING(value));
2083 }
2084
2085 _public_ int sd_json_variant_set_field_integer(sd_json_variant **v, const char *field, int64_t value) {
2086 _cleanup_(sd_json_variant_unrefp) sd_json_variant *m = NULL;
2087 int r;
2088
2089 r = sd_json_variant_new_integer(&m, value);
2090 if (r < 0)
2091 return r;
2092
2093 return sd_json_variant_set_field(v, field, m);
2094 }
2095
2096 _public_ int sd_json_variant_set_field_unsigned(sd_json_variant **v, const char *field, uint64_t value) {
2097 _cleanup_(sd_json_variant_unrefp) sd_json_variant *m = NULL;
2098 int r;
2099
2100 r = sd_json_variant_new_unsigned(&m, value);
2101 if (r < 0)
2102 return r;
2103
2104 return sd_json_variant_set_field(v, field, m);
2105 }
2106
2107 _public_ int sd_json_variant_set_field_boolean(sd_json_variant **v, const char *field, int b) {
2108 _cleanup_(sd_json_variant_unrefp) sd_json_variant *m = NULL;
2109 int r;
2110
2111 r = sd_json_variant_new_boolean(&m, b);
2112 if (r < 0)
2113 return r;
2114
2115 return sd_json_variant_set_field(v, field, m);
2116 }
2117
2118 _public_ int sd_json_variant_set_field_strv(sd_json_variant **v, const char *field, char **l) {
2119 _cleanup_(sd_json_variant_unrefp) sd_json_variant *m = NULL;
2120 int r;
2121
2122 r = sd_json_variant_new_array_strv(&m, l);
2123 if (r < 0)
2124 return r;
2125
2126 return sd_json_variant_set_field(v, field, m);
2127 }
2128
2129 _public_ int sd_json_variant_merge_object(sd_json_variant **v, sd_json_variant *m) {
2130 _cleanup_(sd_json_variant_unrefp) sd_json_variant *w = NULL;
2131 _cleanup_free_ sd_json_variant **array = NULL;
2132 size_t v_elements, m_elements, k;
2133 bool v_blank, m_blank;
2134 int r;
2135
2136 m = json_variant_dereference(m);
2137
2138 v_blank = sd_json_variant_is_blank_object(*v);
2139 m_blank = sd_json_variant_is_blank_object(m);
2140
2141 if (!v_blank && !sd_json_variant_is_object(*v))
2142 return -EINVAL;
2143 if (!m_blank && !sd_json_variant_is_object(m))
2144 return -EINVAL;
2145
2146 if (m_blank)
2147 return 0; /* nothing to do */
2148
2149 if (v_blank) {
2150 JSON_VARIANT_REPLACE(*v, sd_json_variant_ref(m));
2151 return 1;
2152 }
2153
2154 v_elements = sd_json_variant_elements(*v);
2155 m_elements = sd_json_variant_elements(m);
2156 if (v_elements > SIZE_MAX - m_elements) /* overflow check */
2157 return -ENOMEM;
2158
2159 array = new(sd_json_variant*, v_elements + m_elements);
2160 if (!array)
2161 return -ENOMEM;
2162
2163 k = 0;
2164 for (size_t i = 0; i < v_elements; i += 2) {
2165 sd_json_variant *u;
2166
2167 u = sd_json_variant_by_index(*v, i);
2168 if (!sd_json_variant_is_string(u))
2169 return -EINVAL;
2170
2171 if (sd_json_variant_by_key(m, sd_json_variant_string(u)))
2172 continue; /* skip if exists in second variant */
2173
2174 array[k++] = u;
2175 array[k++] = sd_json_variant_by_index(*v, i + 1);
2176 }
2177
2178 for (size_t i = 0; i < m_elements; i++)
2179 array[k++] = sd_json_variant_by_index(m, i);
2180
2181 r = sd_json_variant_new_object(&w, array, k);
2182 if (r < 0)
2183 return r;
2184
2185 json_variant_propagate_sensitive(*v, w);
2186 json_variant_propagate_sensitive(m, w);
2187 json_variant_unref_and_replace(*v, w);
2188
2189 return 1;
2190 }
2191
2192 _public_ int sd_json_variant_merge_objectb(sd_json_variant **v, ...) {
2193 _cleanup_(sd_json_variant_unrefp) sd_json_variant *w = NULL;
2194 va_list ap;
2195 int r;
2196
2197 va_start(ap, v);
2198 r = sd_json_buildv(&w, ap);
2199 va_end(ap);
2200 if (r < 0)
2201 return r;
2202
2203 return sd_json_variant_merge_object(v, w);
2204 }
2205
2206 _public_ int sd_json_variant_append_array(sd_json_variant **v, sd_json_variant *element) {
2207 _cleanup_(sd_json_variant_unrefp) sd_json_variant *nv = NULL;
2208 bool blank;
2209 int r;
2210
2211 assert_return(v, -EINVAL);
2212 assert_return(element, -EINVAL);
2213
2214 if (!*v || sd_json_variant_is_null(*v))
2215 blank = true;
2216 else if (sd_json_variant_is_array(*v))
2217 blank = sd_json_variant_elements(*v) == 0;
2218 else
2219 return -EINVAL;
2220
2221 if (blank) {
2222 r = sd_json_variant_new_array(&nv, (sd_json_variant*[]) { element }, 1);
2223 if (r < 0)
2224 return r;
2225 } else if (json_variant_n_ref(*v) == 1) {
2226 /* Let's bump the reference count on element. We can't do the realloc if we're appending *v
2227 * to itself, or one of the objects embedded in *v to *v. If the reference count grows, we
2228 * need to fall back to the other method below. */
2229
2230 _unused_ _cleanup_(sd_json_variant_unrefp) sd_json_variant *dummy = sd_json_variant_ref(element);
2231 if (json_variant_n_ref(*v) == 1) {
2232 /* We hold the only reference. Let's mutate the object. */
2233 size_t size = sd_json_variant_elements(*v);
2234 void *old = *v;
2235
2236 if (!GREEDY_REALLOC(*v, size + 1 + 1))
2237 return -ENOMEM;
2238
2239 if (old != *v)
2240 /* Readjust the parent pointers to the new address */
2241 for (size_t i = 0; i < size; i++)
2242 (*v)[1 + i].parent = *v;
2243
2244 return json_variant_array_put_element(*v, element);
2245 }
2246 }
2247
2248 if (!blank) {
2249 size_t size = sd_json_variant_elements(*v);
2250
2251 _cleanup_free_ sd_json_variant **array = new(sd_json_variant*, size + 1);
2252 if (!array)
2253 return -ENOMEM;
2254
2255 for (size_t i = 0; i < size; i++)
2256 array[i] = sd_json_variant_by_index(*v, i);
2257
2258 array[size] = element;
2259
2260 r = sd_json_variant_new_array(&nv, array, size + 1);
2261 if (r < 0)
2262 return r;
2263 }
2264
2265 json_variant_propagate_sensitive(*v, nv);
2266 return json_variant_unref_and_replace(*v, nv);
2267 }
2268
2269 _public_ int sd_json_variant_append_arrayb(sd_json_variant **v, ...) {
2270 _cleanup_(sd_json_variant_unrefp) sd_json_variant *w = NULL;
2271 va_list ap;
2272 int r;
2273
2274 va_start(ap, v);
2275 r = sd_json_buildv(&w, ap);
2276 va_end(ap);
2277 if (r < 0)
2278 return r;
2279
2280 return sd_json_variant_append_array(v, w);
2281 }
2282
2283 _public_ sd_json_variant *sd_json_variant_find(sd_json_variant *haystack, sd_json_variant *needle) {
2284 sd_json_variant *i;
2285
2286 /* Find a json object in an array. Returns NULL if not found, or if the array is not actually an array. */
2287
2288 JSON_VARIANT_ARRAY_FOREACH(i, haystack)
2289 if (sd_json_variant_equal(i, needle))
2290 return i;
2291
2292 return NULL;
2293 }
2294
2295 _public_ int sd_json_variant_append_array_nodup(sd_json_variant **v, sd_json_variant *element) {
2296 assert_return(v, -EINVAL);
2297
2298 if (sd_json_variant_find(*v, element))
2299 return 0;
2300
2301 return sd_json_variant_append_array(v, element);
2302 }
2303
2304 _public_ int sd_json_variant_strv(sd_json_variant *v, char ***ret) {
2305 char **l = NULL;
2306 bool sensitive;
2307 int r;
2308
2309 assert_return(ret, -EINVAL);
2310
2311 if (!v || sd_json_variant_is_null(v)) {
2312 l = new0(char*, 1);
2313 if (!l)
2314 return -ENOMEM;
2315
2316 *ret = l;
2317 return 0;
2318 }
2319
2320 if (!sd_json_variant_is_array(v))
2321 return -EINVAL;
2322
2323 sensitive = sd_json_variant_is_sensitive(v);
2324
2325 size_t n = sd_json_variant_elements(v);
2326 l = new(char*, n+1);
2327 if (!l)
2328 return -ENOMEM;
2329
2330 for (size_t i = 0; i < n; i++) {
2331 sd_json_variant *e;
2332
2333 assert_se(e = sd_json_variant_by_index(v, i));
2334 sensitive = sensitive || sd_json_variant_is_sensitive(e);
2335
2336 if (!sd_json_variant_is_string(e)) {
2337 l[i] = NULL;
2338 r = -EINVAL;
2339 goto fail;
2340 }
2341
2342 l[i] = strdup(sd_json_variant_string(e));
2343 if (!l[i]) {
2344 r = -ENOMEM;
2345 goto fail;
2346 }
2347 }
2348
2349 l[n] = NULL;
2350 *ret = TAKE_PTR(l);
2351
2352 return 0;
2353
2354 fail:
2355 if (sensitive)
2356 strv_free_erase(l);
2357 else
2358 strv_free(l);
2359
2360 return r;
2361 }
2362
2363 static int json_variant_copy(sd_json_variant **nv, sd_json_variant *v) {
2364 sd_json_variant_type_t t;
2365 sd_json_variant *c;
2366 JsonValue value;
2367 const void *source;
2368 size_t k;
2369
2370 assert(nv);
2371 assert(v);
2372
2373 /* Let's copy the simple types literally, and the larger types by references */
2374 t = sd_json_variant_type(v);
2375 switch (t) {
2376 case SD_JSON_VARIANT_INTEGER:
2377 k = sizeof(int64_t);
2378 value.integer = sd_json_variant_integer(v);
2379 source = &value;
2380 break;
2381
2382 case SD_JSON_VARIANT_UNSIGNED:
2383 k = sizeof(uint64_t);
2384 value.unsig = sd_json_variant_unsigned(v);
2385 source = &value;
2386 break;
2387
2388 case SD_JSON_VARIANT_REAL:
2389 k = sizeof(double);
2390 value.real = sd_json_variant_real(v);
2391 source = &value;
2392 break;
2393
2394 case SD_JSON_VARIANT_BOOLEAN:
2395 k = sizeof(bool);
2396 value.boolean = sd_json_variant_boolean(v);
2397 source = &value;
2398 break;
2399
2400 case SD_JSON_VARIANT_NULL:
2401 k = 0;
2402 source = NULL;
2403 break;
2404
2405 case SD_JSON_VARIANT_STRING:
2406 source = sd_json_variant_string(v);
2407 k = strnlen(source, INLINE_STRING_MAX + 1);
2408 if (k <= INLINE_STRING_MAX) {
2409 k++;
2410 break;
2411 }
2412
2413 _fallthrough_;
2414
2415 default:
2416 /* Everything else copy by reference */
2417
2418 c = malloc0(MAX(sizeof(sd_json_variant),
2419 offsetof(sd_json_variant, reference) + sizeof(sd_json_variant*)));
2420 if (!c)
2421 return -ENOMEM;
2422
2423 c->n_ref = 1;
2424 c->type = t;
2425 c->is_reference = true;
2426 c->reference = sd_json_variant_ref(json_variant_formalize(v));
2427
2428 *nv = c;
2429 return 0;
2430 }
2431
2432 c = malloc0(MAX(sizeof(sd_json_variant),
2433 offsetof(sd_json_variant, value) + k));
2434 if (!c)
2435 return -ENOMEM;
2436
2437 c->n_ref = 1;
2438 c->type = t;
2439
2440 memcpy_safe(&c->value, source, k);
2441
2442 json_variant_propagate_sensitive(v, c);
2443
2444 *nv = c;
2445 return 0;
2446 }
2447
2448 static bool json_single_ref(sd_json_variant *v) {
2449
2450 /* Checks whether the caller is the single owner of the object, i.e. can get away with changing it */
2451
2452 if (!json_variant_is_regular(v))
2453 return false;
2454
2455 if (v->is_embedded)
2456 return json_single_ref(v->parent);
2457
2458 assert(v->n_ref > 0);
2459 return v->n_ref == 1;
2460 }
2461
2462 static int json_variant_set_source(sd_json_variant **v, JsonSource *source, unsigned line, unsigned column) {
2463 sd_json_variant *w;
2464 int r;
2465
2466 assert(v);
2467
2468 /* Patch in source and line/column number. Tries to do this in-place if the caller is the sole
2469 * referencer of the object. If not, allocates a new object, possibly a surrogate for the original
2470 * one */
2471
2472 if (!*v)
2473 return 0;
2474
2475 if (source && line > source->max_line)
2476 source->max_line = line;
2477 if (source && column > source->max_column)
2478 source->max_column = column;
2479
2480 if (!json_variant_is_regular(*v)) {
2481
2482 if (!source && line == 0 && column == 0)
2483 return 0;
2484
2485 } else {
2486 if (json_source_equal((*v)->source, source) &&
2487 (*v)->line == line &&
2488 (*v)->column == column)
2489 return 0;
2490
2491 if (json_single_ref(*v)) { /* Sole reference? */
2492 json_source_unref((*v)->source);
2493 (*v)->source = json_source_ref(source);
2494 (*v)->line = line;
2495 (*v)->column = column;
2496 return 1;
2497 }
2498 }
2499
2500 r = json_variant_copy(&w, *v);
2501 if (r < 0)
2502 return r;
2503
2504 assert(json_variant_is_regular(w));
2505 assert(!w->is_embedded);
2506 assert(w->n_ref == 1);
2507 assert(!w->source);
2508
2509 w->source = json_source_ref(source);
2510 w->line = line;
2511 w->column = column;
2512
2513 json_variant_unref_and_replace(*v, w);
2514
2515 return 1;
2516 }
2517
2518 static void inc_lines_columns(unsigned *line, unsigned *column, const char *s, size_t n) {
2519 assert(line);
2520 assert(column);
2521 assert(s || n == 0);
2522
2523 while (n > 0) {
2524 if (*s == '\n') {
2525 (*line)++;
2526 *column = 1;
2527 } else if ((signed char) *s >= 0 && *s < 127) /* Process ASCII chars quickly */
2528 (*column)++;
2529 else {
2530 int w;
2531
2532 w = utf8_encoded_valid_unichar(s, n);
2533 if (w < 0) /* count invalid unichars as normal characters */
2534 w = 1;
2535 else if ((size_t) w > n) /* never read more than the specified number of characters */
2536 w = (int) n;
2537
2538 (*column)++;
2539
2540 s += w;
2541 n -= w;
2542 continue;
2543 }
2544
2545 s++;
2546 n--;
2547 }
2548 }
2549
2550 static int unhex_ucs2(const char *c, uint16_t *ret) {
2551 int aa, bb, cc, dd;
2552 uint16_t x;
2553
2554 assert(c);
2555 assert(ret);
2556
2557 aa = unhexchar(c[0]);
2558 if (aa < 0)
2559 return -EINVAL;
2560
2561 bb = unhexchar(c[1]);
2562 if (bb < 0)
2563 return -EINVAL;
2564
2565 cc = unhexchar(c[2]);
2566 if (cc < 0)
2567 return -EINVAL;
2568
2569 dd = unhexchar(c[3]);
2570 if (dd < 0)
2571 return -EINVAL;
2572
2573 x = ((uint16_t) aa << 12) |
2574 ((uint16_t) bb << 8) |
2575 ((uint16_t) cc << 4) |
2576 ((uint16_t) dd);
2577
2578 if (x <= 0)
2579 return -EINVAL;
2580
2581 *ret = x;
2582
2583 return 0;
2584 }
2585
2586 static int json_parse_string(const char **p, char **ret) {
2587 _cleanup_free_ char *s = NULL;
2588 size_t n = 0;
2589 const char *c;
2590
2591 assert(p);
2592 assert(*p);
2593 assert(ret);
2594
2595 c = *p;
2596
2597 if (*c != '"')
2598 return -EINVAL;
2599
2600 c++;
2601
2602 for (;;) {
2603 int len;
2604
2605 /* Check for EOF */
2606 if (*c == 0)
2607 return -EINVAL;
2608
2609 /* Check for control characters 0x00..0x1f */
2610 if (*c > 0 && *c < ' ')
2611 return -EINVAL;
2612
2613 /* Check for control character 0x7f */
2614 if (*c == 0x7f)
2615 return -EINVAL;
2616
2617 if (*c == '"') {
2618 if (!s) {
2619 s = strdup("");
2620 if (!s)
2621 return -ENOMEM;
2622 } else
2623 s[n] = 0;
2624
2625 *p = c + 1;
2626
2627 *ret = TAKE_PTR(s);
2628 return JSON_TOKEN_STRING;
2629 }
2630
2631 if (*c == '\\') {
2632 char ch = 0;
2633 c++;
2634
2635 if (*c == 0)
2636 return -EINVAL;
2637
2638 if (IN_SET(*c, '"', '\\', '/'))
2639 ch = *c;
2640 else if (*c == 'b')
2641 ch = '\b';
2642 else if (*c == 'f')
2643 ch = '\f';
2644 else if (*c == 'n')
2645 ch = '\n';
2646 else if (*c == 'r')
2647 ch = '\r';
2648 else if (*c == 't')
2649 ch = '\t';
2650 else if (*c == 'u') {
2651 char16_t x;
2652 int r;
2653
2654 r = unhex_ucs2(c + 1, &x);
2655 if (r < 0)
2656 return r;
2657
2658 c += 5;
2659
2660 if (!GREEDY_REALLOC(s, n + 5))
2661 return -ENOMEM;
2662
2663 if (!utf16_is_surrogate(x))
2664 n += utf8_encode_unichar(s + n, (char32_t) x);
2665 else if (utf16_is_trailing_surrogate(x))
2666 return -EINVAL;
2667 else {
2668 char16_t y;
2669
2670 if (c[0] != '\\' || c[1] != 'u')
2671 return -EINVAL;
2672
2673 r = unhex_ucs2(c + 2, &y);
2674 if (r < 0)
2675 return r;
2676
2677 c += 6;
2678
2679 if (!utf16_is_trailing_surrogate(y))
2680 return -EINVAL;
2681
2682 n += utf8_encode_unichar(s + n, utf16_surrogate_pair_to_unichar(x, y));
2683 }
2684
2685 continue;
2686 } else
2687 return -EINVAL;
2688
2689 if (!GREEDY_REALLOC(s, n + 2))
2690 return -ENOMEM;
2691
2692 s[n++] = ch;
2693 c++;
2694 continue;
2695 }
2696
2697 len = utf8_encoded_valid_unichar(c, SIZE_MAX);
2698 if (len < 0)
2699 return len;
2700
2701 if (!GREEDY_REALLOC(s, n + len + 1))
2702 return -ENOMEM;
2703
2704 memcpy(s + n, c, len);
2705 n += len;
2706 c += len;
2707 }
2708 }
2709
2710 static int json_parse_number(const char **p, JsonValue *ret) {
2711 bool negative = false, exponent_negative = false, is_real = false;
2712 double x = 0.0, y = 0.0, exponent = 0.0, shift = 1.0;
2713 int64_t i = 0;
2714 uint64_t u = 0;
2715 const char *c;
2716
2717 assert(p);
2718 assert(*p);
2719 assert(ret);
2720
2721 c = *p;
2722
2723 if (*c == '-') {
2724 negative = true;
2725 c++;
2726 }
2727
2728 if (*c == '0')
2729 c++;
2730 else {
2731 if (!strchr("123456789", *c) || *c == 0)
2732 return -EINVAL;
2733
2734 do {
2735 if (!is_real) {
2736 if (negative) {
2737
2738 if (i < INT64_MIN / 10) /* overflow */
2739 is_real = true;
2740 else {
2741 int64_t t = 10 * i;
2742
2743 if (t < INT64_MIN + (*c - '0')) /* overflow */
2744 is_real = true;
2745 else
2746 i = t - (*c - '0');
2747 }
2748 } else {
2749 if (u > UINT64_MAX / 10) /* overflow */
2750 is_real = true;
2751 else {
2752 uint64_t t = 10 * u;
2753
2754 if (t > UINT64_MAX - (*c - '0')) /* overflow */
2755 is_real = true;
2756 else
2757 u = t + (*c - '0');
2758 }
2759 }
2760 }
2761
2762 x = 10.0 * x + (*c - '0');
2763
2764 c++;
2765 } while (strchr(DIGITS, *c) && *c != 0);
2766 }
2767
2768 if (*c == '.') {
2769 is_real = true;
2770 c++;
2771
2772 if (!strchr(DIGITS, *c) || *c == 0)
2773 return -EINVAL;
2774
2775 do {
2776 y = 10.0 * y + (*c - '0');
2777 shift = 10.0 * shift;
2778 c++;
2779 } while (strchr(DIGITS, *c) && *c != 0);
2780 }
2781
2782 if (IN_SET(*c, 'e', 'E')) {
2783 is_real = true;
2784 c++;
2785
2786 if (*c == '-') {
2787 exponent_negative = true;
2788 c++;
2789 } else if (*c == '+')
2790 c++;
2791
2792 if (!strchr(DIGITS, *c) || *c == 0)
2793 return -EINVAL;
2794
2795 do {
2796 exponent = 10.0 * exponent + (*c - '0');
2797 c++;
2798 } while (strchr(DIGITS, *c) && *c != 0);
2799 }
2800
2801 *p = c;
2802
2803 if (is_real) {
2804 /* Clamp before casting to int — a JSON input with an absurdly large exponent could
2805 * otherwise trigger undefined behaviour in the double→int conversion. xexp10i()
2806 * itself saturates anything beyond ~10^308, so clamping at INT_MAX is harmless. */
2807 int e = exponent > (double) INT_MAX ? INT_MAX : (int) exponent;
2808 ret->real = ((negative ? -1.0 : 1.0) * (x + (y / shift))) * xexp10i(exponent_negative ? -e : e);
2809 return JSON_TOKEN_REAL;
2810 } else if (negative) {
2811 ret->integer = i;
2812 return JSON_TOKEN_INTEGER;
2813 } else {
2814 ret->unsig = u;
2815 return JSON_TOKEN_UNSIGNED;
2816 }
2817 }
2818
2819 int json_tokenize(
2820 const char **p,
2821 char **ret_string,
2822 JsonValue *ret_value,
2823 unsigned *ret_line, /* 'reterr_line' returns the line at the beginning of this token */
2824 unsigned *ret_column,
2825 void **state,
2826 unsigned *line, /* 'line' is used as a line state, it always reflect the line we are at after the token was read */
2827 unsigned *column) {
2828
2829 unsigned start_line, start_column;
2830 const char *start, *c;
2831 size_t n;
2832 int t, r;
2833
2834 enum {
2835 STATE_NULL,
2836 STATE_VALUE,
2837 STATE_VALUE_POST,
2838 };
2839
2840 assert(p);
2841 assert(*p);
2842 assert(ret_string);
2843 assert(ret_value);
2844 assert(ret_line);
2845 assert(ret_column);
2846 assert(line);
2847 assert(column);
2848 assert(state);
2849
2850 t = PTR_TO_INT(*state);
2851 if (t == STATE_NULL) {
2852 *line = 1;
2853 *column = 1;
2854 t = STATE_VALUE;
2855 }
2856
2857 /* Skip over the whitespace */
2858 n = strspn(*p, WHITESPACE);
2859 inc_lines_columns(line, column, *p, n);
2860 c = *p + n;
2861
2862 /* Remember where we started processing this token */
2863 start = c;
2864 start_line = *line;
2865 start_column = *column;
2866
2867 if (*c == 0) {
2868 *ret_string = NULL;
2869 *ret_value = JSON_VALUE_NULL;
2870 r = JSON_TOKEN_END;
2871 goto finish;
2872 }
2873
2874 switch (t) {
2875
2876 case STATE_VALUE:
2877
2878 if (*c == '{') {
2879 c++;
2880 *state = INT_TO_PTR(STATE_VALUE);
2881 r = JSON_TOKEN_OBJECT_OPEN;
2882 goto null_return;
2883
2884 } else if (*c == '}') {
2885 c++;
2886 *state = INT_TO_PTR(STATE_VALUE_POST);
2887 r = JSON_TOKEN_OBJECT_CLOSE;
2888 goto null_return;
2889
2890 } else if (*c == '[') {
2891 c++;
2892 *state = INT_TO_PTR(STATE_VALUE);
2893 r = JSON_TOKEN_ARRAY_OPEN;
2894 goto null_return;
2895
2896 } else if (*c == ']') {
2897 c++;
2898 *state = INT_TO_PTR(STATE_VALUE_POST);
2899 r = JSON_TOKEN_ARRAY_CLOSE;
2900 goto null_return;
2901
2902 } else if (*c == '"') {
2903
2904 r = json_parse_string(&c, ret_string);
2905 if (r < 0)
2906 return r;
2907
2908 *ret_value = JSON_VALUE_NULL;
2909 *state = INT_TO_PTR(STATE_VALUE_POST);
2910 goto finish;
2911
2912 } else if (strchr("-" DIGITS, *c)) {
2913
2914 r = json_parse_number(&c, ret_value);
2915 if (r < 0)
2916 return r;
2917
2918 *ret_string = NULL;
2919 *state = INT_TO_PTR(STATE_VALUE_POST);
2920 goto finish;
2921
2922 } else if (startswith(c, "true")) {
2923 *ret_string = NULL;
2924 ret_value->boolean = true;
2925 c += 4;
2926 *state = INT_TO_PTR(STATE_VALUE_POST);
2927 r = JSON_TOKEN_BOOLEAN;
2928 goto finish;
2929
2930 } else if (startswith(c, "false")) {
2931 *ret_string = NULL;
2932 ret_value->boolean = false;
2933 c += 5;
2934 *state = INT_TO_PTR(STATE_VALUE_POST);
2935 r = JSON_TOKEN_BOOLEAN;
2936 goto finish;
2937
2938 } else if (startswith(c, "null")) {
2939 *ret_string = NULL;
2940 *ret_value = JSON_VALUE_NULL;
2941 c += 4;
2942 *state = INT_TO_PTR(STATE_VALUE_POST);
2943 r = JSON_TOKEN_NULL;
2944 goto finish;
2945
2946 }
2947
2948 return -EINVAL;
2949
2950 case STATE_VALUE_POST:
2951
2952 if (*c == ':') {
2953 c++;
2954 *state = INT_TO_PTR(STATE_VALUE);
2955 r = JSON_TOKEN_COLON;
2956 goto null_return;
2957
2958 } else if (*c == ',') {
2959 c++;
2960 *state = INT_TO_PTR(STATE_VALUE);
2961 r = JSON_TOKEN_COMMA;
2962 goto null_return;
2963
2964 } else if (*c == '}') {
2965 c++;
2966 *state = INT_TO_PTR(STATE_VALUE_POST);
2967 r = JSON_TOKEN_OBJECT_CLOSE;
2968 goto null_return;
2969
2970 } else if (*c == ']') {
2971 c++;
2972 *state = INT_TO_PTR(STATE_VALUE_POST);
2973 r = JSON_TOKEN_ARRAY_CLOSE;
2974 goto null_return;
2975 }
2976
2977 return -EINVAL;
2978
2979 default:
2980 assert_not_reached();
2981 }
2982
2983 null_return:
2984 *ret_string = NULL;
2985 *ret_value = JSON_VALUE_NULL;
2986
2987 finish:
2988 inc_lines_columns(line, column, start, c - start);
2989 *p = c;
2990
2991 *ret_line = start_line;
2992 *ret_column = start_column;
2993
2994 return r;
2995 }
2996
2997 typedef enum JsonExpect {
2998 /* The following values are used by sd_json_parse() */
2999 EXPECT_TOPLEVEL,
3000 EXPECT_END,
3001 EXPECT_OBJECT_FIRST_KEY,
3002 EXPECT_OBJECT_NEXT_KEY,
3003 EXPECT_OBJECT_COLON,
3004 EXPECT_OBJECT_VALUE,
3005 EXPECT_OBJECT_COMMA,
3006 EXPECT_ARRAY_FIRST_ELEMENT,
3007 EXPECT_ARRAY_NEXT_ELEMENT,
3008 EXPECT_ARRAY_COMMA,
3009
3010 /* And these are used by sd_json_build() */
3011 EXPECT_ARRAY_ELEMENT,
3012 EXPECT_OBJECT_KEY,
3013 } JsonExpect;
3014
3015 typedef struct JsonStack {
3016 JsonExpect expect;
3017 sd_json_variant **elements;
3018 size_t n_elements;
3019 unsigned line_before;
3020 unsigned column_before;
3021 size_t n_suppress; /* When building: if > 0, suppress this many subsequent elements. If == SIZE_MAX, suppress all subsequent elements */
3022 } JsonStack;
3023
3024 static void json_stack_release(JsonStack *s) {
3025 assert(s);
3026
3027 CLEANUP_ARRAY(s->elements, s->n_elements, sd_json_variant_unref_many);
3028 }
3029
3030 static int json_parse_internal(
3031 const char **input,
3032 JsonSource *source,
3033 sd_json_parse_flags_t flags,
3034 sd_json_variant **ret,
3035 unsigned *line,
3036 unsigned *column,
3037 bool continue_end) {
3038
3039 size_t n_stack = 1;
3040 unsigned line_buffer = 0, column_buffer = 0;
3041 void *tokenizer_state = NULL;
3042 JsonStack *stack = NULL;
3043 const char *p;
3044 int r;
3045
3046 assert_return(input, -EINVAL);
3047
3048 p = *input;
3049
3050 if (!GREEDY_REALLOC(stack, n_stack))
3051 return -ENOMEM;
3052
3053 stack[0] = (JsonStack) {
3054 .expect = EXPECT_TOPLEVEL,
3055 };
3056
3057 if (!line)
3058 line = &line_buffer;
3059 if (!column)
3060 column = &column_buffer;
3061
3062 for (;;) {
3063 _cleanup_(sd_json_variant_unrefp) sd_json_variant *add = NULL;
3064 _cleanup_free_ char *string = NULL;
3065 unsigned line_token, column_token;
3066 JsonStack *current;
3067 JsonValue value;
3068 int token;
3069
3070 assert(n_stack > 0);
3071 current = stack + n_stack - 1;
3072
3073 if (continue_end && current->expect == EXPECT_END)
3074 goto done;
3075
3076 token = json_tokenize(&p, &string, &value, &line_token, &column_token, &tokenizer_state, line, column);
3077 if (token < 0) {
3078 r = token;
3079 goto finish;
3080 }
3081
3082 switch (token) {
3083
3084 case JSON_TOKEN_END:
3085 if (current->expect != EXPECT_END) {
3086 r = -EINVAL;
3087 goto finish;
3088 }
3089
3090 assert(current->n_elements == 1);
3091 assert(n_stack == 1);
3092 goto done;
3093
3094 case JSON_TOKEN_COLON:
3095
3096 if (current->expect != EXPECT_OBJECT_COLON) {
3097 r = -EINVAL;
3098 goto finish;
3099 }
3100
3101 current->expect = EXPECT_OBJECT_VALUE;
3102 break;
3103
3104 case JSON_TOKEN_COMMA:
3105
3106 if (current->expect == EXPECT_OBJECT_COMMA)
3107 current->expect = EXPECT_OBJECT_NEXT_KEY;
3108 else if (current->expect == EXPECT_ARRAY_COMMA)
3109 current->expect = EXPECT_ARRAY_NEXT_ELEMENT;
3110 else {
3111 r = -EINVAL;
3112 goto finish;
3113 }
3114
3115 break;
3116
3117 case JSON_TOKEN_OBJECT_OPEN:
3118 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
3119 r = -EINVAL;
3120 goto finish;
3121 }
3122
3123 if (n_stack == 1 && FLAGS_SET(flags, SD_JSON_PARSE_MUST_BE_ARRAY) && !FLAGS_SET(flags, SD_JSON_PARSE_MUST_BE_OBJECT)) {
3124 r = -EINVAL;
3125 goto finish;
3126 }
3127
3128 /* n_stack includes the top level entry, hence > instead of >= */
3129 if (n_stack > DEPTH_MAX) {
3130 r = -ELNRNG;
3131 goto finish;
3132 }
3133
3134 if (!GREEDY_REALLOC(stack, n_stack+1)) {
3135 r = -ENOMEM;
3136 goto finish;
3137 }
3138 current = stack + n_stack - 1;
3139
3140 /* Prepare the expect for when we return from the child */
3141 if (current->expect == EXPECT_TOPLEVEL)
3142 current->expect = EXPECT_END;
3143 else if (current->expect == EXPECT_OBJECT_VALUE)
3144 current->expect = EXPECT_OBJECT_COMMA;
3145 else {
3146 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3147 current->expect = EXPECT_ARRAY_COMMA;
3148 }
3149
3150 stack[n_stack++] = (JsonStack) {
3151 .expect = EXPECT_OBJECT_FIRST_KEY,
3152 .line_before = line_token,
3153 .column_before = column_token,
3154 };
3155
3156 current = stack + n_stack - 1;
3157 break;
3158
3159 case JSON_TOKEN_OBJECT_CLOSE:
3160 if (!IN_SET(current->expect, EXPECT_OBJECT_FIRST_KEY, EXPECT_OBJECT_COMMA)) {
3161 r = -EINVAL;
3162 goto finish;
3163 }
3164
3165 assert(n_stack > 1);
3166
3167 r = sd_json_variant_new_object(&add, current->elements, current->n_elements);
3168 if (r < 0)
3169 goto finish;
3170
3171 line_token = current->line_before;
3172 column_token = current->column_before;
3173
3174 json_stack_release(current);
3175 n_stack--, current--;
3176
3177 break;
3178
3179 case JSON_TOKEN_ARRAY_OPEN:
3180 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
3181 r = -EINVAL;
3182 goto finish;
3183 }
3184
3185 if (n_stack == 1 && !FLAGS_SET(flags, SD_JSON_PARSE_MUST_BE_ARRAY) && FLAGS_SET(flags, SD_JSON_PARSE_MUST_BE_OBJECT)) {
3186 r = -EINVAL;
3187 goto finish;
3188 }
3189
3190 /* n_stack includes the top level entry, hence > instead of >= */
3191 if (n_stack > DEPTH_MAX) {
3192 r = -ELNRNG;
3193 goto finish;
3194 }
3195
3196 if (!GREEDY_REALLOC(stack, n_stack+1)) {
3197 r = -ENOMEM;
3198 goto finish;
3199 }
3200 current = stack + n_stack - 1;
3201
3202 /* Prepare the expect for when we return from the child */
3203 if (current->expect == EXPECT_TOPLEVEL)
3204 current->expect = EXPECT_END;
3205 else if (current->expect == EXPECT_OBJECT_VALUE)
3206 current->expect = EXPECT_OBJECT_COMMA;
3207 else {
3208 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3209 current->expect = EXPECT_ARRAY_COMMA;
3210 }
3211
3212 stack[n_stack++] = (JsonStack) {
3213 .expect = EXPECT_ARRAY_FIRST_ELEMENT,
3214 .line_before = line_token,
3215 .column_before = column_token,
3216 };
3217
3218 break;
3219
3220 case JSON_TOKEN_ARRAY_CLOSE:
3221 if (!IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_COMMA)) {
3222 r = -EINVAL;
3223 goto finish;
3224 }
3225
3226 assert(n_stack > 1);
3227
3228 r = sd_json_variant_new_array(&add, current->elements, current->n_elements);
3229 if (r < 0)
3230 goto finish;
3231
3232 line_token = current->line_before;
3233 column_token = current->column_before;
3234
3235 json_stack_release(current);
3236 n_stack--, current--;
3237 break;
3238
3239 case JSON_TOKEN_STRING:
3240 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)) {
3241 r = -EINVAL;
3242 goto finish;
3243 }
3244
3245 if (n_stack == 1 && (flags & (SD_JSON_PARSE_MUST_BE_ARRAY|SD_JSON_PARSE_MUST_BE_OBJECT)) != 0) {
3246 r = -EINVAL;
3247 goto finish;
3248 }
3249
3250 r = sd_json_variant_new_string(&add, string);
3251 if (r < 0)
3252 goto finish;
3253
3254 if (current->expect == EXPECT_TOPLEVEL)
3255 current->expect = EXPECT_END;
3256 else if (IN_SET(current->expect, EXPECT_OBJECT_FIRST_KEY, EXPECT_OBJECT_NEXT_KEY))
3257 current->expect = EXPECT_OBJECT_COLON;
3258 else if (current->expect == EXPECT_OBJECT_VALUE)
3259 current->expect = EXPECT_OBJECT_COMMA;
3260 else {
3261 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3262 current->expect = EXPECT_ARRAY_COMMA;
3263 }
3264
3265 break;
3266
3267 case JSON_TOKEN_REAL:
3268 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
3269 r = -EINVAL;
3270 goto finish;
3271 }
3272
3273 if (n_stack == 1 && (flags & (SD_JSON_PARSE_MUST_BE_ARRAY|SD_JSON_PARSE_MUST_BE_OBJECT)) != 0) {
3274 r = -EINVAL;
3275 goto finish;
3276 }
3277
3278 r = sd_json_variant_new_real(&add, value.real);
3279 if (r < 0)
3280 goto finish;
3281
3282 if (current->expect == EXPECT_TOPLEVEL)
3283 current->expect = EXPECT_END;
3284 else if (current->expect == EXPECT_OBJECT_VALUE)
3285 current->expect = EXPECT_OBJECT_COMMA;
3286 else {
3287 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3288 current->expect = EXPECT_ARRAY_COMMA;
3289 }
3290
3291 break;
3292
3293 case JSON_TOKEN_INTEGER:
3294 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
3295 r = -EINVAL;
3296 goto finish;
3297 }
3298
3299 if (n_stack == 1 && (flags & (SD_JSON_PARSE_MUST_BE_ARRAY|SD_JSON_PARSE_MUST_BE_OBJECT)) != 0) {
3300 r = -EINVAL;
3301 goto finish;
3302 }
3303
3304 r = sd_json_variant_new_integer(&add, value.integer);
3305 if (r < 0)
3306 goto finish;
3307
3308 if (current->expect == EXPECT_TOPLEVEL)
3309 current->expect = EXPECT_END;
3310 else if (current->expect == EXPECT_OBJECT_VALUE)
3311 current->expect = EXPECT_OBJECT_COMMA;
3312 else {
3313 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3314 current->expect = EXPECT_ARRAY_COMMA;
3315 }
3316
3317 break;
3318
3319 case JSON_TOKEN_UNSIGNED:
3320 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
3321 r = -EINVAL;
3322 goto finish;
3323 }
3324
3325 if (n_stack == 1 && (flags & (SD_JSON_PARSE_MUST_BE_ARRAY|SD_JSON_PARSE_MUST_BE_OBJECT)) != 0) {
3326 r = -EINVAL;
3327 goto finish;
3328 }
3329
3330 r = sd_json_variant_new_unsigned(&add, value.unsig);
3331 if (r < 0)
3332 goto finish;
3333
3334 if (current->expect == EXPECT_TOPLEVEL)
3335 current->expect = EXPECT_END;
3336 else if (current->expect == EXPECT_OBJECT_VALUE)
3337 current->expect = EXPECT_OBJECT_COMMA;
3338 else {
3339 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3340 current->expect = EXPECT_ARRAY_COMMA;
3341 }
3342
3343 break;
3344
3345 case JSON_TOKEN_BOOLEAN:
3346 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
3347 r = -EINVAL;
3348 goto finish;
3349 }
3350
3351 if (n_stack == 1 && (flags & (SD_JSON_PARSE_MUST_BE_ARRAY|SD_JSON_PARSE_MUST_BE_OBJECT)) != 0) {
3352 r = -EINVAL;
3353 goto finish;
3354 }
3355
3356 r = sd_json_variant_new_boolean(&add, value.boolean);
3357 if (r < 0)
3358 goto finish;
3359
3360 if (current->expect == EXPECT_TOPLEVEL)
3361 current->expect = EXPECT_END;
3362 else if (current->expect == EXPECT_OBJECT_VALUE)
3363 current->expect = EXPECT_OBJECT_COMMA;
3364 else {
3365 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3366 current->expect = EXPECT_ARRAY_COMMA;
3367 }
3368
3369 break;
3370
3371 case JSON_TOKEN_NULL:
3372 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT)) {
3373 r = -EINVAL;
3374 goto finish;
3375 }
3376
3377 if (n_stack == 1 && (flags & (SD_JSON_PARSE_MUST_BE_ARRAY|SD_JSON_PARSE_MUST_BE_OBJECT)) != 0) {
3378 r = -EINVAL;
3379 goto finish;
3380 }
3381
3382 r = sd_json_variant_new_null(&add);
3383 if (r < 0)
3384 goto finish;
3385
3386 if (current->expect == EXPECT_TOPLEVEL)
3387 current->expect = EXPECT_END;
3388 else if (current->expect == EXPECT_OBJECT_VALUE)
3389 current->expect = EXPECT_OBJECT_COMMA;
3390 else {
3391 assert(IN_SET(current->expect, EXPECT_ARRAY_FIRST_ELEMENT, EXPECT_ARRAY_NEXT_ELEMENT));
3392 current->expect = EXPECT_ARRAY_COMMA;
3393 }
3394
3395 break;
3396
3397 default:
3398 assert_not_reached();
3399 }
3400
3401 if (add) {
3402 /* If we are asked to make this parsed object sensitive, then let's apply this
3403 * immediately after allocating each variant, so that when we abort half-way
3404 * everything we already allocated that is then freed is correctly marked. */
3405 if (FLAGS_SET(flags, SD_JSON_PARSE_SENSITIVE))
3406 sd_json_variant_sensitive(add);
3407
3408 (void) json_variant_set_source(&add, source, line_token, column_token);
3409
3410 if (!GREEDY_REALLOC(current->elements, current->n_elements + 1)) {
3411 r = -ENOMEM;
3412 goto finish;
3413 }
3414
3415 current->elements[current->n_elements++] = TAKE_PTR(add);
3416 }
3417 }
3418
3419 done:
3420 assert(n_stack == 1);
3421 assert(stack[0].n_elements == 1);
3422
3423 if (ret)
3424 *ret = sd_json_variant_ref(stack[0].elements[0]);
3425 *input = p;
3426 r = 0;
3427
3428 finish:
3429 FOREACH_ARRAY(i, stack, n_stack)
3430 json_stack_release(i);
3431
3432 free(stack);
3433
3434 return r;
3435 }
3436
3437 _public_ int sd_json_parse_with_source(
3438 const char *string,
3439 const char *source,
3440 sd_json_parse_flags_t flags,
3441 sd_json_variant **ret,
3442 unsigned *reterr_line,
3443 unsigned *reterr_column) {
3444
3445 _cleanup_(json_source_unrefp) JsonSource *s = NULL;
3446
3447 if (isempty(string))
3448 return -ENODATA;
3449
3450 if (source) {
3451 s = json_source_new(source);
3452 if (!s)
3453 return -ENOMEM;
3454 }
3455
3456 return json_parse_internal(&string, s, flags, ret, reterr_line, reterr_column, false);
3457 }
3458
3459 _public_ int sd_json_parse_with_source_continue(
3460 const char **p,
3461 const char *source,
3462 sd_json_parse_flags_t flags,
3463 sd_json_variant **ret,
3464 unsigned *reterr_line,
3465 unsigned *reterr_column) {
3466
3467 _cleanup_(json_source_unrefp) JsonSource *s = NULL;
3468
3469 if (source) {
3470 s = json_source_new(source);
3471 if (!s)
3472 return -ENOMEM;
3473 }
3474
3475 return json_parse_internal(p, s, flags, ret, reterr_line, reterr_column, true);
3476 }
3477
3478 _public_ int sd_json_parse(
3479 const char *string,
3480 sd_json_parse_flags_t flags,
3481 sd_json_variant **ret,
3482 unsigned *reterr_line,
3483 unsigned *reterr_column) {
3484
3485 return sd_json_parse_with_source(string, NULL, flags, ret, reterr_line, reterr_column);
3486 }
3487
3488 _public_ int sd_json_parse_continue(
3489 const char **p,
3490 sd_json_parse_flags_t flags,
3491 sd_json_variant **ret,
3492 unsigned *reterr_line,
3493 unsigned *reterr_column) {
3494
3495 return sd_json_parse_with_source_continue(p, NULL, flags, ret, reterr_line, reterr_column);
3496 }
3497
3498 _public_ int sd_json_parse_file_at(
3499 FILE *f,
3500 int dir_fd,
3501 const char *path,
3502 sd_json_parse_flags_t flags,
3503 sd_json_variant **ret,
3504 unsigned *reterr_line,
3505 unsigned *reterr_column) {
3506
3507 _cleanup_free_ char *text = NULL;
3508 int r;
3509
3510 if (f) {
3511 if (FLAGS_SET(flags, SD_JSON_PARSE_SEEK0) && fseek(f, /* offset= */ 0, SEEK_SET) < 0)
3512 return -errno;
3513
3514 r = read_full_stream(f, &text, NULL);
3515 } else
3516 r = read_full_file_full(dir_fd, path, UINT64_MAX, SIZE_MAX, 0, NULL, &text, NULL);
3517 if (r < 0)
3518 return r;
3519
3520 return sd_json_parse_with_source(text, path, flags, ret, reterr_line, reterr_column);
3521 }
3522
3523 _public_ int sd_json_parse_file(
3524 FILE *f,
3525 const char *path,
3526 sd_json_parse_flags_t flags,
3527 sd_json_variant **ret,
3528 unsigned *reterr_line,
3529 unsigned *reterr_column) {
3530
3531 return sd_json_parse_file_at(f, AT_FDCWD, path, flags, ret, reterr_line, reterr_column);
3532 }
3533
3534 _public_ int sd_json_parse_fd(
3535 const char *path,
3536 int fd,
3537 sd_json_parse_flags_t flags,
3538 sd_json_variant **ret,
3539 unsigned *reterr_line,
3540 unsigned *reterr_column) {
3541
3542 int r;
3543
3544 assert_return(fd >= 0, -EBADF);
3545
3546 _cleanup_close_ int our_fd = -EBADF;
3547 if (FLAGS_SET(flags, SD_JSON_PARSE_REOPEN_FD)) {
3548 assert_return(!FLAGS_SET(flags, SD_JSON_PARSE_DONATE_FD), -EINVAL);
3549
3550 our_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC);
3551 if (our_fd < 0)
3552 return our_fd;
3553
3554 /* If we reopened the thing the file offset will be at the beginning anyway */
3555 flags &= ~SD_JSON_PARSE_SEEK0;
3556 } else if (FLAGS_SET(flags, SD_JSON_PARSE_DONATE_FD))
3557 our_fd = fd;
3558 else {
3559 our_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
3560 if (our_fd < 0)
3561 return -errno;
3562 }
3563
3564 _cleanup_fclose_ FILE *f = NULL;
3565 r = take_fdopen_unlocked(&our_fd, "r", &f);
3566 if (r < 0)
3567 return r;
3568
3569 return sd_json_parse_file(f, path, flags, ret, reterr_line, reterr_column);
3570 }
3571
3572 char *json_underscorify(char *p) {
3573 if (!p)
3574 return NULL;
3575
3576 /* Replaces "-", "+" by "_", to deal with the usual enum naming rules we have. */
3577
3578 for (char *q = p; *q; q++)
3579 *q = IN_SET(*q, '_', '-', '+') ? '_' : *q;
3580
3581 return p;
3582 }
3583
3584 char *json_dashify(char *p) {
3585 if (!p)
3586 return NULL;
3587
3588 /* Replaces "-", "+" by "-", to (somewhat) undo what json_underscorify() does */
3589
3590 for (char *q = p; *q; q++)
3591 *q = IN_SET(*q, '_', '-', '+') ? '-' : *q;
3592
3593 return p;
3594 }
3595
3596 _public_ int sd_json_buildv(sd_json_variant **ret, va_list ap) {
3597 JsonStack *stack = NULL;
3598 size_t n_stack = 1;
3599 const char *name = NULL;
3600 int r;
3601
3602 assert_return(ret, -EINVAL);
3603
3604 if (!GREEDY_REALLOC(stack, n_stack))
3605 return -ENOMEM;
3606
3607 stack[0] = (JsonStack) {
3608 .expect = EXPECT_TOPLEVEL,
3609 };
3610
3611 for (;;) {
3612 _cleanup_(sd_json_variant_unrefp) sd_json_variant *add = NULL, *add_more = NULL;
3613 size_t n_subtract = 0; /* how much to subtract from current->n_suppress, i.e. how many elements would
3614 * have been added to the current variant */
3615 JsonStack *current;
3616 int command;
3617
3618 assert(n_stack > 0);
3619 current = stack + n_stack - 1;
3620
3621 if (current->expect == EXPECT_END)
3622 goto done;
3623
3624 command = va_arg(ap, int);
3625
3626 switch (command) {
3627
3628 case _SD_JSON_BUILD_STRING:
3629 case _JSON_BUILD_STRING_UNDERSCORIFY: {
3630 const char *p;
3631
3632 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3633 r = -EINVAL;
3634 goto finish;
3635 }
3636
3637 p = va_arg(ap, const char *);
3638
3639 if (current->n_suppress == 0) {
3640 _cleanup_free_ char *c = NULL;
3641
3642 if (command == _JSON_BUILD_STRING_UNDERSCORIFY && p) {
3643 c = strdup(p);
3644 if (!c) {
3645 r = -ENOMEM;
3646 goto finish;
3647 }
3648
3649 p = json_underscorify(c);
3650 }
3651
3652 r = sd_json_variant_new_string(&add, p);
3653 if (r < 0)
3654 goto finish;
3655 }
3656
3657 n_subtract = 1;
3658
3659 if (current->expect == EXPECT_TOPLEVEL)
3660 current->expect = EXPECT_END;
3661 else if (current->expect == EXPECT_OBJECT_VALUE)
3662 current->expect = EXPECT_OBJECT_KEY;
3663 else
3664 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3665
3666 break;
3667 }
3668
3669 case _SD_JSON_BUILD_INTEGER: {
3670 int64_t j;
3671
3672 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3673 r = -EINVAL;
3674 goto finish;
3675 }
3676
3677 j = va_arg(ap, int64_t);
3678
3679 if (current->n_suppress == 0) {
3680 r = sd_json_variant_new_integer(&add, j);
3681 if (r < 0)
3682 goto finish;
3683 }
3684
3685 n_subtract = 1;
3686
3687 if (current->expect == EXPECT_TOPLEVEL)
3688 current->expect = EXPECT_END;
3689 else if (current->expect == EXPECT_OBJECT_VALUE)
3690 current->expect = EXPECT_OBJECT_KEY;
3691 else
3692 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3693
3694 break;
3695 }
3696
3697 case _SD_JSON_BUILD_UNSIGNED: {
3698 uint64_t j;
3699
3700 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3701 r = -EINVAL;
3702 goto finish;
3703 }
3704
3705 j = va_arg(ap, uint64_t);
3706
3707 if (current->n_suppress == 0) {
3708 r = sd_json_variant_new_unsigned(&add, j);
3709 if (r < 0)
3710 goto finish;
3711 }
3712
3713 n_subtract = 1;
3714
3715 if (current->expect == EXPECT_TOPLEVEL)
3716 current->expect = EXPECT_END;
3717 else if (current->expect == EXPECT_OBJECT_VALUE)
3718 current->expect = EXPECT_OBJECT_KEY;
3719 else
3720 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3721
3722 break;
3723 }
3724
3725 case _SD_JSON_BUILD_REAL: {
3726 double d;
3727
3728 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3729 r = -EINVAL;
3730 goto finish;
3731 }
3732
3733 d = va_arg(ap, double);
3734
3735 if (current->n_suppress == 0) {
3736 r = sd_json_variant_new_real(&add, d);
3737 if (r < 0)
3738 goto finish;
3739 }
3740
3741 n_subtract = 1;
3742
3743 if (current->expect == EXPECT_TOPLEVEL)
3744 current->expect = EXPECT_END;
3745 else if (current->expect == EXPECT_OBJECT_VALUE)
3746 current->expect = EXPECT_OBJECT_KEY;
3747 else
3748 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3749
3750 break;
3751 }
3752
3753 case _SD_JSON_BUILD_BOOLEAN: {
3754 bool b;
3755
3756 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3757 r = -EINVAL;
3758 goto finish;
3759 }
3760
3761 b = va_arg(ap, int);
3762
3763 if (current->n_suppress == 0) {
3764 r = sd_json_variant_new_boolean(&add, b);
3765 if (r < 0)
3766 goto finish;
3767 }
3768
3769 n_subtract = 1;
3770
3771 if (current->expect == EXPECT_TOPLEVEL)
3772 current->expect = EXPECT_END;
3773 else if (current->expect == EXPECT_OBJECT_VALUE)
3774 current->expect = EXPECT_OBJECT_KEY;
3775 else
3776 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3777
3778 break;
3779 }
3780
3781 case _SD_JSON_BUILD_NULL:
3782
3783 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3784 r = -EINVAL;
3785 goto finish;
3786 }
3787
3788 if (current->n_suppress == 0) {
3789 r = sd_json_variant_new_null(&add);
3790 if (r < 0)
3791 goto finish;
3792 }
3793
3794 n_subtract = 1;
3795
3796 if (current->expect == EXPECT_TOPLEVEL)
3797 current->expect = EXPECT_END;
3798 else if (current->expect == EXPECT_OBJECT_VALUE)
3799 current->expect = EXPECT_OBJECT_KEY;
3800 else
3801 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3802
3803 break;
3804
3805 case _SD_JSON_BUILD_VARIANT:
3806
3807 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3808 r = -EINVAL;
3809 goto finish;
3810 }
3811
3812 /* Note that we don't care for current->n_suppress here, after all the variant is already
3813 * allocated anyway... */
3814 add = va_arg(ap, sd_json_variant*);
3815 if (!add)
3816 add = JSON_VARIANT_MAGIC_NULL;
3817 else
3818 sd_json_variant_ref(add);
3819
3820 n_subtract = 1;
3821
3822 if (current->expect == EXPECT_TOPLEVEL)
3823 current->expect = EXPECT_END;
3824 else if (current->expect == EXPECT_OBJECT_VALUE)
3825 current->expect = EXPECT_OBJECT_KEY;
3826 else
3827 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3828
3829 break;
3830
3831 case _SD_JSON_BUILD_VARIANT_ARRAY: {
3832 sd_json_variant **array;
3833 size_t n;
3834
3835 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3836 r = -EINVAL;
3837 goto finish;
3838 }
3839
3840 array = va_arg(ap, sd_json_variant**);
3841 n = va_arg(ap, size_t);
3842
3843 if (current->n_suppress == 0) {
3844 r = sd_json_variant_new_array(&add, array, n);
3845 if (r < 0)
3846 goto finish;
3847 }
3848
3849 n_subtract = 1;
3850
3851 if (current->expect == EXPECT_TOPLEVEL)
3852 current->expect = EXPECT_END;
3853 else if (current->expect == EXPECT_OBJECT_VALUE)
3854 current->expect = EXPECT_OBJECT_KEY;
3855 else
3856 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3857
3858 break;
3859 }
3860
3861 case _SD_JSON_BUILD_LITERAL: {
3862 const char *l;
3863
3864 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3865 r = -EINVAL;
3866 goto finish;
3867 }
3868
3869 l = va_arg(ap, const char *);
3870
3871 if (l) {
3872 /* Note that we don't care for current->n_suppress here, we should generate parsing
3873 * errors even in suppressed object properties */
3874
3875 r = sd_json_parse(l, 0, &add, NULL, NULL);
3876 if (r < 0)
3877 goto finish;
3878 } else
3879 add = JSON_VARIANT_MAGIC_NULL;
3880
3881 n_subtract = 1;
3882
3883 if (current->expect == EXPECT_TOPLEVEL)
3884 current->expect = EXPECT_END;
3885 else if (current->expect == EXPECT_OBJECT_VALUE)
3886 current->expect = EXPECT_OBJECT_KEY;
3887 else
3888 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3889
3890 break;
3891 }
3892
3893 case _SD_JSON_BUILD_ARRAY_BEGIN:
3894
3895 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3896 r = -EINVAL;
3897 goto finish;
3898 }
3899
3900 if (!GREEDY_REALLOC(stack, n_stack+1)) {
3901 r = -ENOMEM;
3902 goto finish;
3903 }
3904 current = stack + n_stack - 1;
3905
3906 if (current->expect == EXPECT_TOPLEVEL)
3907 current->expect = EXPECT_END;
3908 else if (current->expect == EXPECT_OBJECT_VALUE)
3909 current->expect = EXPECT_OBJECT_KEY;
3910 else
3911 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3912
3913 stack[n_stack++] = (JsonStack) {
3914 .expect = EXPECT_ARRAY_ELEMENT,
3915 .n_suppress = current->n_suppress != 0 ? SIZE_MAX : 0, /* if we shall suppress the
3916 * new array, then we should
3917 * also suppress all array
3918 * members */
3919 };
3920
3921 break;
3922
3923 case _SD_JSON_BUILD_ARRAY_END:
3924 if (current->expect != EXPECT_ARRAY_ELEMENT) {
3925 r = -EINVAL;
3926 goto finish;
3927 }
3928
3929 assert(n_stack > 1);
3930
3931 if (current->n_suppress == 0) {
3932 r = sd_json_variant_new_array(&add, current->elements, current->n_elements);
3933 if (r < 0)
3934 goto finish;
3935 }
3936
3937 n_subtract = 1;
3938
3939 json_stack_release(current);
3940 n_stack--, current--;
3941
3942 break;
3943
3944 case _SD_JSON_BUILD_STRV: {
3945 char **l;
3946
3947 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3948 r = -EINVAL;
3949 goto finish;
3950 }
3951
3952 l = va_arg(ap, char **);
3953
3954 if (current->n_suppress == 0) {
3955 r = sd_json_variant_new_array_strv(&add, l);
3956 if (r < 0)
3957 goto finish;
3958 }
3959
3960 n_subtract = 1;
3961
3962 if (current->expect == EXPECT_TOPLEVEL)
3963 current->expect = EXPECT_END;
3964 else if (current->expect == EXPECT_OBJECT_VALUE)
3965 current->expect = EXPECT_OBJECT_KEY;
3966 else
3967 assert(current->expect == EXPECT_ARRAY_ELEMENT);
3968
3969 break;
3970 }
3971
3972 case _JSON_BUILD_STRV_ENV_PAIR: {
3973 char **l;
3974
3975 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
3976 r = -EINVAL;
3977 goto finish;
3978 }
3979
3980 l = va_arg(ap, char **);
3981
3982 if (current->n_suppress == 0) {
3983 _cleanup_strv_free_ char **el = NULL;
3984
3985 r = strv_env_get_merged(l, &el);
3986 if (r < 0)
3987 goto finish;
3988
3989 r = sd_json_variant_new_array_strv(&add, el);
3990 if (r < 0)
3991 goto finish;
3992 }
3993
3994 n_subtract = 1;
3995
3996 if (current->expect == EXPECT_TOPLEVEL)
3997 current->expect = EXPECT_END;
3998 else if (current->expect == EXPECT_OBJECT_VALUE)
3999 current->expect = EXPECT_OBJECT_KEY;
4000 else
4001 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4002
4003 break;
4004 }
4005
4006 case _SD_JSON_BUILD_BASE64:
4007 case _SD_JSON_BUILD_BASE32HEX:
4008 case _SD_JSON_BUILD_HEX:
4009 case _SD_JSON_BUILD_OCTESCAPE: {
4010 const void *p;
4011 size_t n;
4012
4013 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4014 r = -EINVAL;
4015 goto finish;
4016 }
4017
4018 p = va_arg(ap, const void *);
4019 n = va_arg(ap, size_t);
4020
4021 if (current->n_suppress == 0) {
4022 r = command == _SD_JSON_BUILD_BASE64 ? sd_json_variant_new_base64(&add, p, n) :
4023 command == _SD_JSON_BUILD_BASE32HEX ? sd_json_variant_new_base32hex(&add, p, n) :
4024 command == _SD_JSON_BUILD_HEX ? sd_json_variant_new_hex(&add, p, n) :
4025 sd_json_variant_new_octescape(&add, p, n);
4026 if (r < 0)
4027 goto finish;
4028 }
4029
4030 n_subtract = 1;
4031
4032 if (current->expect == EXPECT_TOPLEVEL)
4033 current->expect = EXPECT_END;
4034 else if (current->expect == EXPECT_OBJECT_VALUE)
4035 current->expect = EXPECT_OBJECT_KEY;
4036 else
4037 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4038
4039 break;
4040 }
4041
4042 case _JSON_BUILD_IOVEC_BASE64:
4043 case _JSON_BUILD_IOVEC_HEX: {
4044 const struct iovec *iov;
4045
4046 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4047 r = -EINVAL;
4048 goto finish;
4049 }
4050
4051 iov = va_arg(ap, const struct iovec*);
4052
4053 if (current->n_suppress == 0) {
4054 if (iov)
4055 r = command == _JSON_BUILD_IOVEC_BASE64 ? sd_json_variant_new_base64(&add, iov->iov_base, iov->iov_len) :
4056 sd_json_variant_new_hex(&add, iov->iov_base, iov->iov_len);
4057 else
4058 r = sd_json_variant_new_string(&add, "");
4059 if (r < 0)
4060 goto finish;
4061 }
4062
4063 n_subtract = 1;
4064
4065 if (current->expect == EXPECT_TOPLEVEL)
4066 current->expect = EXPECT_END;
4067 else if (current->expect == EXPECT_OBJECT_VALUE)
4068 current->expect = EXPECT_OBJECT_KEY;
4069 else
4070 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4071
4072 break;
4073 }
4074
4075 case _SD_JSON_BUILD_ID128:
4076 case _SD_JSON_BUILD_UUID: {
4077 const sd_id128_t *id;
4078
4079 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4080 r = -EINVAL;
4081 goto finish;
4082 }
4083
4084 assert_se(id = va_arg(ap, sd_id128_t*));
4085
4086 if (current->n_suppress == 0) {
4087 r = command == _SD_JSON_BUILD_ID128 ?
4088 sd_json_variant_new_id128(&add, *id) :
4089 sd_json_variant_new_uuid(&add, *id);
4090 if (r < 0)
4091 goto finish;
4092 }
4093
4094 n_subtract = 1;
4095
4096 if (current->expect == EXPECT_TOPLEVEL)
4097 current->expect = EXPECT_END;
4098 else if (current->expect == EXPECT_OBJECT_VALUE)
4099 current->expect = EXPECT_OBJECT_KEY;
4100 else
4101 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4102
4103 break;
4104 }
4105
4106 case _SD_JSON_BUILD_BYTE_ARRAY: {
4107 const void *array;
4108 size_t n;
4109
4110 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4111 r = -EINVAL;
4112 goto finish;
4113 }
4114
4115 array = va_arg(ap, const void*);
4116 n = va_arg(ap, size_t);
4117
4118 if (current->n_suppress == 0) {
4119 r = sd_json_variant_new_array_bytes(&add, array, n);
4120 if (r < 0)
4121 goto finish;
4122 }
4123
4124 n_subtract = 1;
4125
4126 if (current->expect == EXPECT_TOPLEVEL)
4127 current->expect = EXPECT_END;
4128 else if (current->expect == EXPECT_OBJECT_VALUE)
4129 current->expect = EXPECT_OBJECT_KEY;
4130 else
4131 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4132
4133 break;
4134 }
4135
4136 case _JSON_BUILD_HW_ADDR: {
4137 const struct hw_addr_data *hw_addr;
4138
4139 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4140 r = -EINVAL;
4141 goto finish;
4142 }
4143
4144 assert_se(hw_addr = va_arg(ap, struct hw_addr_data*));
4145
4146 if (current->n_suppress == 0) {
4147 r = sd_json_variant_new_array_bytes(&add, hw_addr->bytes, hw_addr->length);
4148 if (r < 0)
4149 goto finish;
4150 }
4151
4152 n_subtract = 1;
4153
4154 if (current->expect == EXPECT_TOPLEVEL)
4155 current->expect = EXPECT_END;
4156 else if (current->expect == EXPECT_OBJECT_VALUE)
4157 current->expect = EXPECT_OBJECT_KEY;
4158 else
4159 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4160
4161 break;
4162 }
4163
4164 case _JSON_BUILD_STRING_SET: {
4165 Set *set;
4166
4167 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4168 r = -EINVAL;
4169 goto finish;
4170 }
4171
4172 set = va_arg(ap, Set*);
4173
4174 if (current->n_suppress == 0) {
4175 _cleanup_free_ char **sorted = NULL;
4176
4177 r = set_dump_sorted(set, (void ***) &sorted, NULL);
4178 if (r < 0)
4179 goto finish;
4180
4181 r = sd_json_variant_new_array_strv(&add, sorted);
4182 if (r < 0)
4183 goto finish;
4184 }
4185
4186 n_subtract = 1;
4187
4188 if (current->expect == EXPECT_TOPLEVEL)
4189 current->expect = EXPECT_END;
4190 else if (current->expect == EXPECT_OBJECT_VALUE)
4191 current->expect = EXPECT_OBJECT_KEY;
4192 else
4193 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4194
4195 break;
4196 }
4197
4198 case _JSON_BUILD_STRING_ORDERED_SET: {
4199 OrderedSet *set;
4200
4201 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4202 r = -EINVAL;
4203 goto finish;
4204 }
4205
4206 set = va_arg(ap, OrderedSet*);
4207
4208 if (current->n_suppress == 0) {
4209 _cleanup_free_ char **sv = NULL;
4210
4211 sv = ordered_set_get_strv(set);
4212 if (!sv) {
4213 r = -ENOMEM;
4214 goto finish;
4215 }
4216
4217 r = sd_json_variant_new_array_strv(&add, sv);
4218 if (r < 0)
4219 goto finish;
4220 }
4221
4222 n_subtract = 1;
4223
4224 if (current->expect == EXPECT_TOPLEVEL)
4225 current->expect = EXPECT_END;
4226 else if (current->expect == EXPECT_OBJECT_VALUE)
4227 current->expect = EXPECT_OBJECT_KEY;
4228 else
4229 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4230
4231 break;
4232 }
4233
4234 case _JSON_BUILD_DUAL_TIMESTAMP: {
4235 dual_timestamp *ts;
4236
4237 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4238 r = -EINVAL;
4239 goto finish;
4240 }
4241
4242 ts = va_arg(ap, dual_timestamp*);
4243
4244 if (current->n_suppress == 0) {
4245 if (dual_timestamp_is_set(ts)) {
4246 r = sd_json_buildo(
4247 &add,
4248 SD_JSON_BUILD_PAIR_UNSIGNED("realtime", ts->realtime),
4249 SD_JSON_BUILD_PAIR_UNSIGNED("monotonic", ts->monotonic));
4250 if (r < 0)
4251 goto finish;
4252 } else
4253 add = JSON_VARIANT_MAGIC_NULL;
4254 }
4255
4256 n_subtract = 1;
4257
4258 if (current->expect == EXPECT_TOPLEVEL)
4259 current->expect = EXPECT_END;
4260 else if (current->expect == EXPECT_OBJECT_VALUE)
4261 current->expect = EXPECT_OBJECT_KEY;
4262 else
4263 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4264
4265 break;
4266 }
4267
4268 case _JSON_BUILD_RATELIMIT: {
4269 const RateLimit *rl;
4270
4271 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4272 r = -EINVAL;
4273 goto finish;
4274 }
4275
4276 rl = va_arg(ap, const RateLimit*);
4277
4278 if (current->n_suppress == 0) {
4279 if (ratelimit_configured(rl)) {
4280 r = sd_json_buildo(
4281 &add,
4282 SD_JSON_BUILD_PAIR_UNSIGNED("intervalUSec", rl->interval),
4283 SD_JSON_BUILD_PAIR_UNSIGNED("burst", rl->burst));
4284 if (r < 0)
4285 goto finish;
4286 } else
4287 add = JSON_VARIANT_MAGIC_NULL;
4288 }
4289
4290 n_subtract = 1;
4291
4292 if (current->expect == EXPECT_TOPLEVEL)
4293 current->expect = EXPECT_END;
4294 else if (current->expect == EXPECT_OBJECT_VALUE)
4295 current->expect = EXPECT_OBJECT_KEY;
4296 else
4297 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4298
4299 break;
4300 }
4301
4302 case _JSON_BUILD_PIDREF: {
4303 PidRef *pidref;
4304
4305 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4306 r = -EINVAL;
4307 goto finish;
4308 }
4309
4310 pidref = va_arg(ap, PidRef*);
4311
4312 if (current->n_suppress == 0) {
4313 r = json_variant_new_pidref(&add, pidref);
4314 if (r < 0)
4315 goto finish;
4316 }
4317
4318 n_subtract = 1;
4319
4320 if (current->expect == EXPECT_TOPLEVEL)
4321 current->expect = EXPECT_END;
4322 else if (current->expect == EXPECT_OBJECT_VALUE)
4323 current->expect = EXPECT_OBJECT_KEY;
4324 else
4325 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4326
4327 break;
4328 }
4329
4330 case _JSON_BUILD_DEVNUM: {
4331 dev_t devnum;
4332
4333 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4334 r = -EINVAL;
4335 goto finish;
4336 }
4337
4338 devnum = va_arg(ap, dev_t);
4339
4340 if (current->n_suppress == 0) {
4341 r = json_variant_new_devnum(&add, devnum);
4342 if (r < 0)
4343 goto finish;
4344 }
4345
4346 n_subtract = 1;
4347
4348 if (current->expect == EXPECT_TOPLEVEL)
4349 current->expect = EXPECT_END;
4350 else if (current->expect == EXPECT_OBJECT_VALUE)
4351 current->expect = EXPECT_OBJECT_KEY;
4352 else
4353 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4354
4355 break;
4356 }
4357
4358 case _JSON_BUILD_TRISTATE: {
4359 int tristate;
4360
4361 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4362 r = -EINVAL;
4363 goto finish;
4364 }
4365
4366 tristate = va_arg(ap, int);
4367
4368 if (current->n_suppress == 0) {
4369 if (tristate >= 0) {
4370 r = sd_json_variant_new_boolean(&add, tristate);
4371 if (r < 0)
4372 goto finish;
4373 } else
4374 add = JSON_VARIANT_MAGIC_NULL;
4375 }
4376
4377 n_subtract = 1;
4378
4379 if (current->expect == EXPECT_TOPLEVEL)
4380 current->expect = EXPECT_END;
4381 else if (current->expect == EXPECT_OBJECT_VALUE)
4382 current->expect = EXPECT_OBJECT_KEY;
4383 else
4384 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4385
4386 break;
4387 }
4388
4389 case _SD_JSON_BUILD_CALLBACK: {
4390 sd_json_build_callback_t cb;
4391 void *userdata;
4392
4393 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4394 r = -EINVAL;
4395 goto finish;
4396 }
4397
4398 cb = va_arg(ap, sd_json_build_callback_t);
4399 userdata = va_arg(ap, void *);
4400
4401 if (current->n_suppress == 0) {
4402 if (cb) {
4403 r = cb(&add, name, userdata);
4404 if (r < 0)
4405 goto finish;
4406 }
4407
4408 if (!add)
4409 add = JSON_VARIANT_MAGIC_NULL;
4410
4411 name = NULL;
4412 }
4413
4414 n_subtract = 1;
4415
4416 if (current->expect == EXPECT_TOPLEVEL)
4417 current->expect = EXPECT_END;
4418 else if (current->expect == EXPECT_OBJECT_VALUE)
4419 current->expect = EXPECT_OBJECT_KEY;
4420 else
4421 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4422
4423 break;
4424 }
4425
4426 case _SD_JSON_BUILD_OBJECT_BEGIN:
4427
4428 if (!IN_SET(current->expect, EXPECT_TOPLEVEL, EXPECT_OBJECT_VALUE, EXPECT_ARRAY_ELEMENT)) {
4429 r = -EINVAL;
4430 goto finish;
4431 }
4432
4433 if (!GREEDY_REALLOC(stack, n_stack+1)) {
4434 r = -ENOMEM;
4435 goto finish;
4436 }
4437 current = stack + n_stack - 1;
4438
4439 if (current->expect == EXPECT_TOPLEVEL)
4440 current->expect = EXPECT_END;
4441 else if (current->expect == EXPECT_OBJECT_VALUE)
4442 current->expect = EXPECT_OBJECT_KEY;
4443 else
4444 assert(current->expect == EXPECT_ARRAY_ELEMENT);
4445
4446 stack[n_stack++] = (JsonStack) {
4447 .expect = EXPECT_OBJECT_KEY,
4448 .n_suppress = current->n_suppress != 0 ? SIZE_MAX : 0, /* If we shall suppress the
4449 * new object, then we should
4450 * also suppress all object
4451 * members. */
4452 };
4453
4454 break;
4455
4456 case _SD_JSON_BUILD_OBJECT_END:
4457
4458 if (current->expect != EXPECT_OBJECT_KEY) {
4459 r = -EINVAL;
4460 goto finish;
4461 }
4462
4463 assert(n_stack > 1);
4464
4465 if (current->n_suppress == 0) {
4466 r = sd_json_variant_new_object(&add, current->elements, current->n_elements);
4467 if (r < 0)
4468 goto finish;
4469 }
4470
4471 n_subtract = 1;
4472
4473 json_stack_release(current);
4474 n_stack--, current--;
4475
4476 break;
4477
4478 case _SD_JSON_BUILD_PAIR: {
4479
4480 if (current->expect != EXPECT_OBJECT_KEY) {
4481 r = -EINVAL;
4482 goto finish;
4483 }
4484
4485 name = va_arg(ap, const char *);
4486
4487 if (current->n_suppress == 0) {
4488 r = sd_json_variant_new_string(&add, name);
4489 if (r < 0)
4490 goto finish;
4491 }
4492
4493 n_subtract = 1;
4494
4495 current->expect = EXPECT_OBJECT_VALUE;
4496 break;
4497 }
4498
4499 case _SD_JSON_BUILD_PAIR_CONDITION: {
4500 bool b;
4501
4502 if (current->expect != EXPECT_OBJECT_KEY) {
4503 r = -EINVAL;
4504 goto finish;
4505 }
4506
4507 b = va_arg(ap, int);
4508 name = va_arg(ap, const char *);
4509
4510 if (b && current->n_suppress == 0) {
4511 r = sd_json_variant_new_string(&add, name);
4512 if (r < 0)
4513 goto finish;
4514 }
4515
4516 n_subtract = 1; /* we generated one item */
4517
4518 if (!b && current->n_suppress != SIZE_MAX)
4519 current->n_suppress += 2; /* Suppress this one and the next item */
4520
4521 current->expect = EXPECT_OBJECT_VALUE;
4522 break;
4523 }
4524
4525 case _JSON_BUILD_PAIR_INTEGER_NON_ZERO:
4526 case _JSON_BUILD_PAIR_INTEGER_NON_NEGATIVE: {
4527 const char *n;
4528 int64_t i;
4529 bool include;
4530
4531 if (current->expect != EXPECT_OBJECT_KEY) {
4532 r = -EINVAL;
4533 goto finish;
4534 }
4535
4536 n = va_arg(ap, const char*);
4537 i = va_arg(ap, int64_t);
4538
4539 if (command == _JSON_BUILD_PAIR_INTEGER_NON_ZERO)
4540 include = i != 0;
4541 else if (command == _JSON_BUILD_PAIR_INTEGER_NON_NEGATIVE)
4542 include = i >= 0;
4543 else
4544 assert_not_reached();
4545
4546 if (include && current->n_suppress == 0) {
4547 r = sd_json_variant_new_string(&add, n);
4548 if (r < 0)
4549 goto finish;
4550
4551 r = sd_json_variant_new_integer(&add_more, i);
4552 if (r < 0)
4553 goto finish;
4554 }
4555
4556 n_subtract = 2; /* we generated two items */
4557
4558 current->expect = EXPECT_OBJECT_KEY;
4559 break;
4560 }
4561
4562 case _JSON_BUILD_PAIR_UNSIGNED_NON_ZERO:
4563 case _JSON_BUILD_PAIR_UNSIGNED_NOT_EQUAL: {
4564 const char *n;
4565 uint64_t u, eq;
4566
4567 if (current->expect != EXPECT_OBJECT_KEY) {
4568 r = -EINVAL;
4569 goto finish;
4570 }
4571
4572 n = va_arg(ap, const char *);
4573 u = va_arg(ap, uint64_t);
4574 eq = command == _JSON_BUILD_PAIR_UNSIGNED_NON_ZERO ? 0 : va_arg(ap, uint64_t);
4575
4576 if (u != eq && current->n_suppress == 0) {
4577 r = sd_json_variant_new_string(&add, n);
4578 if (r < 0)
4579 goto finish;
4580
4581 r = sd_json_variant_new_unsigned(&add_more, u);
4582 if (r < 0)
4583 goto finish;
4584 }
4585
4586 n_subtract = 2; /* we generated two items */
4587
4588 current->expect = EXPECT_OBJECT_KEY;
4589 break;
4590 }
4591
4592 case _JSON_BUILD_PAIR_FINITE_USEC_NON_ZERO:
4593 case _JSON_BUILD_PAIR_FINITE_USEC: {
4594 const char *n;
4595 usec_t u;
4596
4597 if (current->expect != EXPECT_OBJECT_KEY) {
4598 r = -EINVAL;
4599 goto finish;
4600 }
4601
4602 n = va_arg(ap, const char *);
4603 u = va_arg(ap, usec_t);
4604
4605 if (u != USEC_INFINITY &&
4606 (command != _JSON_BUILD_PAIR_FINITE_USEC_NON_ZERO || u > 0) &&
4607 current->n_suppress == 0) {
4608 r = sd_json_variant_new_string(&add, n);
4609 if (r < 0)
4610 goto finish;
4611
4612 r = sd_json_variant_new_unsigned(&add_more, u);
4613 if (r < 0)
4614 goto finish;
4615 }
4616
4617 n_subtract = 2; /* we generated two items */
4618
4619 current->expect = EXPECT_OBJECT_KEY;
4620 break;
4621 }
4622
4623 case _JSON_BUILD_PAIR_STRING_NON_EMPTY:
4624 case _JSON_BUILD_PAIR_STRING_NON_EMPTY_UNDERSCORIFY: {
4625 const char *n, *s;
4626
4627 if (current->expect != EXPECT_OBJECT_KEY) {
4628 r = -EINVAL;
4629 goto finish;
4630 }
4631
4632 n = va_arg(ap, const char *);
4633 s = va_arg(ap, const char *);
4634
4635 if (!isempty(s) && current->n_suppress == 0) {
4636 r = sd_json_variant_new_string(&add, n);
4637 if (r < 0)
4638 goto finish;
4639
4640 if (command == _JSON_BUILD_PAIR_STRING_NON_EMPTY_UNDERSCORIFY) {
4641 _cleanup_free_ char *c = strdup(s);
4642 if (!c) {
4643 r = -ENOMEM;
4644 goto finish;
4645 }
4646
4647 r = sd_json_variant_new_string(&add_more, json_underscorify(c));
4648 } else
4649 r = sd_json_variant_new_string(&add_more, s);
4650 if (r < 0)
4651 goto finish;
4652 }
4653
4654 n_subtract = 2; /* we generated two items */
4655
4656 current->expect = EXPECT_OBJECT_KEY;
4657 break;
4658 }
4659
4660 case _JSON_BUILD_PAIR_STRV_NON_EMPTY:
4661 case _JSON_BUILD_PAIR_STRV_ENV_PAIR_NON_EMPTY: {
4662 const char *n;
4663 char **l;
4664
4665 if (current->expect != EXPECT_OBJECT_KEY) {
4666 r = -EINVAL;
4667 goto finish;
4668 }
4669
4670 n = va_arg(ap, const char *);
4671 l = va_arg(ap, char **);
4672
4673 if (!strv_isempty(l) && current->n_suppress == 0) {
4674 _cleanup_strv_free_ char **el = NULL;
4675
4676 if (command == _JSON_BUILD_PAIR_STRV_ENV_PAIR_NON_EMPTY) {
4677 r = strv_env_get_merged(l, &el);
4678 if (r < 0)
4679 goto finish;
4680 }
4681
4682 r = sd_json_variant_new_string(&add, n);
4683 if (r < 0)
4684 goto finish;
4685
4686 r = sd_json_variant_new_array_strv(&add_more, el ?: l);
4687 if (r < 0)
4688 goto finish;
4689 }
4690
4691 n_subtract = 2; /* we generated two items */
4692
4693 current->expect = EXPECT_OBJECT_KEY;
4694 break;
4695 }
4696
4697 case _JSON_BUILD_PAIR_VARIANT_NON_NULL: {
4698 sd_json_variant *v;
4699 const char *n;
4700
4701 if (current->expect != EXPECT_OBJECT_KEY) {
4702 r = -EINVAL;
4703 goto finish;
4704 }
4705
4706 n = va_arg(ap, const char *);
4707 v = va_arg(ap, sd_json_variant *);
4708
4709 if (v && !sd_json_variant_is_null(v) && current->n_suppress == 0) {
4710 r = sd_json_variant_new_string(&add, n);
4711 if (r < 0)
4712 goto finish;
4713
4714 add_more = sd_json_variant_ref(v);
4715 }
4716
4717 n_subtract = 2; /* we generated two items */
4718
4719 current->expect = EXPECT_OBJECT_KEY;
4720 break;
4721 }
4722
4723 case _JSON_BUILD_PAIR_VARIANT_NON_EMPTY: {
4724 sd_json_variant *v;
4725 const char *n;
4726
4727 if (current->expect != EXPECT_OBJECT_KEY) {
4728 r = -EINVAL;
4729 goto finish;
4730 }
4731
4732 n = va_arg(ap, const char *);
4733 v = va_arg(ap, sd_json_variant *);
4734
4735 if (v && !sd_json_variant_is_blank_object(v) && current->n_suppress == 0) {
4736 r = sd_json_variant_new_string(&add, n);
4737 if (r < 0)
4738 goto finish;
4739
4740 add_more = sd_json_variant_ref(v);
4741 }
4742
4743 n_subtract = 2; /* we generated two items */
4744
4745 current->expect = EXPECT_OBJECT_KEY;
4746 break;
4747 }
4748
4749 case _JSON_BUILD_PAIR_BYTE_ARRAY_NON_EMPTY: {
4750 const void *array;
4751 size_t sz;
4752 const char *n;
4753
4754 if (current->expect != EXPECT_OBJECT_KEY) {
4755 r = -EINVAL;
4756 goto finish;
4757 }
4758
4759 n = va_arg(ap, const char *);
4760 array = va_arg(ap, const void*);
4761 sz = va_arg(ap, size_t);
4762
4763 if (sz > 0 && current->n_suppress == 0) {
4764 r = sd_json_variant_new_string(&add, n);
4765 if (r < 0)
4766 goto finish;
4767
4768 r = sd_json_variant_new_array_bytes(&add_more, array, sz);
4769 if (r < 0)
4770 goto finish;
4771 }
4772
4773 n_subtract = 2; /* we generated two items */
4774
4775 current->expect = EXPECT_OBJECT_KEY;
4776 break;
4777 }
4778
4779 case _JSON_BUILD_PAIR_IN_ADDR_NON_NULL:
4780 case _JSON_BUILD_PAIR_IN_ADDR_WITH_STRING_NON_NULL:
4781 case _JSON_BUILD_PAIR_IN_ADDR_WITH_STRING: {
4782 const union in_addr_union *a;
4783 const char *n;
4784 int f;
4785
4786 if (current->expect != EXPECT_OBJECT_KEY) {
4787 r = -EINVAL;
4788 goto finish;
4789 }
4790
4791 n = va_arg(ap, const char *);
4792 f = va_arg(ap, int);
4793 a = va_arg(ap, const union in_addr_union *);
4794
4795 if (current->n_suppress == 0 &&
4796 ((a && in_addr_is_set(f, a)) ||
4797 command == _JSON_BUILD_PAIR_IN_ADDR_WITH_STRING)) {
4798
4799 if (!a)
4800 a = &IN_ADDR_NULL;
4801
4802 r = sd_json_variant_new_string(&add, n);
4803 if (r < 0)
4804 goto finish;
4805
4806 r = sd_json_variant_new_array_bytes(&add_more, a->bytes, FAMILY_ADDRESS_SIZE_SAFE(f));
4807 if (r < 0)
4808 goto finish;
4809
4810 if (IN_SET(command, _JSON_BUILD_PAIR_IN_ADDR_WITH_STRING, _JSON_BUILD_PAIR_IN_ADDR_WITH_STRING_NON_NULL)) {
4811 _cleanup_free_ char *string_key_name = NULL;
4812 _cleanup_(sd_json_variant_unrefp) sd_json_variant *string_key = NULL, *string_value = NULL;
4813
4814 string_key_name = strjoin(n, "String");
4815 if (!string_key_name) {
4816 r = -ENOMEM;
4817 goto finish;
4818 }
4819
4820 r = sd_json_variant_new_string(&string_key, string_key_name);
4821 if (r < 0)
4822 goto finish;
4823
4824 r = sd_json_variant_new_string(&string_value, IN_ADDR_TO_STRING(f, a));
4825 if (r < 0)
4826 goto finish;
4827
4828 if (!GREEDY_REALLOC(current->elements, current->n_elements + 2)) {
4829 r = -ENOMEM;
4830 goto finish;
4831 }
4832
4833 current->elements[current->n_elements++] = TAKE_PTR(string_key);
4834 current->elements[current->n_elements++] = TAKE_PTR(string_value);
4835 }
4836 }
4837
4838 n_subtract = command == _JSON_BUILD_PAIR_IN_ADDR_NON_NULL ? 2 : 4;
4839
4840 current->expect = EXPECT_OBJECT_KEY;
4841 break;
4842 }
4843
4844 case _JSON_BUILD_PAIR_ETHER_ADDR_NON_NULL: {
4845 const struct ether_addr *a;
4846 const char *n;
4847
4848 if (current->expect != EXPECT_OBJECT_KEY) {
4849 r = -EINVAL;
4850 goto finish;
4851 }
4852
4853 n = va_arg(ap, const char *);
4854 a = va_arg(ap, const struct ether_addr *);
4855
4856 if (a && !ether_addr_is_null(a) && current->n_suppress == 0) {
4857 r = sd_json_variant_new_string(&add, n);
4858 if (r < 0)
4859 goto finish;
4860
4861 r = sd_json_variant_new_array_bytes(&add_more, a->ether_addr_octet, sizeof(struct ether_addr));
4862 if (r < 0)
4863 goto finish;
4864 }
4865
4866 n_subtract = 2; /* we generated two items */
4867
4868 current->expect = EXPECT_OBJECT_KEY;
4869 break;
4870 }
4871
4872 case _JSON_BUILD_PAIR_HW_ADDR_NON_NULL: {
4873 const struct hw_addr_data *a;
4874 const char *n;
4875
4876 if (current->expect != EXPECT_OBJECT_KEY) {
4877 r = -EINVAL;
4878 goto finish;
4879 }
4880
4881 n = va_arg(ap, const char *);
4882 a = va_arg(ap, const struct hw_addr_data *);
4883
4884 if (a && !hw_addr_is_null(a) && current->n_suppress == 0) {
4885 r = sd_json_variant_new_string(&add, n);
4886 if (r < 0)
4887 goto finish;
4888
4889 r = sd_json_variant_new_array_bytes(&add_more, a->bytes, a->length);
4890 if (r < 0)
4891 goto finish;
4892 }
4893
4894 n_subtract = 2; /* we generated two items */
4895
4896 current->expect = EXPECT_OBJECT_KEY;
4897 break;
4898 }
4899
4900 case _JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL: {
4901 const dual_timestamp *ts;
4902 const char *n;
4903
4904 if (current->expect != EXPECT_OBJECT_KEY) {
4905 r = -EINVAL;
4906 goto finish;
4907 }
4908
4909 n = va_arg(ap, const char*);
4910 ts = va_arg(ap, const dual_timestamp*);
4911
4912 if (ts && dual_timestamp_is_set(ts) && current->n_suppress == 0) {
4913 r = sd_json_variant_new_string(&add, n);
4914 if (r < 0)
4915 goto finish;
4916
4917 r = sd_json_buildo(&add_more,
4918 SD_JSON_BUILD_PAIR_UNSIGNED("realtime", ts->realtime),
4919 SD_JSON_BUILD_PAIR_UNSIGNED("monotonic", ts->monotonic));
4920 if (r < 0)
4921 goto finish;
4922 }
4923
4924 n_subtract = 2; /* we generated two items */
4925
4926 current->expect = EXPECT_OBJECT_KEY;
4927 break;
4928 }
4929
4930 case _JSON_BUILD_PAIR_RATELIMIT_ENABLED: {
4931 const RateLimit *rl;
4932 const char *n;
4933
4934 if (current->expect != EXPECT_OBJECT_KEY) {
4935 r = -EINVAL;
4936 goto finish;
4937 }
4938
4939 n = va_arg(ap, const char*);
4940 rl = va_arg(ap, const RateLimit*);
4941
4942 if (rl && ratelimit_configured(rl) && current->n_suppress == 0) {
4943 r = sd_json_variant_new_string(&add, n);
4944 if (r < 0)
4945 goto finish;
4946
4947 r = sd_json_buildo(&add_more,
4948 SD_JSON_BUILD_PAIR_UNSIGNED("intervalUSec", rl->interval),
4949 SD_JSON_BUILD_PAIR_UNSIGNED("burst", rl->burst));
4950 if (r < 0)
4951 goto finish;
4952 }
4953
4954 n_subtract = 2; /* we generated two items */
4955
4956 current->expect = EXPECT_OBJECT_KEY;
4957 break;
4958 }
4959
4960 case _JSON_BUILD_PAIR_PIDREF_NON_NULL: {
4961 PidRef *p;
4962 const char *n;
4963
4964 if (current->expect != EXPECT_OBJECT_KEY) {
4965 r = -EINVAL;
4966 goto finish;
4967 }
4968
4969 n = va_arg(ap, const char*);
4970 p = va_arg(ap, PidRef*);
4971
4972 if (pidref_is_set(p) && current->n_suppress == 0) {
4973 r = sd_json_variant_new_string(&add, n);
4974 if (r < 0)
4975 goto finish;
4976
4977 r = json_variant_new_pidref(&add_more, p);
4978 if (r < 0)
4979 goto finish;
4980 }
4981
4982 n_subtract = 2; /* we generated two items */
4983
4984 current->expect = EXPECT_OBJECT_KEY;
4985 break;
4986 }
4987
4988 case _JSON_BUILD_PAIR_CALLBACK_NON_NULL: {
4989 sd_json_build_callback_t cb;
4990 void *userdata;
4991 const char *n;
4992
4993 if (current->expect != EXPECT_OBJECT_KEY) {
4994 r = -EINVAL;
4995 goto finish;
4996 }
4997
4998 n = va_arg(ap, const char*);
4999 cb = va_arg(ap, sd_json_build_callback_t);
5000 userdata = va_arg(ap, void*);
5001
5002 if (current->n_suppress == 0) {
5003 if (cb) {
5004 r = cb(&add_more, n, userdata);
5005 if (r < 0)
5006 goto finish;
5007 }
5008
5009 if (add_more) {
5010 r = sd_json_variant_new_string(&add, n);
5011 if (r < 0)
5012 goto finish;
5013 }
5014 }
5015
5016 n_subtract = 2; /* we generated two items */
5017
5018 current->expect = EXPECT_OBJECT_KEY;
5019 break;
5020 }
5021
5022 case _JSON_BUILD_PAIR_BASE64_NON_EMPTY:
5023 case _JSON_BUILD_PAIR_BASE32HEX_NON_EMPTY:
5024 case _JSON_BUILD_PAIR_HEX_NON_EMPTY:
5025 case _JSON_BUILD_PAIR_OCTESCAPE_NON_EMPTY: {
5026 const void *p;
5027 size_t sz;
5028 const char *n;
5029
5030 if (current->expect != EXPECT_OBJECT_KEY) {
5031 r = -EINVAL;
5032 goto finish;
5033 }
5034
5035 n = va_arg(ap, const char*);
5036 p = va_arg(ap, const void *);
5037 sz = va_arg(ap, size_t);
5038
5039 if (sz > 0 && current->n_suppress == 0) {
5040 r = sd_json_variant_new_string(&add, n);
5041 if (r < 0)
5042 goto finish;
5043
5044 r = command == _JSON_BUILD_PAIR_BASE64_NON_EMPTY ? sd_json_variant_new_base64(&add_more, p, sz) :
5045 command == _JSON_BUILD_PAIR_BASE32HEX_NON_EMPTY ? sd_json_variant_new_base32hex(&add_more, p, sz) :
5046 command == _JSON_BUILD_PAIR_HEX_NON_EMPTY ? sd_json_variant_new_hex(&add_more, p, sz) :
5047 sd_json_variant_new_octescape(&add_more, p, sz);
5048 if (r < 0)
5049 goto finish;
5050 }
5051
5052 n_subtract = 2; /* we generated two items */
5053
5054 current->expect = EXPECT_OBJECT_KEY;
5055 break;
5056 }
5057
5058 case _JSON_BUILD_PAIR_TRISTATE_NON_NULL: {
5059 int tristate;
5060 const char *n;
5061
5062 if (current->expect != EXPECT_OBJECT_KEY) {
5063 r = -EINVAL;
5064 goto finish;
5065 }
5066
5067 n = va_arg(ap, const char*);
5068 tristate = va_arg(ap, int);
5069
5070 if (tristate >= 0 && current->n_suppress == 0) {
5071 r = sd_json_variant_new_string(&add, n);
5072 if (r < 0)
5073 goto finish;
5074
5075 r = sd_json_variant_new_boolean(&add_more, tristate);
5076 if (r < 0)
5077 goto finish;
5078 }
5079
5080 n_subtract = 2; /* we generated two items */
5081
5082 current->expect = EXPECT_OBJECT_KEY;
5083 break;
5084 }
5085 }
5086
5087 /* If variants were generated, add them to our current variant, but only if we are not supposed to suppress additions */
5088 if (add && current->n_suppress == 0) {
5089 if (!GREEDY_REALLOC(current->elements, current->n_elements + 1 + !!add_more)) {
5090 r = -ENOMEM;
5091 goto finish;
5092 }
5093
5094 current->elements[current->n_elements++] = TAKE_PTR(add);
5095 if (add_more)
5096 current->elements[current->n_elements++] = TAKE_PTR(add_more);
5097 }
5098
5099 /* If we are supposed to suppress items, let's subtract how many items where generated from
5100 * that counter. Except if the counter is SIZE_MAX, i.e. we shall suppress an infinite number
5101 * of elements on this stack level */
5102 if (current->n_suppress != SIZE_MAX) {
5103 if (current->n_suppress <= n_subtract) /* Saturated */
5104 current->n_suppress = 0;
5105 else
5106 current->n_suppress -= n_subtract;
5107 }
5108 }
5109
5110 done:
5111 assert(n_stack == 1);
5112 assert(stack[0].n_elements == 1);
5113
5114 *ret = sd_json_variant_ref(stack[0].elements[0]);
5115 r = 0;
5116
5117 finish:
5118 FOREACH_ARRAY(i, stack, n_stack)
5119 json_stack_release(i);
5120
5121 free(stack);
5122
5123 return r;
5124 }
5125
5126 _public_ int sd_json_build(sd_json_variant **ret, ...) {
5127 va_list ap;
5128 int r;
5129
5130 va_start(ap, ret);
5131 r = sd_json_buildv(ret, ap);
5132 va_end(ap);
5133
5134 return r;
5135 }
5136
5137 int json_log_internal(
5138 sd_json_variant *variant,
5139 int level,
5140 int error,
5141 const char *file,
5142 int line,
5143 const char *func,
5144 const char *format, ...) {
5145
5146 PROTECT_ERRNO;
5147
5148 unsigned source_line, source_column;
5149 char buffer[LINE_MAX];
5150 const char *source;
5151 va_list ap;
5152 int r;
5153
5154 errno = ERRNO_VALUE(error);
5155
5156 va_start(ap, format);
5157 (void) vsnprintf(buffer, sizeof buffer, format, ap);
5158 va_end(ap);
5159
5160 if (variant) {
5161 r = sd_json_variant_get_source(variant, &source, &source_line, &source_column);
5162 if (r < 0)
5163 return r;
5164 } else {
5165 source = NULL;
5166 source_line = 0;
5167 source_column = 0;
5168 }
5169
5170 if (source && source_line > 0 && source_column > 0)
5171 return log_struct_internal(
5172 level,
5173 error,
5174 file, line, func,
5175 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
5176 LOG_ITEM("CONFIG_FILE=%s", source),
5177 LOG_ITEM("CONFIG_LINE=%u", source_line),
5178 LOG_ITEM("CONFIG_COLUMN=%u", source_column),
5179 LOG_MESSAGE("%s:%u:%u: %s", source, source_line, source_column, buffer),
5180 NULL);
5181 else if (source_line > 0 && source_column > 0)
5182 return log_struct_internal(
5183 level,
5184 error,
5185 file, line, func,
5186 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
5187 LOG_ITEM("CONFIG_LINE=%u", source_line),
5188 LOG_ITEM("CONFIG_COLUMN=%u", source_column),
5189 LOG_MESSAGE("(string):%u:%u: %s", source_line, source_column, buffer),
5190 NULL);
5191 else
5192 return log_struct_internal(
5193 level,
5194 error,
5195 file, line, func,
5196 LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
5197 LOG_MESSAGE("%s", buffer),
5198 NULL);
5199 }
5200
5201 static void* dispatch_userdata(const sd_json_dispatch_field *p, void *userdata) {
5202
5203 /* When the userdata pointer is passed in as NULL, then we'll just use the offset as a literal
5204 * address, and convert it to a pointer. Note that might as well just add the offset to the NULL
5205 * pointer, but UndefinedBehaviourSanitizer doesn't like pointer arithmetics based on NULL pointers,
5206 * hence we code this explicitly here. */
5207
5208 if (userdata)
5209 return (uint8_t*) userdata + p->offset;
5210
5211 return SIZE_TO_PTR(p->offset);
5212 }
5213
5214 _public_ int sd_json_dispatch_full(
5215 sd_json_variant *v,
5216 const sd_json_dispatch_field table[],
5217 sd_json_dispatch_callback_t bad,
5218 sd_json_dispatch_flags_t flags,
5219 void *userdata,
5220 const char **reterr_bad_field) {
5221 size_t m;
5222 int r, done = 0;
5223 bool *found;
5224
5225 /* Consider a NULL pointer equivalent to an empty object */
5226 if (!v)
5227 v = JSON_VARIANT_MAGIC_EMPTY_OBJECT;
5228
5229 if (!sd_json_variant_is_object(v)) {
5230 json_log(v, flags, 0, "JSON variant is not an object.");
5231
5232 if (flags & SD_JSON_PERMISSIVE)
5233 return 0;
5234
5235 if (reterr_bad_field)
5236 *reterr_bad_field = NULL;
5237
5238 return -EINVAL;
5239 }
5240
5241 m = 0;
5242 for (const sd_json_dispatch_field *p = table; p && p->name; p++)
5243 m++;
5244
5245 found = newa0(bool, m);
5246
5247 size_t n = sd_json_variant_elements(v);
5248 for (size_t i = 0; i < n; i += 2) {
5249 sd_json_variant *key, *value;
5250 const sd_json_dispatch_field *p;
5251
5252 assert_se(key = sd_json_variant_by_index(v, i));
5253 assert_se(value = sd_json_variant_by_index(v, i+1));
5254
5255 for (p = table; p && p->name; p++)
5256 if (p->name == POINTER_MAX ||
5257 streq_ptr(sd_json_variant_string(key), p->name))
5258 break;
5259
5260 if (p && p->name) { /* Found a matching entry! 🙂 */
5261 sd_json_dispatch_flags_t merged_flags;
5262
5263 merged_flags = flags | p->flags;
5264
5265 /* If an explicit type is specified, verify it matches */
5266 if (p->type != _SD_JSON_VARIANT_TYPE_INVALID &&
5267 !sd_json_variant_has_type(value, p->type) &&
5268 !(FLAGS_SET(merged_flags, SD_JSON_NULLABLE) && sd_json_variant_is_null(value))) {
5269
5270 json_log(value, merged_flags, 0,
5271 "Object field '%s' has wrong type %s, expected %s.", sd_json_variant_string(key),
5272 sd_json_variant_type_to_string(sd_json_variant_type(value)), sd_json_variant_type_to_string(p->type));
5273
5274 if (merged_flags & SD_JSON_PERMISSIVE)
5275 continue;
5276
5277 if (reterr_bad_field)
5278 *reterr_bad_field = p->name;
5279
5280 return -EINVAL;
5281 }
5282
5283 /* If the SD_JSON_REFUSE_NULL flag is specified, insist the field is not "null". Note
5284 * that this provides overlapping functionality with the type check above. */
5285 if (FLAGS_SET(merged_flags, SD_JSON_REFUSE_NULL) && sd_json_variant_is_null(value)) {
5286
5287 json_log(value, merged_flags, 0,
5288 "Object field '%s' may not be null.", sd_json_variant_string(key));
5289
5290 if (merged_flags & SD_JSON_PERMISSIVE)
5291 continue;
5292
5293 if (reterr_bad_field)
5294 *reterr_bad_field = p->name;
5295
5296 return -EINVAL;
5297 }
5298
5299 if (found[p-table]) {
5300 json_log(value, merged_flags, 0, "Duplicate object field '%s'.", sd_json_variant_string(key));
5301
5302 if (merged_flags & SD_JSON_PERMISSIVE)
5303 continue;
5304
5305 if (reterr_bad_field)
5306 *reterr_bad_field = p->name;
5307
5308 return -ENOTUNIQ;
5309 }
5310
5311 found[p-table] = true;
5312
5313 if (p->callback) {
5314 r = p->callback(sd_json_variant_string(key), value, merged_flags, dispatch_userdata(p, userdata));
5315 if (r < 0) {
5316 if (merged_flags & SD_JSON_PERMISSIVE)
5317 continue;
5318
5319 if (reterr_bad_field)
5320 *reterr_bad_field = sd_json_variant_string(key);
5321
5322 return r;
5323 }
5324 }
5325
5326 done++;
5327
5328 } else { /* Didn't find a matching entry! ☹️ */
5329
5330 if (bad) {
5331 r = bad(sd_json_variant_string(key), value, flags, userdata);
5332 if (r < 0) {
5333 if (flags & SD_JSON_PERMISSIVE)
5334 continue;
5335
5336 if (reterr_bad_field)
5337 *reterr_bad_field = sd_json_variant_string(key);
5338
5339 return r;
5340 } else
5341 done++;
5342
5343 } else {
5344 if (flags & SD_JSON_ALLOW_EXTENSIONS)
5345 continue;
5346
5347 json_log(value, flags, 0, "Unexpected object field '%s'.", sd_json_variant_string(key));
5348 if (flags & SD_JSON_PERMISSIVE)
5349 continue;
5350
5351 if (reterr_bad_field)
5352 *reterr_bad_field = sd_json_variant_string(key);
5353
5354 return -EADDRNOTAVAIL;
5355 }
5356 }
5357 }
5358
5359 for (const sd_json_dispatch_field *p = table; p && p->name; p++) {
5360 sd_json_dispatch_flags_t merged_flags = p->flags | flags;
5361
5362 if ((merged_flags & SD_JSON_MANDATORY) && !found[p-table]) {
5363 json_log(v, merged_flags, 0, "Missing object field '%s'.", p->name);
5364
5365 if ((merged_flags & SD_JSON_PERMISSIVE))
5366 continue;
5367
5368 if (reterr_bad_field)
5369 *reterr_bad_field = p->name;
5370
5371 return -ENXIO;
5372 }
5373 }
5374
5375 return done;
5376 }
5377
5378 _public_ int sd_json_dispatch(
5379 sd_json_variant *v,
5380 const sd_json_dispatch_field table[],
5381 sd_json_dispatch_flags_t flags,
5382 void *userdata) {
5383
5384 return sd_json_dispatch_full(v, table, NULL, flags, userdata, NULL);
5385 }
5386
5387 _public_ int sd_json_dispatch_stdbool(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5388 bool *b = userdata;
5389
5390 assert_return(variant, -EINVAL);
5391 assert_return(userdata, -EINVAL);
5392
5393 if (sd_json_variant_is_null(variant)) {
5394 *b = false;
5395 return 0;
5396 }
5397
5398 if (!sd_json_variant_is_boolean(variant))
5399 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a boolean.", strna(name));
5400
5401 *b = sd_json_variant_boolean(variant);
5402 return 0;
5403 }
5404
5405 _public_ int sd_json_dispatch_intbool(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5406 int *b = userdata;
5407
5408 assert_return(variant, -EINVAL);
5409 assert_return(userdata, -EINVAL);
5410
5411 if (sd_json_variant_is_null(variant)) {
5412 *b = false;
5413 return 0;
5414 }
5415
5416 if (!sd_json_variant_is_boolean(variant))
5417 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a boolean.", strna(name));
5418
5419 *b = sd_json_variant_boolean(variant);
5420 return 0;
5421 }
5422
5423 _public_ int sd_json_dispatch_tristate(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5424 int *b = userdata;
5425
5426 assert_return(variant, -EINVAL);
5427 assert_return(userdata, -EINVAL);
5428
5429 if (sd_json_variant_is_null(variant)) {
5430 *b = -1;
5431 return 0;
5432 }
5433
5434 if (!sd_json_variant_is_boolean(variant))
5435 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a boolean.", strna(name));
5436
5437 *b = sd_json_variant_boolean(variant);
5438 return 0;
5439 }
5440
5441 _public_ int sd_json_dispatch_int64(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5442 int64_t *i = userdata;
5443
5444 assert_return(variant, -EINVAL);
5445 assert_return(userdata, -EINVAL);
5446
5447 if (sd_json_variant_is_null(variant)) {
5448 *i = -1;
5449 return 0;
5450 }
5451
5452 /* Also accept numbers formatted as string, to increase compatibility with less capable JSON
5453 * implementations that cannot do 64bit integers. */
5454 if (sd_json_variant_is_string(variant) && safe_atoi64(sd_json_variant_string(variant), i) >= 0)
5455 return 0;
5456
5457 if (!sd_json_variant_is_integer(variant))
5458 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an integer, nor one formatted as decimal string.", strna(name));
5459
5460 *i = sd_json_variant_integer(variant);
5461 return 0;
5462 }
5463
5464 _public_ int sd_json_dispatch_uint64(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5465 uint64_t *u = userdata;
5466
5467 assert_return(variant, -EINVAL);
5468 assert_return(userdata, -EINVAL);
5469
5470 if (sd_json_variant_is_null(variant)) {
5471 *u = UINT64_MAX;
5472 return 0;
5473 }
5474
5475 /* Since 64bit values (in particular unsigned ones) in JSON are problematic, let's also accept them
5476 * formatted as strings. If this is not desired make sure to set the .type field in
5477 * sd_json_dispatch_field to SD_JSON_UNSIGNED rather than _SD_JSON_VARIANT_TYPE_INVALID, so that
5478 * json_dispatch() already filters out the non-matching type. */
5479
5480 if (sd_json_variant_is_string(variant) && safe_atou64(sd_json_variant_string(variant), u) >= 0)
5481 return 0;
5482
5483 if (!sd_json_variant_is_unsigned(variant))
5484 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an unsigned integer, nor one formatted as decimal string.", strna(name));
5485
5486 *u = sd_json_variant_unsigned(variant);
5487 return 0;
5488 }
5489
5490 _public_ int sd_json_dispatch_uint32(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5491 uint32_t *u = userdata;
5492 uint64_t u64;
5493 int r;
5494
5495 assert_return(variant, -EINVAL);
5496 assert_return(userdata, -EINVAL);
5497
5498 if (sd_json_variant_is_null(variant)) {
5499 *u = UINT32_MAX;
5500 return 0;
5501 }
5502
5503 r = sd_json_dispatch_uint64(name, variant, flags, &u64);
5504 if (r < 0)
5505 return r;
5506
5507 if (u64 > UINT32_MAX)
5508 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
5509
5510 *u = (uint32_t) u64;
5511 return 0;
5512 }
5513
5514 /* We define sd_json_dispatch_uint() as alias for json_dispatch_uint32(), let's make sure this is safe */
5515 assert_cc(sizeof(uint32_t) == sizeof(unsigned));
5516
5517 _public_ int sd_json_dispatch_int32(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5518 int32_t *i = userdata;
5519 int64_t i64;
5520 int r;
5521
5522 assert_return(variant, -EINVAL);
5523 assert_return(userdata, -EINVAL);
5524
5525 if (sd_json_variant_is_null(variant)) {
5526 *i = -1;
5527 return 0;
5528 }
5529
5530 r = sd_json_dispatch_int64(name, variant, flags, &i64);
5531 if (r < 0)
5532 return r;
5533
5534 if (i64 < INT32_MIN || i64 > INT32_MAX)
5535 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
5536
5537 *i = (int32_t) i64;
5538 return 0;
5539 }
5540
5541 /* We define sd_json_dispatch_int() as alias for json_dispatch_int32(), let's make sure this is safe */
5542 assert_cc(sizeof(int32_t) == sizeof(int));
5543
5544 _public_ int sd_json_dispatch_int16(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5545 int16_t *i = userdata;
5546 int64_t i64;
5547 int r;
5548
5549 assert_return(variant, -EINVAL);
5550 assert_return(userdata, -EINVAL);
5551
5552 if (sd_json_variant_is_null(variant)) {
5553 *i = -1;
5554 return 0;
5555 }
5556
5557 r = sd_json_dispatch_int64(name, variant, flags, &i64);
5558 if (r < 0)
5559 return r;
5560
5561 if (i64 < INT16_MIN || i64 > INT16_MAX)
5562 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
5563
5564 *i = (int16_t) i64;
5565 return 0;
5566 }
5567
5568 _public_ int sd_json_dispatch_uint16(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5569 uint16_t *u = userdata;
5570 uint64_t u64;
5571 int r;
5572
5573 assert_return(variant, -EINVAL);
5574 assert_return(userdata, -EINVAL);
5575
5576 if (sd_json_variant_is_null(variant)) {
5577 *u = UINT16_MAX;
5578 return 0;
5579 }
5580
5581 r = sd_json_dispatch_uint64(name, variant, flags, &u64);
5582 if (r < 0)
5583 return r;
5584
5585 if (u64 > UINT16_MAX)
5586 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
5587
5588 *u = (uint16_t) u64;
5589 return 0;
5590 }
5591
5592 _public_ int sd_json_dispatch_int8(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5593 int8_t *i = userdata;
5594 int64_t i64;
5595 int r;
5596
5597 assert_return(variant, -EINVAL);
5598 assert_return(userdata, -EINVAL);
5599
5600 if (sd_json_variant_is_null(variant)) {
5601 *i = -1;
5602 return 0;
5603 }
5604
5605 r = sd_json_dispatch_int64(name, variant, flags, &i64);
5606 if (r < 0)
5607 return r;
5608
5609 if (i64 < INT8_MIN || i64 > INT8_MAX)
5610 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
5611
5612 *i = (int8_t) i64;
5613 return 0;
5614 }
5615
5616 _public_ int sd_json_dispatch_uint8(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5617 uint8_t *u = userdata;
5618 uint64_t u64;
5619 int r;
5620
5621 assert_return(variant, -EINVAL);
5622 assert_return(userdata, -EINVAL);
5623
5624 if (sd_json_variant_is_null(variant)) {
5625 *u = UINT8_MAX;
5626 return 0;
5627 }
5628
5629 r = sd_json_dispatch_uint64(name, variant, flags, &u64);
5630 if (r < 0)
5631 return r;
5632
5633 if (u64 > UINT8_MAX)
5634 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' out of bounds.", strna(name));
5635
5636 *u = (uint8_t) u64;
5637 return 0;
5638 }
5639
5640 _public_ int sd_json_dispatch_double(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5641 double *d = userdata;
5642
5643 assert_return(variant, -EINVAL);
5644 assert_return(userdata, -EINVAL);
5645
5646 if (sd_json_variant_is_null(variant)) {
5647 *d = NAN;
5648 return 0;
5649 }
5650
5651 /* Note, this will take care of parsing NaN, -Infinity, Infinity for us */
5652 if (sd_json_variant_is_string(variant) && safe_atod(sd_json_variant_string(variant), d) >= 0)
5653 return 0;
5654
5655 if (!sd_json_variant_is_real(variant))
5656 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a floating point value, nor one formatted as string.", strna(name));
5657
5658 *d = sd_json_variant_real(variant);
5659 return 0;
5660 }
5661
5662 _public_ int sd_json_dispatch_string(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5663 char **s = userdata;
5664 const char *n;
5665 int r;
5666
5667 assert_return(variant, -EINVAL);
5668 assert_return(userdata, -EINVAL);
5669
5670 if (sd_json_variant_is_null(variant)) {
5671 *s = mfree(*s);
5672 return 0;
5673 }
5674
5675 r = sd_json_dispatch_const_string(name, variant, flags, &n);
5676 if (r < 0)
5677 return r;
5678
5679 r = free_and_strdup(s, n);
5680 if (r < 0)
5681 return json_log(variant, flags, r, "Failed to allocate string: %m");
5682
5683 return 0;
5684 }
5685
5686 _public_ int sd_json_dispatch_const_string(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5687 const char **s = userdata;
5688
5689 assert_return(variant, -EINVAL);
5690 assert_return(userdata, -EINVAL);
5691
5692 if (sd_json_variant_is_null(variant)) {
5693 *s = NULL;
5694 return 0;
5695 }
5696
5697 if (!sd_json_variant_is_string(variant))
5698 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a string.", strna(name));
5699
5700 if ((flags & SD_JSON_STRICT) && !string_is_safe(sd_json_variant_string(variant), STRING_ALLOW_EMPTY|STRING_ALLOW_GLOBS))
5701 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' contains unsafe characters, refusing.", strna(name));
5702
5703 *s = sd_json_variant_string(variant);
5704 return 0;
5705 }
5706
5707 _public_ int sd_json_dispatch_strv(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5708 _cleanup_strv_free_ char **l = NULL;
5709 char ***s = userdata;
5710 sd_json_variant *e;
5711 size_t n = 0;
5712 int r;
5713
5714 assert_return(variant, -EINVAL);
5715 assert_return(userdata, -EINVAL);
5716
5717 if (sd_json_variant_is_null(variant)) {
5718 *s = strv_free(*s);
5719 return 0;
5720 }
5721
5722 /* Let's be flexible here: accept a single string in place of a single-item array */
5723 if (sd_json_variant_is_string(variant)) {
5724 if ((flags & SD_JSON_STRICT) && !string_is_safe(sd_json_variant_string(variant), STRING_ALLOW_EMPTY|STRING_ALLOW_GLOBS))
5725 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' contains unsafe characters, refusing.", strna(name));
5726
5727 l = strv_new(sd_json_variant_string(variant));
5728 if (!l)
5729 return log_oom();
5730
5731 strv_free_and_replace(*s, l);
5732 return 0;
5733 }
5734
5735 if (!sd_json_variant_is_array(variant))
5736 return json_log(variant, SYNTHETIC_ERRNO(EINVAL), flags, "JSON field '%s' is not an array.", strna(name));
5737
5738 JSON_VARIANT_ARRAY_FOREACH(e, variant) {
5739 if (!sd_json_variant_is_string(e))
5740 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "JSON array element is not a string.");
5741
5742 if ((flags & SD_JSON_STRICT) && !string_is_safe(sd_json_variant_string(e), STRING_ALLOW_EMPTY|STRING_ALLOW_GLOBS))
5743 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' contains unsafe characters, refusing.", strna(name));
5744
5745 r = strv_extend_with_size(&l, &n, sd_json_variant_string(e));
5746 if (r < 0)
5747 return json_log(e, flags, r, "Failed to append array element: %m");
5748 }
5749
5750 strv_free_and_replace(*s, l);
5751 return 0;
5752 }
5753
5754 _public_ int sd_json_dispatch_variant(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5755 sd_json_variant **p = userdata;
5756
5757 assert_return(variant, -EINVAL);
5758 assert_return(userdata, -EINVAL);
5759
5760 /* Takes a reference */
5761 JSON_VARIANT_REPLACE(*p, sd_json_variant_ref(variant));
5762 return 0;
5763 }
5764
5765 _public_ int sd_json_dispatch_variant_noref(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5766 sd_json_variant **p = userdata;
5767
5768 assert_return(variant, -EINVAL);
5769 assert_return(userdata, -EINVAL);
5770
5771 /* Doesn't take a reference */
5772 *p = variant;
5773 return 0;
5774 }
5775
5776 _public_ int sd_json_dispatch_uid_gid(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5777 uid_t *uid = userdata;
5778 uint32_t k;
5779 int r;
5780
5781 assert_return(variant, -EINVAL);
5782 assert_return(userdata, -EINVAL);
5783
5784 assert_cc(sizeof(uid_t) == sizeof(uint32_t));
5785 assert_cc(sizeof(gid_t) == sizeof(uint32_t));
5786
5787 DISABLE_WARNING_TYPE_LIMITS;
5788 assert_cc((UID_INVALID < (uid_t) 0) == (GID_INVALID < (gid_t) 0));
5789 REENABLE_WARNING;
5790
5791 if (sd_json_variant_is_null(variant)) {
5792 *uid = UID_INVALID;
5793 return 0;
5794 }
5795
5796 r = sd_json_dispatch_uint32(name, variant, flags, &k);
5797 if (r < 0)
5798 return r;
5799 if (!uid_is_valid(k))
5800 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a valid UID/GID.", strna(name));
5801
5802 *uid = k;
5803 return 0;
5804 }
5805
5806 _public_ int sd_json_dispatch_id128(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5807 sd_id128_t *uuid = userdata;
5808 int r;
5809
5810 assert_return(variant, -EINVAL);
5811 assert_return(userdata, -EINVAL);
5812
5813 if (sd_json_variant_is_null(variant)) {
5814 *uuid = SD_ID128_NULL;
5815 return 0;
5816 }
5817
5818 if (!sd_json_variant_is_string(variant))
5819 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a string.", strna(name));
5820
5821 r = sd_id128_from_string(sd_json_variant_string(variant), uuid);
5822 if (r < 0)
5823 return json_log(variant, flags, r, "JSON field '%s' is not a valid UID.", strna(name));
5824
5825 return 0;
5826 }
5827
5828 _public_ int sd_json_dispatch_signal(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5829 int *signo = userdata, r;
5830
5831 assert_return(variant, -EINVAL);
5832 assert_return(userdata, -EINVAL);
5833
5834 if (sd_json_variant_is_null(variant)) {
5835 *signo = SIGNO_INVALID;
5836 return 0;
5837 }
5838
5839 int k;
5840 if (sd_json_variant_is_string(variant)) {
5841 k = signal_from_string(sd_json_variant_string(variant));
5842 if (k < 0)
5843 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a valid signal.", strna(name));
5844 } else {
5845 r = sd_json_dispatch_int(name, variant, flags, &k);
5846 if (r < 0)
5847 return r;
5848
5849 if (!SIGNAL_VALID(k))
5850 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a valid signal.", strna(name));
5851 }
5852
5853 *signo = k;
5854 return 0;
5855 }
5856
5857 _public_ int sd_json_dispatch_unsupported(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
5858 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not allowed in this object.", strna(name));
5859 }
5860
5861 static int json_cmp_strings(const void *x, const void *y) {
5862 sd_json_variant *const *a = x, *const *b = y;
5863
5864 if (!sd_json_variant_is_string(*a) || !sd_json_variant_is_string(*b))
5865 return CMP(*a, *b);
5866
5867 return strcmp(sd_json_variant_string(*a), sd_json_variant_string(*b));
5868 }
5869
5870 _public_ int sd_json_variant_sort(sd_json_variant **v) {
5871 _cleanup_free_ sd_json_variant **a = NULL;
5872 _cleanup_(sd_json_variant_unrefp) sd_json_variant *n = NULL;
5873 size_t m;
5874 int r;
5875
5876 assert_return(v, -EINVAL);
5877
5878 if (sd_json_variant_is_sorted(*v))
5879 return 0;
5880
5881 if (!sd_json_variant_is_object(*v))
5882 return -EMEDIUMTYPE;
5883
5884 /* Sorts they key/value pairs in an object variant */
5885
5886 m = sd_json_variant_elements(*v);
5887 a = new(sd_json_variant*, m);
5888 if (!a)
5889 return -ENOMEM;
5890
5891 for (size_t i = 0; i < m; i++)
5892 a[i] = sd_json_variant_by_index(*v, i);
5893
5894 qsort(a, m/2, sizeof(sd_json_variant*)*2, json_cmp_strings);
5895
5896 r = sd_json_variant_new_object(&n, a, m);
5897 if (r < 0)
5898 return r;
5899
5900 json_variant_propagate_sensitive(*v, n);
5901
5902 if (!n->sorted) /* Check if this worked. This will fail if there are multiple identical keys used. */
5903 return -ENOTUNIQ;
5904
5905 json_variant_unref_and_replace(*v, n);
5906
5907 return 1;
5908 }
5909
5910 _public_ int sd_json_variant_normalize(sd_json_variant **v) {
5911 _cleanup_free_ sd_json_variant **a = NULL;
5912 _cleanup_(sd_json_variant_unrefp) sd_json_variant *n = NULL;
5913 size_t i, m;
5914 int r;
5915
5916 assert_return(v, -EINVAL);
5917
5918 if (sd_json_variant_is_normalized(*v))
5919 return 0;
5920
5921 if (!sd_json_variant_is_object(*v) && !sd_json_variant_is_array(*v))
5922 return -EMEDIUMTYPE;
5923
5924 /* Sorts the key/value pairs in an object variant anywhere down the tree in the specified variant */
5925
5926 m = sd_json_variant_elements(*v);
5927 a = new(sd_json_variant*, m);
5928 if (!a)
5929 return -ENOMEM;
5930
5931 for (i = 0; i < m; ) {
5932 a[i] = sd_json_variant_ref(sd_json_variant_by_index(*v, i));
5933 i++;
5934
5935 r = sd_json_variant_normalize(&a[i-1]);
5936 if (r < 0)
5937 goto finish;
5938 }
5939
5940 qsort(a, m/2, sizeof(sd_json_variant*)*2, json_cmp_strings);
5941
5942 if (sd_json_variant_is_object(*v))
5943 r = sd_json_variant_new_object(&n, a, m);
5944 else {
5945 assert(sd_json_variant_is_array(*v));
5946 r = sd_json_variant_new_array(&n, a, m);
5947 }
5948 if (r < 0)
5949 goto finish;
5950
5951 json_variant_propagate_sensitive(*v, n);
5952
5953 if (!n->normalized) { /* Let's see if normalization worked. It will fail if there are multiple
5954 * identical keys used in the same object anywhere, or if there are floating
5955 * point numbers used (see below) */
5956 r = -ENOTUNIQ;
5957 goto finish;
5958 }
5959
5960 json_variant_unref_and_replace(*v, n);
5961
5962 r = 1;
5963
5964 finish:
5965 for (size_t j = 0; j < i; j++)
5966 sd_json_variant_unref(a[j]);
5967
5968 return r;
5969 }
5970
5971 _public_ int sd_json_variant_is_normalized(sd_json_variant *v) {
5972 /* For now, let's consider anything containing numbers not expressible as integers as non-normalized.
5973 * That's because we cannot sensibly compare them due to accuracy issues, nor even store them if they
5974 * are too large. */
5975 if (sd_json_variant_is_real(v) && !sd_json_variant_is_integer(v) && !sd_json_variant_is_unsigned(v))
5976 return false;
5977
5978 /* The concept only applies to variants that include other variants, i.e. objects and arrays. All
5979 * others are normalized anyway. */
5980 if (!sd_json_variant_is_object(v) && !sd_json_variant_is_array(v))
5981 return true;
5982
5983 /* Empty objects/arrays don't include any other variant, hence are always normalized too */
5984 if (sd_json_variant_elements(v) == 0)
5985 return true;
5986
5987 return v->normalized; /* For everything else there's an explicit boolean we maintain */
5988 }
5989
5990 _public_ int sd_json_variant_is_sorted(sd_json_variant *v) {
5991
5992 /* Returns true if all key/value pairs of an object are properly sorted. Note that this only applies
5993 * to objects, not arrays. */
5994
5995 if (!sd_json_variant_is_object(v))
5996 return true;
5997 if (sd_json_variant_elements(v) <= 1)
5998 return true;
5999
6000 return v->sorted;
6001 }
6002
6003 _public_ int sd_json_variant_unbase64(sd_json_variant *v, void **ret, size_t *ret_size) {
6004 if (!sd_json_variant_is_string(v))
6005 return -EINVAL;
6006
6007 return unbase64mem_full(sd_json_variant_string(v), SIZE_MAX, /* secure= */ sd_json_variant_is_sensitive(v), ret, ret_size);
6008 }
6009
6010 _public_ int sd_json_variant_unhex(sd_json_variant *v, void **ret, size_t *ret_size) {
6011 if (!sd_json_variant_is_string(v))
6012 return -EINVAL;
6013
6014 return unhexmem_full(sd_json_variant_string(v), SIZE_MAX, /* secure= */ sd_json_variant_is_sensitive(v), ret, ret_size);
6015 }
6016
6017 static const char* const sd_json_variant_type_table[_SD_JSON_VARIANT_TYPE_MAX] = {
6018 [SD_JSON_VARIANT_STRING] = "string",
6019 [SD_JSON_VARIANT_INTEGER] = "integer",
6020 [SD_JSON_VARIANT_UNSIGNED] = "unsigned",
6021 [SD_JSON_VARIANT_REAL] = "real",
6022 [SD_JSON_VARIANT_NUMBER] = "number",
6023 [SD_JSON_VARIANT_BOOLEAN] = "boolean",
6024 [SD_JSON_VARIANT_ARRAY] = "array",
6025 [SD_JSON_VARIANT_OBJECT] = "object",
6026 [SD_JSON_VARIANT_NULL] = "null",
6027 };
6028
6029 _DEFINE_STRING_TABLE_LOOKUP(sd_json_variant_type, sd_json_variant_type_t, _public_);