summaryrefslogtreecommitdiffstats
path: root/src/libsystemd/sd-json/sd-json.c
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2024-05-08 09:42:12 +0200
committerLuca Boccassi <luca.boccassi@gmail.com>2024-06-15 11:58:02 +0200
commit3d6c2c918bdf59eab8edd6eda4e7ffd4efb09d33 (patch)
tree8aa4bb94cb9bac14ecfeecb92fc1406e2e8328ed /src/libsystemd/sd-json/sd-json.c
parentvarlink: handle NULL varlink server object gracefully in varlink_server_curre... (diff)
downloadsystemd-3d6c2c918bdf59eab8edd6eda4e7ffd4efb09d33.tar.xz
systemd-3d6c2c918bdf59eab8edd6eda4e7ffd4efb09d33.zip
json: extend JsonDispatch flags with nullable and refuse-null flags
currently when dispatching json objects into C structs we either insist on the field type or we don't. Let's extend this model a bit: depending on two new fields either allow or refuse null types in addition to the specified type. This is useful for example when dispatch enums as this allows us explicitly refuse null in various scenarios where we allow multiple types.
Diffstat (limited to 'src/libsystemd/sd-json/sd-json.c')
-rw-r--r--src/libsystemd/sd-json/sd-json.c20
1 files changed, 19 insertions, 1 deletions
diff --git a/src/libsystemd/sd-json/sd-json.c b/src/libsystemd/sd-json/sd-json.c
index 1316498620..f7b36af880 100644
--- a/src/libsystemd/sd-json/sd-json.c
+++ b/src/libsystemd/sd-json/sd-json.c
@@ -4656,8 +4656,10 @@ _public_ int sd_json_dispatch_full(
merged_flags = flags | p->flags;
+ /* If an explicit type is specified, verify it matches */
if (p->type != _SD_JSON_VARIANT_TYPE_INVALID &&
- !sd_json_variant_has_type(value, p->type)) {
+ !sd_json_variant_has_type(value, p->type) &&
+ !(FLAGS_SET(merged_flags, SD_JSON_NULLABLE) && sd_json_variant_is_null(value))) {
json_log(value, merged_flags, 0,
"Object field '%s' has wrong type %s, expected %s.", sd_json_variant_string(key),
@@ -4672,6 +4674,22 @@ _public_ int sd_json_dispatch_full(
return -EINVAL;
}
+ /* If the SD_JSON_REFUSE_NULL flag is specified, insist the field is not "null". Note
+ * that this provides overlapping functionality with the type check above. */
+ if (FLAGS_SET(merged_flags, SD_JSON_REFUSE_NULL) && sd_json_variant_is_null(value)) {
+
+ json_log(value, merged_flags, 0,
+ "Object field '%s' may not be null.", sd_json_variant_string(key));
+
+ if (merged_flags & SD_JSON_PERMISSIVE)
+ continue;
+
+ if (reterr_bad_field)
+ *reterr_bad_field = p->name;
+
+ return -EINVAL;
+ }
+
if (found[p-table]) {
json_log(value, merged_flags, 0, "Duplicate object field '%s'.", sd_json_variant_string(key));