]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
json: be more careful when iterating through a JSON object/array 12290/head
authorLennart Poettering <lennart@poettering.net>
Fri, 12 Apr 2019 10:59:05 +0000 (12:59 +0200)
committerLennart Poettering <lennart@poettering.net>
Fri, 12 Apr 2019 11:11:11 +0000 (13:11 +0200)
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

index 675ce2091ed031fdeb13c36530c24d3e424aa782..70dfe70dfd2e777f7ad89cc6c1f1bbb946b29939 100644 (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; });                                  \