From f034139bc0cef7725cae54ce155e09969bfa9dce Mon Sep 17 00:00:00 2001 From: Daan van Gorkum Date: Wed, 12 Jul 2023 13:11:24 +0800 Subject: [PATCH] MINOR: lua: Allow reading "proc." scoped vars from LUA core. This adds the "core.get_var()" method allow the reading of "proc." scoped variables outside of TXN or HTTP/TCPApplet. Fixes: #2212 Signed-off-by: Daan van Gorkum --- doc/lua-api/index.rst | 10 ++++++++++ src/hlua.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/doc/lua-api/index.rst b/doc/lua-api/index.rst index d2720d22c8..4f7246fecf 100644 --- a/doc/lua-api/index.rst +++ b/doc/lua-api/index.rst @@ -381,6 +381,16 @@ Core class :returns: an array of values. +.. js:function:: core.get_var() + + **context**: body, init, task, action, sample-fetch, converter + + Returns data stored in the variable converter in Lua type. + This is limited to "proc." scoped variables. + + :param string var: The variable name in "proc." scope according with the + HAProxy variable syntax. + .. js:function:: core.now() **context**: body, init, task, action diff --git a/src/hlua.c b/src/hlua.c index 0972964d9d..72081528e7 100644 --- a/src/hlua.c +++ b/src/hlua.c @@ -1965,6 +1965,33 @@ static int hlua_set_map(lua_State *L) return 0; } +/* This function is an LUA binding. It provides a function + * for retrieving a var from the proc scope in core. + */ + static int hlua_core_get_var(lua_State *L) +{ + const char *name; + size_t len; + struct sample smp; + + MAY_LJMP(check_args(L, 1, "get_var")); + + name = MAY_LJMP(luaL_checklstring(L, 1, &len)); + + /* We can only retrieve information from the proc. scope */ + /* FIXME: I didn't want to expose vars_hash_name from vars.c */ + if (len < 5 || strncmp(name, "proc.", 5) != 0) + WILL_LJMP(luaL_error(L, "'get_var': Only 'proc.' scope allowed to be retrieved in 'core.get_var()'.")); + + if (!vars_get_by_name(name, len, &smp, NULL)) { + lua_pushnil(L); + return 1; + } + + return MAY_LJMP(hlua_smp2lua(L, &smp)); + return 1; +} + /* This function disables the sending of email through the * legacy email sending function which is implemented using * checks. @@ -13209,6 +13236,7 @@ lua_State *hlua_init_state(int thread_num) hlua_class_function(L, "del_acl", hlua_del_acl); hlua_class_function(L, "set_map", hlua_set_map); hlua_class_function(L, "del_map", hlua_del_map); + hlua_class_function(L, "get_var", hlua_core_get_var); hlua_class_function(L, "tcp", hlua_socket_new); hlua_class_function(L, "httpclient", hlua_httpclient_new); hlua_class_function(L, "event_sub", hlua_event_global_sub);