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.
This commit is contained in:
Lennart Poettering 2019-04-12 12:59:05 +02:00
parent 33d60b8d57
commit 1b266e3c6f
1 changed files with 4 additions and 2 deletions

View File

@ -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; }); \