From 1b266e3c6f462dd835d3890ab4b1cb316b6fc205 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Fri, 12 Apr 2019 12:59:05 +0200 Subject: [PATCH] json: be more careful when iterating through a JSON object/array Let's exit the loop early in case the variant is not actually an object or array. This is safer since otherwise we might end up iterating through these variants and access fields that aren't of the type we expect them to be and then bad things happen. Of course, this doesn't absolve uses of these macros to check the type of the variant explicitly beforehand, but it makes it less bad if they forget to do so. --- src/shared/json.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/shared/json.h b/src/shared/json.h index 675ce2091ed..70dfe70dfd2 100644 --- a/src/shared/json.h +++ b/src/shared/json.h @@ -135,14 +135,16 @@ struct json_variant_foreach_state { #define JSON_VARIANT_ARRAY_FOREACH(i, v) \ for (struct json_variant_foreach_state _state = { (v), 0 }; \ - _state.idx < json_variant_elements(_state.variant) && \ + json_variant_is_array(_state.variant) && \ + _state.idx < json_variant_elements(_state.variant) && \ ({ i = json_variant_by_index(_state.variant, _state.idx); \ true; }); \ _state.idx++) #define JSON_VARIANT_OBJECT_FOREACH(k, e, v) \ for (struct json_variant_foreach_state _state = { (v), 0 }; \ - _state.idx < json_variant_elements(_state.variant) && \ + json_variant_is_object(_state.variant) && \ + _state.idx < json_variant_elements(_state.variant) && \ ({ k = json_variant_string(json_variant_by_index(_state.variant, _state.idx)); \ e = json_variant_by_index(_state.variant, _state.idx + 1); \ true; }); \ -- 2.47.3