From: Vladimír Čunát Date: Mon, 6 May 2019 11:00:07 +0000 (+0200) Subject: lua event.*: better safety X-Git-Tag: v4.1.0~21^2~7 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=63f5cb4dfbfd8fd2932fb8ec64007fdac58af0b7;p=thirdparty%2Fknot-resolver.git lua event.*: better safety ... when called with bad parameters, and restructure the code a bit. Note: uv_timer_start() is documented to be OK on active timers. --- diff --git a/daemon/bindings/event.c b/daemon/bindings/event.c index 32723a118..a964683bd 100644 --- a/daemon/bindings/event.c +++ b/daemon/bindings/event.c @@ -125,18 +125,20 @@ static int event_cancel(lua_State *L) /* Fetch event if it exists */ lua_rawgeti(L, LUA_REGISTRYINDEX, lua_tointeger(L, 1)); - if (!lua_istable(L, -1)) { - lua_pushboolean(L, false); - return 1; - } + bool ok = lua_istable(L, -1); /* Close the timer */ - lua_rawgeti(L, -1, 2); - uv_handle_t *timer = *(uv_handle_t **)lua_touserdata(L, -1); - if (!uv_is_closing(timer)) { - uv_close(timer, (uv_close_cb) event_free); + uv_handle_t **timer_pp = NULL; + if (ok) { + lua_rawgeti(L, -1, 2); + timer_pp = lua_touserdata(L, -1); + ok = timer_pp && *timer_pp; + /* That have been sufficient safety checks, hopefully. */ + } + if (ok && !uv_is_closing(*timer_pp)) { + uv_close(*timer_pp, (uv_close_cb)event_free); } - lua_pushboolean(L, true); + lua_pushboolean(L, ok); return 1; } @@ -148,26 +150,25 @@ static int event_reschedule(lua_State *L) /* Fetch event if it exists */ lua_rawgeti(L, LUA_REGISTRYINDEX, lua_tointeger(L, 1)); - if (!lua_istable(L, -1)) { - lua_pushboolean(L, false); - return 1; - } + bool ok = lua_istable(L, -1); /* Reschedule the timer */ - lua_rawgeti(L, -1, 2); - uv_handle_t *timer = *(uv_handle_t **)lua_touserdata(L, -1); - if (!uv_is_closing(timer)) { - if (uv_is_active(timer)) { - uv_timer_stop((uv_timer_t *)timer); - } - int ret = uv_timer_start((uv_timer_t *)timer, event_callback, lua_tointeger(L, 2), 0); + uv_handle_t **timer_pp = NULL; + if (ok) { + lua_rawgeti(L, -1, 2); + timer_pp = lua_touserdata(L, -1); + ok = timer_pp && *timer_pp; + /* That have been sufficient safety checks, hopefully. */ + } + if (ok && !uv_is_closing(*timer_pp)) { + int ret = uv_timer_start((uv_timer_t *)*timer_pp, + event_callback, lua_tointeger(L, 2), 0); if (ret != 0) { - event_cancel(L); - lua_pushboolean(L, false); - return 1; + uv_close(*timer_pp, (uv_close_cb)event_free); + ok = false; } } - lua_pushboolean(L, true); + lua_pushboolean(L, ok); return 1; }