From: Lennart Poettering Date: Fri, 12 Apr 2019 10:59:05 +0000 (+0200) Subject: json: be more careful when iterating through a JSON object/array X-Git-Tag: v243-rc1~556^2 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F12290%2Fhead;p=thirdparty%2Fsystemd.git 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. --- 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; }); \