blob: b5e411521f6c315a61e98e89b9c210bb33ba9664 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020054#include <haproxy/sc_strm.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010055#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020056#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020057#include <haproxy/ssl_ckch.h>
58#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020059#include <haproxy/stats-t.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020060#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010068#include <haproxy/event_hdl.h>
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +020069#include <haproxy/check.h>
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020070#include <haproxy/mailers.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010071
Tristan2632d042023-10-23 13:07:39 +010072/* Global LUA flags */
73
74enum hlua_log_opt {
75 /* tune.lua.log.loggers */
76 HLUA_LOG_LOGGERS_ON = 0x00000001, /* forward logs to current loggers */
77
78 /* tune.lua.log.stderr */
79 HLUA_LOG_STDERR_ON = 0x00000010, /* forward logs to stderr */
80 HLUA_LOG_STDERR_AUTO = 0x00000020, /* forward logs to stderr if no loggers */
81 HLUA_LOG_STDERR_MASK = 0x00000030,
82};
83/* default log options, made of flags in hlua_log_opt */
84static uint hlua_log_opts = HLUA_LOG_LOGGERS_ON | HLUA_LOG_STDERR_ON;
85
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010086/* Lua uses longjmp to perform yield or throwing errors. This
87 * macro is used only for identifying the function that can
88 * not return because a longjmp is executed.
89 * __LJMP marks a prototype of hlua file that can use longjmp.
90 * WILL_LJMP() marks an lua function that will use longjmp.
91 * MAY_LJMP() marks an lua function that may use longjmp.
92 */
93#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020094#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010095#define MAY_LJMP(func) func
96
Thierry FOURNIERbabae282015-09-17 11:36:37 +020097/* This couple of function executes securely some Lua calls outside of
98 * the lua runtime environment. Each Lua call can return a longjmp
99 * if it encounter a memory error.
100 *
101 * Lua documentation extract:
102 *
103 * If an error happens outside any protected environment, Lua calls
104 * a panic function (see lua_atpanic) and then calls abort, thus
105 * exiting the host application. Your panic function can avoid this
106 * exit by never returning (e.g., doing a long jump to your own
107 * recovery point outside Lua).
108 *
109 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +0100110 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200111 * stack. However, there is no guarantee about stack space. To push
112 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +0100113 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200114 *
115 * We must check all the Lua entry point. This includes:
116 * - The include/proto/hlua.h exported functions
117 * - the task wrapper function
118 * - The action wrapper function
119 * - The converters wrapper function
120 * - The sample-fetch wrapper functions
121 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500122 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800123 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200124 *
125 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
126 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
127 * because they must be exists in the program stack when the longjmp
128 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200129 *
130 * Note that the Lua processing is not really thread safe. It provides
131 * heavy system which consists to add our own lock function in the Lua
132 * code and recompile the library. This system will probably not accepted
133 * by maintainers of various distribs.
134 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500135 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200136 * quick looking on the Lua sources displays a lua_lock() a the start
137 * of function and a lua_unlock() at the end of the function. So I
138 * conclude that the Lua thread safe mode just perform a mutex around
139 * all execution. So I prefer to do this in the HAProxy code, it will be
140 * easier for distro maintainers.
141 *
142 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
143 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
144 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200145 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100146__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200147THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200148static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200149static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200150
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100151/* This is the chained list of struct hlua_function referenced
152 * for haproxy action, sample-fetches, converters, cli and
153 * applet bindings. It is used for a post-initialisation control.
154 */
155static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
156
Thierry Fournierc7492592020-11-28 23:57:24 +0100157/* This variable is used only during initialization to identify the Lua state
158 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
159 * states dedicated to each thread (in this case hlua_state_id==tid+1).
160 */
161static int hlua_state_id;
162
Thierry Fournier59f11be2020-11-29 00:37:41 +0100163/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200164static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100165
166lua_State *hlua_init_state(int thread_id);
167
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200168/* This function takes the Lua global lock. Keep this function's visibility
169 * global so that it can appear in stack dumps and performance profiles!
170 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100171static inline void lua_take_global_lock()
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200172{
173 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
174}
175
176static inline void lua_drop_global_lock()
177{
178 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
179}
180
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100181/* lua lock helpers: only lock when required
182 *
183 * state_id == 0: we're operating on the main lua stack (shared between
184 * os threads), so we need to acquire the main lock
185 *
186 * If the thread already owns the lock (_hlua_locked != 0), skip the lock
187 * attempt. This could happen if we run under protected lua environment.
188 * Not doing this could result in deadlocks because of nested locking
189 * attempts from the same thread
190 */
191static THREAD_LOCAL int _hlua_locked = 0;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100192static inline void hlua_lock(struct hlua *hlua)
193{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100194 if (hlua->state_id != 0)
195 return;
196 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100197 lua_take_global_lock();
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100198 _hlua_locked += 1;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100199}
200static inline void hlua_unlock(struct hlua *hlua)
201{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100202 if (hlua->state_id != 0)
203 return;
204 BUG_ON(_hlua_locked <= 0);
205 _hlua_locked--;
206 /* drop the lock once the lock count reaches 0 */
207 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100208 lua_drop_global_lock();
209}
210
Aurelien DARRAGONcf511892024-03-01 15:55:17 +0100211/* below is an helper function to retrieve string on on Lua stack at <index>
212 * in a safe way (function may not LJMP). It can be useful to retrieve errors
213 * at the top of the stack from an unprotected environment.
214 *
215 * The returned string will is only valid as long as the value at <index> is
216 * not removed from the stack.
217 *
218 * It is assumed that the calling function is allowed to manipulate <L>
219 */
220__LJMP static int _hlua_tostring_safe(lua_State *L)
221{
222 const char **str = lua_touserdata(L, 1);
223 const char *cur_str = MAY_LJMP(lua_tostring(L, 2));
224
225 if (cur_str)
226 *str = cur_str;
227 return 0;
228}
229static const char *hlua_tostring_safe(lua_State *L, int index)
230{
231 const char *str = NULL;
232
233 if (!lua_checkstack(L, 4))
234 return NULL;
235
236 /* before any stack modification, save the targeted value on the top of
237 * the stack: this will allow us to use relative index to target it.
238 */
239 lua_pushvalue(L, index);
240
241 /* push our custom _hlua_tostring_safe() function on the stack, then push
242 * our own string pointer and targeted value (at <index>) as argument
243 */
244 lua_pushcfunction(L, _hlua_tostring_safe);
245 lua_pushlightuserdata(L, &str); // 1st func argument = string pointer
246 lua_pushvalue(L, -3); // 2nd func argument = targeted value
247
248 lua_remove(L, -4); // remove <index> copy as we're done using it
249
250 /* call our custom function with proper arguments using pcall() to catch
251 * exceptions (if any)
252 */
253 switch (lua_pcall(L, 2, 0, 0)) {
254 case LUA_OK:
255 break;
256 default:
257 /* error was caught */
258 return NULL;
259 }
260 return str;
261}
262
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +0200263/* below is an helper function similar to lua_pushvfstring() to push a
264 * formatted string on Lua stack but in a safe way (function may not LJMP).
265 * It can be useful to push allocated strings (ie: error messages) on the
266 * stack and ensure proper cleanup.
267 *
268 * Returns a pointer to the internal copy of the string on success and NULL
269 * on error.
270 *
271 * It is assumed that the calling function is allowed to manipulate <L>
272 */
273__LJMP static int _hlua_pushvfstring_safe(lua_State *L)
274{
275 const char **dst = lua_touserdata(L, 1);
276 const char *fmt = lua_touserdata(L, 2);
277 va_list *argp = lua_touserdata(L, 3);
278
279 *dst = lua_pushvfstring(L, fmt, *argp);
280 return 1;
281}
282static const char *hlua_pushvfstring_safe(lua_State *L, const char *fmt, va_list argp)
283{
284 const char *dst = NULL;
285 va_list cpy_argp; /* required if argp is implemented as array type */
286
287 if (!lua_checkstack(L, 4))
288 return NULL;
289
290 va_copy(cpy_argp, argp);
291
292 /* push our custom _hlua_pushvfstring_safe() function on the stack, then
293 * push our destination string pointer, fmt and arg list
294 */
295 lua_pushcfunction(L, _hlua_pushvfstring_safe);
296 lua_pushlightuserdata(L, &dst); // 1st func argument = dst string pointer
297 lua_pushlightuserdata(L, (void *)fmt); // 2nd func argument = fmt
298 lua_pushlightuserdata(L, &cpy_argp); // 3rd func argument = arg list
299
300 /* call our custom function with proper arguments using pcall() to catch
301 * exceptions (if any)
302 */
303 switch (lua_pcall(L, 3, 1, 0)) {
304 case LUA_OK:
305 break;
306 default:
307 /* error was caught */
308 dst = NULL;
309 }
310 va_end(cpy_argp);
311
312 return dst;
313}
314
315static const char *hlua_pushfstring_safe(lua_State *L, const char *fmt, ...)
316{
317 va_list argp;
318 const char *dst;
319
320 va_start(argp, fmt);
321 dst = hlua_pushvfstring_safe(L, fmt, argp);
322 va_end(argp);
323
324 return dst;
325}
326
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100327#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200328 ({ \
329 int ret; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100330 hlua_lock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200331 if (setjmp(safe_ljmp_env) != 0) { \
332 lua_atpanic(__L, hlua_panic_safe); \
333 ret = 0; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100334 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200335 } else { \
336 lua_atpanic(__L, hlua_panic_ljmp); \
337 ret = 1; \
338 } \
339 ret; \
340 })
341
342/* If we are the last function catching Lua errors, we
343 * must reset the panic function.
344 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100345#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200346 do { \
347 lua_atpanic(__L, hlua_panic_safe); \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100348 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200349 } while(0)
350
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100351#define SET_SAFE_LJMP(__HLUA) \
352 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
353
354#define RESET_SAFE_LJMP(__HLUA) \
355 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
356
357#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100358 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100359
360#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100361 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100362
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200363/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200364#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100365/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200366#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200367/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100368#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100369#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200370
Thierry Fournierafc63e22020-11-28 17:06:51 +0100371/* The main Lua execution context. The 0 index is the
372 * common state shared by all threads.
373 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100374static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100375
Christopher Fauletc404f112020-02-26 15:03:09 +0100376#define HLUA_FLT_CB_FINAL 0x00000001
377#define HLUA_FLT_CB_RETVAL 0x00000002
378#define HLUA_FLT_CB_ARG_CHN 0x00000004
379#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
380
Christopher Faulet9f55a502020-02-25 15:21:02 +0100381#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
382
Christopher Faulet69c581a2021-05-31 08:54:04 +0200383struct hlua_reg_filter {
384 char *name;
385 int flt_ref[MAX_THREADS + 1];
386 int fun_ref[MAX_THREADS + 1];
387 struct list l;
388};
389
390struct hlua_flt_config {
391 struct hlua_reg_filter *reg;
392 int ref[MAX_THREADS + 1];
393 char **args;
394};
395
396struct hlua_flt_ctx {
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +0100397 struct hlua *_hlua; /* main hlua context */
398 int ref; /* ref to the filter lua object (in main hlua context) */
Christopher Faulet69c581a2021-05-31 08:54:04 +0200399 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
400 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
401 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
402 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
403};
404
Willy Tarreau5321da92022-05-06 11:57:34 +0200405/* appctx context used by the cosockets */
406struct hlua_csk_ctx {
407 int connected;
408 struct xref xref; /* cross reference with the Lua object owner. */
409 struct list wake_on_read;
410 struct list wake_on_write;
411 struct appctx *appctx;
Christopher Faulet26786572023-09-27 17:39:44 +0200412 struct server *srv;
Christopher Fauletcb068552023-09-27 17:34:24 +0200413 int timeout;
Willy Tarreau5321da92022-05-06 11:57:34 +0200414 int die;
415};
416
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200417/* appctx context used by TCP services */
418struct hlua_tcp_ctx {
419 struct hlua *hlua;
420 int flags;
421 struct task *task;
422};
423
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200424/* appctx context used by HTTP services */
425struct hlua_http_ctx {
426 struct hlua *hlua;
427 int left_bytes; /* The max amount of bytes that we can read. */
428 int flags;
429 int status;
430 const char *reason;
431 struct task *task;
432};
433
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200434/* used by registered CLI keywords */
435struct hlua_cli_ctx {
436 struct hlua *hlua;
437 struct task *task;
438 struct hlua_function *fcn;
439};
440
Christopher Faulet69c581a2021-05-31 08:54:04 +0200441DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
442
Christopher Faulet9f55a502020-02-25 15:21:02 +0100443static int hlua_filter_from_payload(struct filter *filter);
444
Christopher Faulet69c581a2021-05-31 08:54:04 +0200445/* This is the chained list of struct hlua_flt referenced
446 * for haproxy filters. It is used for a post-initialisation control.
447 */
448static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
449
450
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100451/* This is the memory pool containing struct lua for applets
452 * (including cli).
453 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100454DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100455
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100456/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100457static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100458static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100459#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100460static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100461#endif
462
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100463/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100464struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100465
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100466/* The following variables contains the reference of the different
467 * Lua classes. These references are useful for identify metadata
468 * associated with an object.
469 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100470static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100471static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100472static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100473static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100474static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100475static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100476static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200477static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200478static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200479static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200480static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100481static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100482
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100483/* Lua max execution timeouts. By default, stream-related
484 * lua coroutines (e.g.: actions) have a short timeout.
485 * On the other hand tasks coroutines don't have a timeout because
486 * a task may remain alive during all the haproxy execution.
487 *
488 * Timeouts are expressed in milliseconds, they are meant to be used
489 * with hlua timer's API exclusively.
490 * 0 means no timeout
491 */
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200492static uint32_t hlua_timeout_burst = 1000; /* burst timeout. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100493static uint32_t hlua_timeout_session = 4000; /* session timeout. */
494static uint32_t hlua_timeout_task = 0; /* task timeout. */
495static uint32_t hlua_timeout_applet = 4000; /* applet timeout. */
496
497/* hlua multipurpose timer:
498 * used to compute burst lua time (within a single hlua_ctx_resume())
499 * and cumulative lua time for a given coroutine, and to check
500 * the lua coroutine against the configured timeouts
501 */
502
503/* fetch per-thread cpu_time with ms precision (may wrap) */
504static inline uint32_t _hlua_time_ms()
505{
506 /* We're interested in the current cpu time in ms, which will be returned
507 * as a uint32_t to save some space.
508 * We must take the following into account:
509 *
510 * - now_cpu_time_fast() which returns the time in nanoseconds as a uint64_t
511 * will wrap every 585 years.
512 * - uint32_t may only contain 4294967295ms (~=49.7 days), so _hlua_time_ms()
513 * itself will also wrap every 49.7 days.
514 *
515 * While we can safely ignore the now_cpu_time_fast() wrap, we must
516 * take care of the uint32_t wrap by making sure to exclusively
517 * manipulate the time using uint32_t everywhere _hlua_time_ms()
518 * is involved.
519 */
520 return (uint32_t)(now_cpu_time_fast() / 1000000ULL);
521}
522
523/* computes time spent in a single lua execution (in ms) */
524static inline uint32_t _hlua_time_burst(const struct hlua_timer *timer)
525{
526 uint32_t burst_ms;
527
528 /* wrapping is expected and properly
529 * handled thanks to _hlua_time_ms() and burst_ms
530 * being of the same type
531 */
532 burst_ms = _hlua_time_ms() - timer->start;
533 return burst_ms;
534}
535
536static inline void hlua_timer_init(struct hlua_timer *timer, unsigned int max)
537{
538 timer->cumulative = 0;
539 timer->burst = 0;
540 timer->max = max;
541}
542
543/* reset the timer ctx between 2 yields */
544static inline void hlua_timer_reset(struct hlua_timer *timer)
545{
546 timer->cumulative += timer->burst;
547 timer->burst = 0;
548}
549
550/* start the timer right before a new execution */
551static inline void hlua_timer_start(struct hlua_timer *timer)
552{
553 timer->start = _hlua_time_ms();
554}
555
556/* update hlua timer when finishing an execution */
557static inline void hlua_timer_stop(struct hlua_timer *timer)
558{
559 timer->burst += _hlua_time_burst(timer);
560}
561
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200562/* check the timers for current hlua context:
563 * - first check for burst timeout (max execution time for the current
564 hlua resume, ie: time between effective yields)
565 * - then check for yield cumulative timeout
566 *
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100567 * Returns 1 if the check succeeded and 0 if it failed
568 * (ie: timeout exceeded)
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100569 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100570static inline int hlua_timer_check(const struct hlua_timer *timer)
571{
572 uint32_t pburst = _hlua_time_burst(timer); /* pending burst time in ms */
573
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200574 if (hlua_timeout_burst && (timer->burst + pburst) > hlua_timeout_burst)
575 return 0; /* burst timeout exceeded */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100576 if (timer->max && (timer->cumulative + timer->burst + pburst) > timer->max)
577 return 0; /* cumulative timeout exceeded */
578 return 1; /* ok */
579}
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100580
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100581/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
582 * it is used for preventing infinite loops.
583 *
584 * I test the scheer with an infinite loop containing one incrementation
585 * and one test. I run this loop between 10 seconds, I raise a ceil of
586 * 710M loops from one interrupt each 9000 instructions, so I fix the value
587 * to one interrupt each 10 000 instructions.
588 *
589 * configured | Number of
590 * instructions | loops executed
591 * between two | in milions
592 * forced yields |
593 * ---------------+---------------
594 * 10 | 160
595 * 500 | 670
596 * 1000 | 680
597 * 5000 | 700
598 * 7000 | 700
599 * 8000 | 700
600 * 9000 | 710 <- ceil
601 * 10000 | 710
602 * 100000 | 710
603 * 1000000 | 710
604 *
605 */
606static unsigned int hlua_nb_instruction = 10000;
607
Willy Tarreaucdb53462020-12-02 12:12:00 +0100608/* Descriptor for the memory allocation state. The limit is pre-initialised to
609 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
610 * is replaced with ~0 during post_init after everything was loaded. This way
611 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
612 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100613 */
614struct hlua_mem_allocator {
615 size_t allocated;
616 size_t limit;
617};
618
Willy Tarreaucdb53462020-12-02 12:12:00 +0100619static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100620
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100621/* hlua event subscription */
622struct hlua_event_sub {
623 int fcn_ref;
624 int state_id;
625 struct hlua *hlua;
626 struct task *task;
627 event_hdl_async_equeue equeue;
628 struct event_hdl_sub *sub;
629 uint8_t paused;
630};
631
632/* This is the memory pool containing struct hlua_event_sub
633 * for event subscriptions from lua
634 */
635DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
636
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100637/* These functions converts types between HAProxy internal args or
638 * sample and LUA types. Another function permits to check if the
639 * LUA stack contains arguments according with an required ARG_T
640 * format.
641 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200642__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100643static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100644__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100645 uint64_t mask, struct proxy *p);
Aurelien DARRAGON41217722023-05-17 10:44:47 +0200646__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp);
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +0200647__LJMP static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100648static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
649
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100650__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200651
Thierry Fournier59f11be2020-11-29 00:37:41 +0100652struct prepend_path {
653 struct list l;
654 char *type;
655 char *path;
656};
657
658static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
659
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200660#define SEND_ERR(__be, __fmt, __args...) \
661 do { \
662 send_log(__be, LOG_ERR, __fmt, ## __args); \
663 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100664 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200665 } while (0)
666
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100667static inline struct hlua_function *new_hlua_function()
668{
669 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100670 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100671
672 fcn = calloc(1, sizeof(*fcn));
673 if (!fcn)
674 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200675 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100676 for (i = 0; i < MAX_THREADS + 1; i++)
677 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100678 return fcn;
679}
680
Christopher Fauletdda44442021-04-12 14:05:43 +0200681static inline void release_hlua_function(struct hlua_function *fcn)
682{
683 if (!fcn)
684 return;
685 if (fcn->name)
686 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200687 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200688 ha_free(&fcn);
689}
690
Thierry Fournierc7492592020-11-28 23:57:24 +0100691/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
692static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
693{
694 if (fcn->function_ref[0] == -1)
695 return tid + 1;
696 return 0;
697}
698
Christopher Faulet69c581a2021-05-31 08:54:04 +0200699/* Create a new registered filter. Only its name is filled */
700static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
701{
702 struct hlua_reg_filter *reg_flt;
703 int i;
704
705 reg_flt = calloc(1, sizeof(*reg_flt));
706 if (!reg_flt)
707 return NULL;
708 reg_flt->name = strdup(name);
709 if (!reg_flt->name) {
710 free(reg_flt);
711 return NULL;
712 }
713 LIST_APPEND(&referenced_filters, &reg_flt->l);
714 for (i = 0; i < MAX_THREADS + 1; i++) {
715 reg_flt->flt_ref[i] = -1;
716 reg_flt->fun_ref[i] = -1;
717 }
718 return reg_flt;
719}
720
721/* Release a registered filter */
722static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
723{
724 if (!reg_flt)
725 return;
726 if (reg_flt->name)
727 ha_free(&reg_flt->name);
728 LIST_DELETE(&reg_flt->l);
729 ha_free(&reg_flt);
730}
731
732/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
733static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
734{
735 if (reg_flt->fun_ref[0] == -1)
736 return tid + 1;
737 return 0;
738}
739
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100740/* Used to check an Lua function type in the stack. It creates and
741 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100742 * error if the argument is not a "function".
743 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100744 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100745__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100746{
747 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100748 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100749 WILL_LJMP(luaL_argerror(L, argno, msg));
750 }
751 lua_pushvalue(L, argno);
752 return luaL_ref(L, LUA_REGISTRYINDEX);
753}
754
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100755/* Used to check an Lua table type in the stack. It creates and
756 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100757 * error if the argument is not a "table".
758 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100759 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100760__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100761{
762 if (!lua_istable(L, argno)) {
763 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
764 WILL_LJMP(luaL_argerror(L, argno, msg));
765 }
766 lua_pushvalue(L, argno);
767 return luaL_ref(L, LUA_REGISTRYINDEX);
768}
769
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100770/* Get a reference to the object that is at the top of the stack
771 * The referenced object will be popped from the stack
772 *
773 * The function returns the reference to the object which must
774 * be cleared using hlua_unref() when no longer used
775 */
776__LJMP int hlua_ref(lua_State *L)
777{
778 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
779}
780
781/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
782 * on <L> stack
783 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
784 *
785 * When the reference is no longer used, it should be released by calling
786 * hlua_unref()
787 *
788 * <L> can be from any co-routine as long as it belongs to the same lua
789 * parent state that the one used to get the reference.
790 */
791void hlua_pushref(lua_State *L, int ref)
792{
793 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
794}
795
796/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
797 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
798 *
799 * This will allow the reference to be reused and the referred object
800 * to be garbage collected.
801 *
802 * <L> can be from any co-routine as long as it belongs to the same lua
803 * parent state that the one used to get the reference.
804 */
805void hlua_unref(lua_State *L, int ref)
806{
807 luaL_unref(L, LUA_REGISTRYINDEX, ref);
808}
809
Aurelien DARRAGON5bb41752024-06-04 10:41:32 +0200810__LJMP static int _hlua_traceback(lua_State *L)
811{
812 lua_Debug *ar = lua_touserdata(L, 1);
813
814 /* Fill fields:
815 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
816 * 'l': fills in the field currentline;
817 * 'n': fills in the field name and namewhat;
818 * 't': fills in the field istailcall;
819 */
820 return lua_getinfo(L, "Slnt", ar);
821}
822
823
824/* This function cannot fail (output will simply be truncated upon errors) */
825const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200826{
827 lua_Debug ar;
828 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200829 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200830
831 while (lua_getstack(L, level++, &ar)) {
Aurelien DARRAGON5bb41752024-06-04 10:41:32 +0200832 if (!lua_checkstack(L, 2))
833 goto end; // abort
834
835 lua_pushcfunction(L, _hlua_traceback);
836 lua_pushlightuserdata(L, &ar);
837
838 /* safe getinfo */
839 switch (lua_pcall(L, 1, 1, 0)) {
840 case LUA_OK:
841 break;
842 default:
843 goto end; // abort
844 }
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200845
Willy Tarreau5c143402022-06-19 17:35:53 +0200846 /* skip these empty entries, usually they come from deep C functions */
847 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
848 continue;
849
850 /* Add separator */
851 if (b_data(msg))
852 chunk_appendf(msg, "%s", sep);
853
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200854 /* Append code localisation */
855 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100856 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200857 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100858 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200859
860 /*
861 * Get function name
862 *
863 * if namewhat is no empty, name is defined.
864 * what contains "Lua" for Lua function, "C" for C function,
865 * or "main" for main code.
866 */
867 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100868 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200869
870 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100871 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200872
873 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100874 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200875
876 else /* nothing left... */
877 chunk_appendf(msg, "?");
878
879
880 /* Display tailed call */
881 if (ar.istailcall)
882 chunk_appendf(msg, " ...");
883 }
884
Aurelien DARRAGON5bb41752024-06-04 10:41:32 +0200885 end:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200886 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200887}
888
889
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100890/* This function check the number of arguments available in the
891 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500892 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100893 */
894__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
895{
896 if (lua_gettop(L) == nb)
897 return;
898 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
899}
900
Mark Lakes22154b42018-01-29 14:38:40 -0800901/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100902 * and the line number where the error is encountered.
Aurelien DARRAGON532136d2024-06-04 13:08:59 +0200903 *
904 * It returns 1 on success and 0 on failure (function won't LJMP)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100905 */
Aurelien DARRAGON532136d2024-06-04 13:08:59 +0200906__LJMP static int _hlua_pusherror(lua_State *L)
907{
908 const char *fmt = lua_touserdata(L, 1);
909 va_list *argp = lua_touserdata(L, 2);
910
911 luaL_where(L, 2);
912 lua_pushvfstring(L, fmt, *argp);
913 lua_concat(L, 2);
914
915 return 1;
916}
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100917static int hlua_pusherror(lua_State *L, const char *fmt, ...)
918{
919 va_list argp;
Aurelien DARRAGON532136d2024-06-04 13:08:59 +0200920 int ret = 1;
921
922 if (!lua_checkstack(L, 3))
923 return 0;
924
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100925 va_start(argp, fmt);
Aurelien DARRAGON532136d2024-06-04 13:08:59 +0200926
927 /* push our custom _hlua_pusherror() function on the stack, then
928 * push fmt and arg list
929 */
930 lua_pushcfunction(L, _hlua_pusherror);
931 lua_pushlightuserdata(L, (void *)fmt); // 1st func argument = fmt
932 lua_pushlightuserdata(L, &argp); // 2nd func argument = arg list
933
934 /* call our custom function with proper arguments using pcall() to catch
935 * exceptions (if any)
936 */
937 switch (lua_pcall(L, 2, 1, 0)) {
938 case LUA_OK:
939 break;
940 default:
941 ret = 0;
942 }
943
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100944 va_end(argp);
Aurelien DARRAGON532136d2024-06-04 13:08:59 +0200945
946 return ret;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100947}
948
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100949/* This functions is used with sample fetch and converters. It
950 * converts the HAProxy configuration argument in a lua stack
951 * values.
952 *
953 * It takes an array of "arg", and each entry of the array is
954 * converted and pushed in the LUA stack.
955 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200956__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100957{
958 switch (arg->type) {
959 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100960 case ARGT_TIME:
961 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100962 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100963 break;
964
965 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200966 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100967 break;
968
969 case ARGT_IPV4:
970 case ARGT_IPV6:
971 case ARGT_MSK4:
972 case ARGT_MSK6:
973 case ARGT_FE:
974 case ARGT_BE:
975 case ARGT_TAB:
976 case ARGT_SRV:
977 case ARGT_USR:
978 case ARGT_MAP:
979 default:
980 lua_pushnil(L);
981 break;
982 }
983 return 1;
984}
985
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500986/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100987 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500988 * with sample fetch wrappers. The input arguments are given to the
989 * lua wrapper and converted as arg list by the function.
Aurelien DARRAGON0aaf6c42023-05-17 15:33:59 +0200990 *
991 * Note: although lua_tolstring() may raise a memory error according to
992 * lua documentation, in practise this could only happen when using to
993 * use lua_tolstring() on a number (lua will try to push the number as a
994 * string on the stack, and this may result in memory failure), so here we
995 * assume that hlua_lua2arg() will never raise an exception since it is
996 * exclusively used with lua string inputs.
997 *
998 * Note2: You should be extra careful when using <arg> argument, since
999 * string arguments rely on lua_tolstring() which returns a pointer to lua
1000 * object that may be garbage collected at any time when removed from lua
1001 * stack, thus you should make sure that <arg> is only used from a local
1002 * scope within lua context (and not exported or stored in a lua-independent
1003 * ctx) and that related lua object still exists when accessing arg data.
1004 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001005 */
1006static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
1007{
1008 switch (lua_type(L, ud)) {
1009
1010 case LUA_TNUMBER:
1011 case LUA_TBOOLEAN:
1012 arg->type = ARGT_SINT;
1013 arg->data.sint = lua_tointeger(L, ud);
1014 break;
1015
1016 case LUA_TSTRING:
1017 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +02001018 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +02001019 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001020 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +02001021 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001022 break;
1023
1024 case LUA_TUSERDATA:
1025 case LUA_TNIL:
1026 case LUA_TTABLE:
1027 case LUA_TFUNCTION:
1028 case LUA_TTHREAD:
1029 case LUA_TLIGHTUSERDATA:
1030 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +02001031 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001032 break;
1033 }
1034 return 1;
1035}
1036
1037/* the following functions are used to convert a struct sample
1038 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +05001039 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001040 */
Aurelien DARRAGON41217722023-05-17 10:44:47 +02001041__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001042{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001043 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001044 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001045 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001046 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001047 break;
1048
1049 case SMP_T_BIN:
1050 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001051 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001052 break;
1053
1054 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001055 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001056 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
1057 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
1058 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
1059 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
1060 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
1061 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
1062 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
1063 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
1064 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001065 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001066 break;
1067 default:
1068 lua_pushnil(L);
1069 break;
1070 }
1071 break;
1072
1073 case SMP_T_IPV4:
1074 case SMP_T_IPV6:
1075 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001076 if (sample_casts[smp->data.type][SMP_T_STR] &&
1077 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001078 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +01001079 else
1080 lua_pushnil(L);
1081 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001082 default:
1083 lua_pushnil(L);
1084 break;
1085 }
1086 return 1;
1087}
1088
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001089/* the following functions are used to convert a struct sample
1090 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +05001091 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001092 */
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02001093__LJMP static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001094{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001095 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001096
1097 case SMP_T_BIN:
1098 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001099 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001100 break;
1101
1102 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001103 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001104 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
1105 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
1106 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
1107 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
1108 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
1109 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
1110 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
1111 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
1112 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001113 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001114 break;
1115 default:
1116 lua_pushstring(L, "");
1117 break;
1118 }
1119 break;
1120
1121 case SMP_T_SINT:
1122 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001123 case SMP_T_IPV4:
1124 case SMP_T_IPV6:
1125 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001126 if (sample_casts[smp->data.type][SMP_T_STR] &&
1127 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001128 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001129 else
1130 lua_pushstring(L, "");
1131 break;
1132 default:
1133 lua_pushstring(L, "");
1134 break;
1135 }
1136 return 1;
1137}
1138
Aurelien DARRAGONa3624cb2023-05-17 15:44:45 +02001139/* The following function is used to convert a Lua type to a
1140 * struct sample. This is useful to provide data from LUA code to
1141 * a converter.
1142 *
1143 * Note: although lua_tolstring() may raise a memory error according to
1144 * lua documentation, in practise this could only happen when using to
1145 * use lua_tolstring() on a number (lua will try to push the number as a
1146 * string on the stack, and this may result in memory failure), so here we
1147 * assume that hlua_lua2arg() will never raise an exception since it is
1148 * exclusively used with lua string inputs.
1149 *
1150 * Note2: You should be extra careful when using <smp> argument, since
1151 * string arguments rely on lua_tolstring() which returns a pointer to lua
1152 * object that may be garbage collected at any time when removed from lua
1153 * stack, thus you should make sure that <smp> is only used from a local
1154 * scope within lua context (not exported or stored in a lua-independent
1155 * ctx) and that related lua object still exists when accessing arg data.
1156 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
1157 *
1158 * If you don't comply with this usage restriction, then you should consider
1159 * duplicating the smp using smp_dup() to make it portable (little overhead),
1160 * as this will ensure that the smp always points to valid memory block.
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001161 */
1162static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
1163{
1164 switch (lua_type(L, ud)) {
1165
1166 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001167 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001168 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001169 break;
1170
1171
1172 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001173 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001174 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001175 break;
1176
1177 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001178 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001179 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +02001180 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +02001181 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001182 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +02001183 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001184 break;
1185
1186 case LUA_TUSERDATA:
1187 case LUA_TNIL:
1188 case LUA_TTABLE:
1189 case LUA_TFUNCTION:
1190 case LUA_TTHREAD:
1191 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +02001192 case LUA_TNONE:
1193 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001194 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001195 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001196 break;
1197 }
1198 return 1;
1199}
1200
Ilya Shipitsind4259502020-04-08 01:07:56 +05001201/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001202 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001203 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001204 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001205 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +02001206 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001207 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001208__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +01001209 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001210{
1211 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001212 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001213 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +02001214 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001215 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001216 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001217 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001218
1219 idx = 0;
1220 min_arg = ARGM(mask);
1221 mask >>= ARGM_BITS;
1222
1223 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001224 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001225
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001226 /* Check for mandatory arguments. */
1227 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001228 if (idx < min_arg) {
1229
1230 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001231 if (idx > 0) {
1232 msg = "Mandatory argument expected";
1233 goto error;
1234 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001235
1236 /* If first argument have a certain type, some default values
1237 * may be used. See the function smp_resolve_args().
1238 */
1239 switch (mask & ARGT_MASK) {
1240
1241 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001242 if (!(p->cap & PR_CAP_FE)) {
1243 msg = "Mandatory argument expected";
1244 goto error;
1245 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001246 argp[idx].data.prx = p;
1247 argp[idx].type = ARGT_FE;
1248 argp[idx+1].type = ARGT_STOP;
1249 break;
1250
1251 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001252 if (!(p->cap & PR_CAP_BE)) {
1253 msg = "Mandatory argument expected";
1254 goto error;
1255 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001256 argp[idx].data.prx = p;
1257 argp[idx].type = ARGT_BE;
1258 argp[idx+1].type = ARGT_STOP;
1259 break;
1260
1261 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001262 if (!p->table) {
1263 msg = "Mandatory argument expected";
1264 goto error;
1265 }
1266 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001267 argp[idx].type = ARGT_TAB;
1268 argp[idx+1].type = ARGT_STOP;
1269 break;
1270
1271 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001272 msg = "Mandatory argument expected";
1273 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001274 break;
1275 }
1276 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001277 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001278 }
1279
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001280 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001281 if ((mask & ARGT_MASK) == ARGT_STOP &&
1282 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001283 msg = "Last argument expected";
1284 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001285 }
1286
1287 if ((mask & ARGT_MASK) == ARGT_STOP &&
1288 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001289 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001290 }
1291
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001292 /* Convert some argument types. All string in argp[] are for not
1293 * duplicated yet.
1294 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001295 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001296 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001297 if (argp[idx].type != ARGT_SINT) {
1298 msg = "integer expected";
1299 goto error;
1300 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001301 argp[idx].type = ARGT_SINT;
1302 break;
1303
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001304 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001305 if (argp[idx].type != ARGT_SINT) {
1306 msg = "integer expected";
1307 goto error;
1308 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001309 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001310 break;
1311
1312 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001313 if (argp[idx].type != ARGT_SINT) {
1314 msg = "integer expected";
1315 goto error;
1316 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001317 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001318 break;
1319
1320 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001321 if (argp[idx].type != ARGT_STR) {
1322 msg = "string expected";
1323 goto error;
1324 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001325 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001326 if (!argp[idx].data.prx) {
1327 msg = "frontend doesn't exist";
1328 goto error;
1329 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001330 argp[idx].type = ARGT_FE;
1331 break;
1332
1333 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001334 if (argp[idx].type != ARGT_STR) {
1335 msg = "string expected";
1336 goto error;
1337 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001338 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001339 if (!argp[idx].data.prx) {
1340 msg = "backend doesn't exist";
1341 goto error;
1342 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001343 argp[idx].type = ARGT_BE;
1344 break;
1345
1346 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001347 if (argp[idx].type != ARGT_STR) {
1348 msg = "string expected";
1349 goto error;
1350 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001351 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001352 if (!argp[idx].data.t) {
1353 msg = "table doesn't exist";
1354 goto error;
1355 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001356 argp[idx].type = ARGT_TAB;
1357 break;
1358
1359 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001360 if (argp[idx].type != ARGT_STR) {
1361 msg = "string expected";
1362 goto error;
1363 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001364 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001365 if (sname) {
1366 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001367 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001368 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001369 if (!px) {
1370 msg = "backend doesn't exist";
1371 goto error;
1372 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001373 }
1374 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001375 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001376 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001377 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001378 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001379 if (!argp[idx].data.srv) {
1380 msg = "server doesn't exist";
1381 goto error;
1382 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001383 argp[idx].type = ARGT_SRV;
1384 break;
1385
1386 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001387 if (argp[idx].type != ARGT_STR) {
1388 msg = "string expected";
1389 goto error;
1390 }
1391 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1392 msg = "invalid IPv4 address";
1393 goto error;
1394 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001395 argp[idx].type = ARGT_IPV4;
1396 break;
1397
1398 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001399 if (argp[idx].type == ARGT_SINT)
1400 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1401 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001402 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1403 msg = "invalid IPv4 mask";
1404 goto error;
1405 }
1406 }
1407 else {
1408 msg = "integer or string expected";
1409 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001410 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001411 argp[idx].type = ARGT_MSK4;
1412 break;
1413
1414 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001415 if (argp[idx].type != ARGT_STR) {
1416 msg = "string expected";
1417 goto error;
1418 }
1419 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1420 msg = "invalid IPv6 address";
1421 goto error;
1422 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001423 argp[idx].type = ARGT_IPV6;
1424 break;
1425
1426 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001427 if (argp[idx].type == ARGT_SINT)
1428 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1429 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001430 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1431 msg = "invalid IPv6 mask";
1432 goto error;
1433 }
1434 }
1435 else {
1436 msg = "integer or string expected";
1437 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001438 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001439 argp[idx].type = ARGT_MSK6;
1440 break;
1441
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001442 case ARGT_REG:
1443 if (argp[idx].type != ARGT_STR) {
1444 msg = "string expected";
1445 goto error;
1446 }
1447 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1448 if (!reg) {
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02001449 msg = hlua_pushfstring_safe(L, "error compiling regex '%s' : '%s'",
1450 argp[idx].data.str.area, err);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001451 free(err);
1452 goto error;
1453 }
1454 argp[idx].type = ARGT_REG;
1455 argp[idx].data.reg = reg;
1456 break;
1457
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001458 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001459 if (argp[idx].type != ARGT_STR) {
1460 msg = "string expected";
1461 goto error;
1462 }
1463 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001464 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001465 ul = p->uri_auth->userlist;
1466 else
1467 ul = auth_find_userlist(argp[idx].data.str.area);
1468
1469 if (!ul) {
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02001470 msg = hlua_pushfstring_safe(L, "unable to find userlist '%s'",
1471 argp[idx].data.str.area);
Christopher Fauletd25d9262020-08-06 11:04:46 +02001472 goto error;
1473 }
1474 argp[idx].type = ARGT_USR;
1475 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001476 break;
1477
1478 case ARGT_STR:
1479 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1480 msg = "unable to duplicate string arg";
1481 goto error;
1482 }
1483 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001484 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001485
Christopher Fauletd25d9262020-08-06 11:04:46 +02001486 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001487 msg = "type not yet supported";
1488 goto error;
1489 break;
1490
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001491 }
1492
1493 /* Check for type of argument. */
1494 if ((mask & ARGT_MASK) != argp[idx].type) {
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02001495 msg = hlua_pushfstring_safe(L, "'%s' expected, got '%s'",
1496 arg_type_names[(mask & ARGT_MASK)],
1497 arg_type_names[argp[idx].type & ARGT_MASK]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001498 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001499 }
1500
1501 /* Next argument. */
1502 mask >>= ARGT_BITS;
1503 idx++;
1504 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001505 return 0;
1506
1507 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001508 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001509 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001510 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1511 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001512}
1513
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001515 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001516 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001517 *
1518 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001519 * - hlua_sethlua : create the association between hlua context and lua_state.
1520 */
Aurelien DARRAGON40cd44f2023-05-04 13:59:48 +02001521inline struct hlua *hlua_gethlua(lua_State *L)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001522{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001523 struct hlua **hlua = lua_getextraspace(L);
1524 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001525}
1526static inline void hlua_sethlua(struct hlua *hlua)
1527{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001528 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1529 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001530}
1531
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001532/* Will return a non-NULL string indicating the Lua call trace if the caller
1533 * currently is executing from within a Lua function. One line per entry will
1534 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1535 * Lua function is not detected, NULL is returned.
1536 */
1537const char *hlua_show_current_location(const char *pfx)
1538{
1539 lua_State *L;
1540 lua_Debug ar;
1541
1542 /* global or per-thread stack initializing ? */
1543 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1544 return hlua_traceback(L, pfx);
1545
1546 /* per-thread stack running ? */
1547 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1548 return hlua_traceback(L, pfx);
1549
1550 /* global stack running ? */
1551 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1552 return hlua_traceback(L, pfx);
1553
1554 return NULL;
1555}
1556
Tristan2632d042023-10-23 13:07:39 +01001557/* This function is used to send logs. It tries to send them to:
1558 * - the log target applicable in the current context, AND
1559 * - stderr if not in quiet mode or explicitly disabled
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001560 */
1561static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1562{
1563 struct tm tm;
1564 char *p;
1565
1566 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001567 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001568 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001569 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001570 /* Break the message if exceed the buffer size. */
1571 *(p-4) = ' ';
1572 *(p-3) = '.';
1573 *(p-2) = '.';
1574 *(p-1) = '.';
1575 break;
1576 }
Willy Tarreau90807112020-02-25 08:16:33 +01001577 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001578 *p = *msg;
1579 else
1580 *p = '.';
1581 }
1582 *p = '\0';
1583
Tristan2632d042023-10-23 13:07:39 +01001584 if (hlua_log_opts & HLUA_LOG_LOGGERS_ON)
1585 send_log(px, level, "%s\n", trash.area);
1586
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001587 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Tristan2632d042023-10-23 13:07:39 +01001588 if (!(hlua_log_opts & HLUA_LOG_STDERR_MASK))
1589 return;
1590
1591 /* when logging via stderr is set to 'auto', it behaves like 'off' unless one of:
1592 * - logging via loggers is disabled
1593 * - this is a non-proxy context and there is no global logger configured
1594 * - this is a proxy context and the proxy has no logger configured
1595 */
1596 if ((hlua_log_opts & (HLUA_LOG_STDERR_MASK | HLUA_LOG_LOGGERS_ON)) == (HLUA_LOG_STDERR_AUTO | HLUA_LOG_LOGGERS_ON)) {
1597 /* AUTO=OFF in non-proxy context only if at least one global logger is defined */
1598 if ((px == NULL) && (!LIST_ISEMPTY(&global.logsrvs)))
1599 return;
1600
1601 /* AUTO=OFF in proxy context only if at least one logger is configured for the proxy */
1602 if ((px != NULL) && (!LIST_ISEMPTY(&px->logsrvs)))
1603 return;
1604 }
1605
Christopher Fauletf98d8212020-10-02 18:13:52 +02001606 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1607 return;
1608
Willy Tarreaua678b432015-08-28 10:14:59 +02001609 get_localtime(date.tv_sec, &tm);
1610 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001611 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001612 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001613 fflush(stderr);
1614 }
1615}
1616
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001617/* This function just ensure that the yield will be always
1618 * returned with a timeout and permit to set some flags
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02001619 * <timeout> is a tick value
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001620 */
Aurelien DARRAGONbcdf07e2023-07-13 10:18:04 +02001621__LJMP void hlua_yieldk(lua_State *L, int nresults, lua_KContext ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001622 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001623{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001624 struct hlua *hlua;
1625
1626 /* Get hlua struct, or NULL if we execute from main lua state */
1627 hlua = hlua_gethlua(L);
1628 if (!hlua) {
1629 return;
1630 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001631
1632 /* Set the wake timeout. If timeout is required, we set
1633 * the expiration time.
1634 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001635 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001636
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001637 hlua->flags |= flags;
1638
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001639 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001640 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001641}
1642
Willy Tarreau87b09662015-04-03 00:22:06 +02001643/* This function initialises the Lua environment stored in the stream.
1644 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001645 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001646 *
1647 * This function is particular. it initialises a new Lua thread. If the
1648 * initialisation fails (example: out of memory error), the lua function
1649 * throws an error (longjmp).
1650 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001651 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001652 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001653 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001654 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001655 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001656int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001657{
1658 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001659 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001660 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001661 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001662 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001663 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001664 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001665 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001666 if (!SET_SAFE_LJMP_PARENT(lua)) {
1667 lua->Tref = LUA_REFNIL;
1668 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001669 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001670 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001671 if (!lua->T) {
1672 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001673 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001674 return 0;
1675 }
1676 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001677 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001678 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001679 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001680 return 1;
1681}
1682
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001683/* kill all associated httpclient to this hlua task
1684 * We must take extra precautions as we're manipulating lua-exposed
1685 * objects without the main lua lock.
1686 */
William Lallemandbb581422022-10-20 10:57:28 +02001687static void hlua_httpclient_destroy_all(struct hlua *hlua)
1688{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001689 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001690
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001691 /* use thread-safe accessors for hc_list since GC cycle initiated by
1692 * another thread sharing the same main lua stack (lua coroutine)
1693 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1694 * in parallel: Lua GC applies on the main stack, it is not limited to
1695 * a single coroutine stack, see Github issue #2037 for reference.
1696 * Remember, coroutines created using lua_newthread() are not meant to
1697 * be thread safe in Lua. (From lua co-author:
1698 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1699 *
1700 * This security measure is superfluous when 'lua-load-per-thread' is used
1701 * since in this case coroutines exclusively run on the same thread
1702 * (main stack is not shared between OS threads).
1703 */
1704 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1705 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001706 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001707 }
1708}
1709
1710
Willy Tarreau87b09662015-04-03 00:22:06 +02001711/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001712 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001713 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001714 */
1715void hlua_ctx_destroy(struct hlua *lua)
1716{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001717 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001718 return;
1719
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001720 if (!lua->T)
1721 goto end;
1722
William Lallemandbb581422022-10-20 10:57:28 +02001723 /* clean all running httpclient */
1724 hlua_httpclient_destroy_all(lua);
1725
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001726 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001727 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001728
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001729 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001730 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001731 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001732 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001733
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001734 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001735 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001736 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001737 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001738 /* Forces a garbage collecting process. If the Lua program is finished
1739 * without error, we run the GC on the thread pointer. Its freed all
1740 * the unused memory.
1741 * If the thread is finnish with an error or is currently yielded,
1742 * it seems that the GC applied on the thread doesn't clean anything,
1743 * so e run the GC on the main thread.
1744 * NOTE: maybe this action locks all the Lua threads untiml the en of
1745 * the garbage collection.
1746 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001747 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001748 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001749 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001750 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001751 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001752 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001753
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001754 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001755
1756end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001757 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001758}
1759
1760/* This function is used to restore the Lua context when a coroutine
1761 * fails. This function copy the common memory between old coroutine
1762 * and the new coroutine. The old coroutine is destroyed, and its
1763 * replaced by the new coroutine.
1764 * If the flag "keep_msg" is set, the last entry of the old is assumed
1765 * as string error message and it is copied in the new stack.
1766 */
1767static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1768{
1769 lua_State *T;
1770 int new_ref;
1771
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001772 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001773 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001774 if (!T)
1775 return 0;
1776
1777 /* Copy last error message. */
1778 if (keep_msg)
1779 lua_xmove(lua->T, T, 1);
1780
1781 /* Copy data between the coroutines. */
1782 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1783 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001784 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001785
1786 /* Destroy old data. */
1787 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1788
1789 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001790 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001791
1792 /* Fill the struct with the new coroutine values. */
1793 lua->Mref = new_ref;
1794 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001795 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001796
1797 /* Set context. */
1798 hlua_sethlua(lua);
1799
1800 return 1;
1801}
1802
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01001803/* Helper function to get the lua ctx for a given stream and state_id */
1804static inline struct hlua *hlua_stream_ctx_get(struct stream *s, int state_id)
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01001805{
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01001806 /* state_id == 0 -> global runtime ctx
1807 * state_id != 0 -> per-thread runtime ctx
1808 */
1809 return s->hlua[!!state_id];
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01001810}
1811
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01001812/* Helper function to prepare the lua ctx for a given stream and state id
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01001813 *
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01001814 * It uses the global or per-thread ctx depending on the expected
1815 * <state_id>.
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01001816 *
1817 * Returns hlua ctx on success and NULL on failure
1818 */
1819static struct hlua *hlua_stream_ctx_prepare(struct stream *s, int state_id)
1820{
1821 /* In the execution wrappers linked with a stream, the
1822 * Lua context can be not initialized. This behavior
1823 * permits to save performances because a systematic
1824 * Lua initialization cause 5% performances loss.
1825 */
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01001826 if (!s->hlua[!!state_id]) {
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01001827 struct hlua *hlua;
1828
1829 hlua = pool_alloc(pool_head_hlua);
1830 if (!hlua)
1831 return NULL;
1832 HLUA_INIT(hlua);
1833 if (!hlua_ctx_init(hlua, state_id, s->task)) {
1834 pool_free(pool_head_hlua, hlua);
1835 return NULL;
1836 }
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01001837 s->hlua[!!state_id] = hlua;
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01001838 }
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01001839 return s->hlua[!!state_id];
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01001840}
1841
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001842void hlua_hook(lua_State *L, lua_Debug *ar)
1843{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001844 struct hlua *hlua;
1845
1846 /* Get hlua struct, or NULL if we execute from main lua state */
1847 hlua = hlua_gethlua(L);
1848 if (!hlua)
1849 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001850
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001851 if (hlua->T != L) {
1852 /* We don't want to enforce a yield on a sub coroutine, since
1853 * we have no guarantees that the yield will be handled properly.
1854 * Indeed, only the hlua->T coroutine is being handled through
1855 * hlua_ctx_resume() function.
1856 *
1857 * Instead, we simply check for timeouts and wait for the sub
1858 * coroutine to finish..
1859 */
1860 goto check_timeout;
1861 }
1862
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001863 /* Lua cannot yield when its returning from a function,
1864 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001865 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001866 */
1867 if (lua_gethookmask(L) & LUA_MASKRET) {
1868 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1869 return;
1870 }
1871
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001872 /* If we interrupt the Lua processing in yieldable state, we yield.
1873 * If the state is not yieldable, trying yield causes an error.
1874 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001875 if (lua_isyieldable(L)) {
1876 /* note: for converters/fetches.. where yielding is not allowed
1877 * hlua_ctx_resume() will simply perform a goto resume_execution
1878 * instead of rescheduling hlua->task.
1879 * also: hlua_ctx_resume() will take care of checking execution
1880 * timeout and re-applying the hook as needed.
1881 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001882 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001883 /* lua docs says that the hook should return immediately after lua_yieldk
1884 *
1885 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1886 *
1887 * Moreover, it seems that we don't want to continue after the yield
1888 * because the end of the function is about handling unyieldable function,
1889 * which is not the case here.
1890 *
1891 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1892 * in the function.
1893 */
1894 return;
1895 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001896
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001897 check_timeout:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001898 /* If we cannot yield, check the timeout. */
1899 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001900 lua_pushfstring(L, "execution timeout");
1901 WILL_LJMP(lua_error(L));
1902 }
1903
1904 /* Try to interrupt the process at the end of the current
1905 * unyieldable function.
1906 */
1907 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001908}
1909
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001910/* This function start or resumes the Lua stack execution. If the flag
1911 * "yield_allowed" if no set and the LUA stack execution returns a yield
1912 * The function return an error.
1913 *
1914 * The function can returns 4 values:
1915 * - HLUA_E_OK : The execution is terminated without any errors.
1916 * - HLUA_E_AGAIN : The execution must continue at the next associated
1917 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001918 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001919 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001920 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001921 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001922 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001923 * LUA code.
1924 */
1925static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1926{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001927#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1928 int nres;
1929#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001930 int ret;
1931 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001932 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001933
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001934 /* Lock the whole Lua execution. This lock must be before the
1935 * label "resume_execution".
1936 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001937 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001938
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001939 /* reset the timer as we might be re-entering the function to
1940 * resume the coroutine after a successful yield
1941 * (cumulative time will be updated)
1942 */
1943 hlua_timer_reset(&lua->timer);
1944
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001945resume_execution:
1946
1947 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1948 * instructions. it is used for preventing infinite loops.
1949 */
1950 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1951
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001952 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001953 HLUA_SET_RUN(lua);
1954 HLUA_CLR_CTRLYIELD(lua);
1955 HLUA_CLR_WAKERESWR(lua);
1956 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001957 HLUA_CLR_NOYIELD(lua);
1958 if (!yield_allowed)
1959 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001960
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001961 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001962 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001963
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001964 /* start the timer as we're about to start lua processing */
1965 hlua_timer_start(&lua->timer);
1966
Aurelien DARRAGON4796ace2024-03-12 00:22:44 +01001967 HLUA_SET_BUSY(lua);
1968
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001969 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001970#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001971 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001972#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001973 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001974#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001975
Aurelien DARRAGON4796ace2024-03-12 00:22:44 +01001976 HLUA_CLR_BUSY(lua);
1977
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001978 /* out of lua processing, stop the timer */
1979 hlua_timer_stop(&lua->timer);
1980
Aurelien DARRAGONfa76a102023-09-08 14:00:27 +02001981 /* reset nargs because those possibly passed to the lua_resume() call
1982 * were already consumed, and since we may call lua_resume() again
1983 * after a successful yield, we don't want to pass stale nargs hint
1984 * to the Lua API. As such, nargs should be set explicitly before each
1985 * lua_resume() (or hlua_ctx_resume()) invocation if needed.
1986 */
1987 lua->nargs = 0;
1988
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001989 switch (ret) {
1990
1991 case LUA_OK:
1992 ret = HLUA_E_OK;
1993 break;
1994
1995 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001996 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001997 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001998 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001999 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01002000 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02002001 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01002002 break;
2003 }
2004 /* Process the forced yield. if the general yield is not allowed or
2005 * if no task were associated this the current Lua execution
2006 * coroutine, we resume the execution. Else we want to return in the
2007 * scheduler and we want to be waked up again, to continue the
2008 * current Lua execution. So we schedule our own task.
2009 */
2010 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01002011 if (!yield_allowed || !lua->task)
2012 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01002013 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01002014 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002015 if (!yield_allowed) {
2016 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02002017 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002018 break;
2019 }
2020 ret = HLUA_E_AGAIN;
2021 break;
2022
2023 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02002024
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002025 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02002026 * because the errors ares the only one mean to return immediately
2027 * from and lua execution.
2028 */
2029 if (lua->flags & HLUA_EXIT) {
2030 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01002031 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02002032 break;
2033 }
2034
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01002035 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002036 if (!lua_checkstack(lua->T, 1)) {
2037 ret = HLUA_E_ERR;
2038 break;
2039 }
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01002040 msg = hlua_tostring_safe(lua->T, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01002041 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002042 if (msg)
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02002043 hlua_pushfstring_safe(lua->T, "[state-id %d] runtime error: %s from %s",
2044 lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002045 else
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02002046 hlua_pushfstring_safe(lua->T, "[state-id %d] unknown runtime error from %s",
2047 lua->state_id, trace);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +01002048
Aurelien DARRAGON96e7b772024-06-04 15:52:23 +02002049 /* Move the error msg at the bottom and then empty the stack except last msg */
2050 lua_insert(lua->T, 1);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +01002051 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002052 ret = HLUA_E_ERRMSG;
2053 break;
2054
2055 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01002056 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002057 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02002058 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002059 break;
2060
2061 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01002062 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002063 if (!lua_checkstack(lua->T, 1)) {
2064 ret = HLUA_E_ERR;
2065 break;
2066 }
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01002067 msg = hlua_tostring_safe(lua->T, -1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002068 if (msg)
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02002069 hlua_pushfstring_safe(lua->T, "[state-id %d] message handler error: %s",
2070 lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002071 else
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02002072 hlua_pushfstring_safe(lua->T, "[state-id %d] message handler error",
2073 lua->state_id);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +01002074
Aurelien DARRAGON96e7b772024-06-04 15:52:23 +02002075 /* Move the error msg at the bottom and then empty the stack except last msg */
2076 lua_insert(lua->T, 1);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +01002077 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002078 ret = HLUA_E_ERRMSG;
2079 break;
2080
2081 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01002082 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002083 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02002084 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002085 break;
2086 }
2087
2088 switch (ret) {
2089 case HLUA_E_AGAIN:
2090 break;
2091
2092 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002093 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002094 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002095 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002096 break;
2097
Thierry Fournierd5b073c2018-05-21 19:42:47 +02002098 case HLUA_E_ETMOUT:
2099 case HLUA_E_NOMEM:
2100 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002101 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002102 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002103 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002104 hlua_ctx_renew(lua, 0);
2105 break;
2106
2107 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002108 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002109 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002110 break;
2111 }
2112
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02002113 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01002114 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02002115
Thierry FOURNIER380d0932015-01-23 14:27:52 +01002116 return ret;
2117}
2118
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02002119/* This function exit the current code. */
2120__LJMP static int hlua_done(lua_State *L)
2121{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002122 struct hlua *hlua;
2123
2124 /* Get hlua struct, or NULL if we execute from main lua state */
2125 hlua = hlua_gethlua(L);
2126 if (!hlua)
2127 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02002128
2129 hlua->flags |= HLUA_EXIT;
2130 WILL_LJMP(lua_error(L));
2131
2132 return 0;
2133}
2134
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002135/* This function is an LUA binding. It provides a function
2136 * for deleting ACL from a referenced ACL file.
2137 */
2138__LJMP static int hlua_del_acl(lua_State *L)
2139{
2140 const char *name;
2141 const char *key;
2142 struct pat_ref *ref;
2143
2144 MAY_LJMP(check_args(L, 2, "del_acl"));
2145
2146 name = MAY_LJMP(luaL_checkstring(L, 1));
2147 key = MAY_LJMP(luaL_checkstring(L, 2));
2148
2149 ref = pat_ref_lookup(name);
2150 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02002151 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002152
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002153 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002154 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002155 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002156 return 0;
2157}
2158
2159/* This function is an LUA binding. It provides a function
2160 * for deleting map entry from a referenced map file.
2161 */
2162static int hlua_del_map(lua_State *L)
2163{
2164 const char *name;
2165 const char *key;
2166 struct pat_ref *ref;
2167
2168 MAY_LJMP(check_args(L, 2, "del_map"));
2169
2170 name = MAY_LJMP(luaL_checkstring(L, 1));
2171 key = MAY_LJMP(luaL_checkstring(L, 2));
2172
2173 ref = pat_ref_lookup(name);
2174 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02002175 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002176
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002177 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002178 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002179 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002180 return 0;
2181}
2182
2183/* This function is an LUA binding. It provides a function
2184 * for adding ACL pattern from a referenced ACL file.
2185 */
2186static int hlua_add_acl(lua_State *L)
2187{
2188 const char *name;
2189 const char *key;
2190 struct pat_ref *ref;
2191
2192 MAY_LJMP(check_args(L, 2, "add_acl"));
2193
2194 name = MAY_LJMP(luaL_checkstring(L, 1));
2195 key = MAY_LJMP(luaL_checkstring(L, 2));
2196
2197 ref = pat_ref_lookup(name);
2198 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02002199 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002200
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002201 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002202 if (pat_ref_find_elt(ref, key) == NULL)
2203 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002204 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002205 return 0;
2206}
2207
2208/* This function is an LUA binding. It provides a function
2209 * for setting map pattern and sample from a referenced map
2210 * file.
2211 */
2212static int hlua_set_map(lua_State *L)
2213{
2214 const char *name;
2215 const char *key;
2216 const char *value;
2217 struct pat_ref *ref;
2218
2219 MAY_LJMP(check_args(L, 3, "set_map"));
2220
2221 name = MAY_LJMP(luaL_checkstring(L, 1));
2222 key = MAY_LJMP(luaL_checkstring(L, 2));
2223 value = MAY_LJMP(luaL_checkstring(L, 3));
2224
2225 ref = pat_ref_lookup(name);
2226 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02002227 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002228
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002229 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002230 if (pat_ref_find_elt(ref, key) != NULL)
2231 pat_ref_set(ref, key, value, NULL);
2232 else
2233 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002234 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002235 return 0;
2236}
2237
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +02002238/* This function disables the sending of email through the
2239 * legacy email sending function which is implemented using
2240 * checks.
2241 *
2242 * It may not be used during runtime.
2243 */
2244__LJMP static int hlua_disable_legacy_mailers(lua_State *L)
2245{
2246 if (hlua_gethlua(L))
2247 WILL_LJMP(luaL_error(L, "disable_legacy_mailers: "
2248 "not available outside of init or body context"));
2249 send_email_disabled = 1;
2250 return 0;
2251}
2252
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002253/* A class is a lot of memory that contain data. This data can be a table,
2254 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002255 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002256 * the name of the object (_G[<name>] = <metable> ).
2257 *
2258 * A metable is a table that modify the standard behavior of a standard
2259 * access to the associated data. The entries of this new metatable are
2260 * defined as is:
2261 *
2262 * http://lua-users.org/wiki/MetatableEvents
2263 *
2264 * __index
2265 *
2266 * we access an absent field in a table, the result is nil. This is
2267 * true, but it is not the whole truth. Actually, such access triggers
2268 * the interpreter to look for an __index metamethod: If there is no
2269 * such method, as usually happens, then the access results in nil;
2270 * otherwise, the metamethod will provide the result.
2271 *
2272 * Control 'prototype' inheritance. When accessing "myTable[key]" and
2273 * the key does not appear in the table, but the metatable has an __index
2274 * property:
2275 *
2276 * - if the value is a function, the function is called, passing in the
2277 * table and the key; the return value of that function is returned as
2278 * the result.
2279 *
2280 * - if the value is another table, the value of the key in that table is
2281 * asked for and returned (and if it doesn't exist in that table, but that
2282 * table's metatable has an __index property, then it continues on up)
2283 *
2284 * - Use "rawget(myTable,key)" to skip this metamethod.
2285 *
2286 * http://www.lua.org/pil/13.4.1.html
2287 *
2288 * __newindex
2289 *
2290 * Like __index, but control property assignment.
2291 *
2292 * __mode - Control weak references. A string value with one or both
2293 * of the characters 'k' and 'v' which specifies that the the
2294 * keys and/or values in the table are weak references.
2295 *
2296 * __call - Treat a table like a function. When a table is followed by
2297 * parenthesis such as "myTable( 'foo' )" and the metatable has
2298 * a __call key pointing to a function, that function is invoked
2299 * (passing any specified arguments) and the return value is
2300 * returned.
2301 *
2302 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
2303 * called, if the metatable for myTable has a __metatable
2304 * key, the value of that key is returned instead of the
2305 * actual metatable.
2306 *
2307 * __tostring - Control string representation. When the builtin
2308 * "tostring( myTable )" function is called, if the metatable
2309 * for myTable has a __tostring property set to a function,
2310 * that function is invoked (passing myTable to it) and the
2311 * return value is used as the string representation.
2312 *
2313 * __len - Control table length. When the table length is requested using
2314 * the length operator ( '#' ), if the metatable for myTable has
2315 * a __len key pointing to a function, that function is invoked
2316 * (passing myTable to it) and the return value used as the value
2317 * of "#myTable".
2318 *
2319 * __gc - Userdata finalizer code. When userdata is set to be garbage
2320 * collected, if the metatable has a __gc field pointing to a
2321 * function, that function is first invoked, passing the userdata
2322 * to it. The __gc metamethod is not called for tables.
2323 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
2324 *
2325 * Special metamethods for redefining standard operators:
2326 * http://www.lua.org/pil/13.1.html
2327 *
2328 * __add "+"
2329 * __sub "-"
2330 * __mul "*"
2331 * __div "/"
2332 * __unm "!"
2333 * __pow "^"
2334 * __concat ".."
2335 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002336 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002337 * http://www.lua.org/pil/13.2.html
2338 *
2339 * __eq "=="
2340 * __lt "<"
2341 * __le "<="
2342 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343
2344/*
2345 *
2346 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002347 * Class Map
2348 *
2349 *
2350 */
2351
2352/* Returns a struct hlua_map if the stack entry "ud" is
2353 * a class session, otherwise it throws an error.
2354 */
2355__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2356{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002357 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002358}
2359
2360/* This function is the map constructor. It don't need
2361 * the class Map object. It creates and return a new Map
2362 * object. It must be called only during "body" or "init"
2363 * context because it process some filesystem accesses.
2364 */
2365__LJMP static int hlua_map_new(struct lua_State *L)
2366{
2367 const char *fn;
2368 int match = PAT_MATCH_STR;
2369 struct sample_conv conv;
2370 const char *file = "";
2371 int line = 0;
2372 lua_Debug ar;
2373 char *err = NULL;
2374 struct arg args[2];
2375
2376 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2377 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2378
2379 fn = MAY_LJMP(luaL_checkstring(L, 1));
2380
2381 if (lua_gettop(L) >= 2) {
2382 match = MAY_LJMP(luaL_checkinteger(L, 2));
2383 if (match < 0 || match >= PAT_MATCH_NUM)
2384 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2385 }
2386
2387 /* Get Lua filename and line number. */
2388 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2389 lua_getinfo(L, "Sl", &ar); /* get info about it */
2390 if (ar.currentline > 0) { /* is there info? */
2391 file = ar.short_src;
2392 line = ar.currentline;
2393 }
2394 }
2395
2396 /* fill fake sample_conv struct. */
2397 conv.kw = ""; /* unused. */
2398 conv.process = NULL; /* unused. */
2399 conv.arg_mask = 0; /* unused. */
2400 conv.val_args = NULL; /* unused. */
2401 conv.out_type = SMP_T_STR;
2402 conv.private = (void *)(long)match;
2403 switch (match) {
2404 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2405 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2406 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2407 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2408 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2409 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2410 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002411 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002412 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2413 default:
2414 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2415 }
2416
2417 /* fill fake args. */
2418 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002419 args[0].data.str.area = strdup(fn);
2420 args[0].data.str.data = strlen(fn);
2421 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002422 args[1].type = ARGT_STOP;
2423
2424 /* load the map. */
2425 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002426 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002427 * free the err variable.
2428 */
Aurelien DARRAGON78e1d2d2024-06-04 12:48:45 +02002429 hlua_pusherror(L, "'new': %s.", err);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002430 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002431 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002432 WILL_LJMP(lua_error(L));
2433 }
2434
2435 /* create the lua object. */
2436 lua_newtable(L);
2437 lua_pushlightuserdata(L, args[0].data.map);
2438 lua_rawseti(L, -2, 0);
2439
2440 /* Pop a class Map metatable and affect it to the userdata. */
2441 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2442 lua_setmetatable(L, -2);
2443
2444
2445 return 1;
2446}
2447
2448__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2449{
2450 struct map_descriptor *desc;
2451 struct pattern *pat;
2452 struct sample smp;
2453
2454 MAY_LJMP(check_args(L, 2, "lookup"));
2455 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002456 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002457 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002458 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002459 }
2460 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002461 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002462 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002463 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry Fournier91dc0c02020-11-10 20:38:20 +01002464 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002465 }
2466
2467 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002468 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002469 if (str)
2470 lua_pushstring(L, "");
2471 else
2472 lua_pushnil(L);
2473 return 1;
2474 }
2475
2476 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002477 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002478 return 1;
2479}
2480
2481__LJMP static int hlua_map_lookup(struct lua_State *L)
2482{
2483 return _hlua_map_lookup(L, 0);
2484}
2485
2486__LJMP static int hlua_map_slookup(struct lua_State *L)
2487{
2488 return _hlua_map_lookup(L, 1);
2489}
2490
2491/*
2492 *
2493 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002494 * Class Socket
2495 *
2496 *
2497 */
2498
2499__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2500{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002501 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502}
2503
2504/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002505 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506 * received.
2507 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002508static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509{
Willy Tarreau5321da92022-05-06 11:57:34 +02002510 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002511 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002512
Christopher Faulet31572222023-03-31 11:13:48 +02002513 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
Aurelien DARRAGONa2c53212023-05-02 19:10:24 +02002514 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Christopher Faulet31572222023-03-31 11:13:48 +02002515 notification_wake(&ctx->wake_on_read);
2516 notification_wake(&ctx->wake_on_write);
2517 return;
2518 }
2519
Willy Tarreau5321da92022-05-06 11:57:34 +02002520 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002521 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002522 notification_wake(&ctx->wake_on_read);
2523 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002524 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002525 }
2526
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002527 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002528 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002529 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002530
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002531 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002532 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002533 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002534
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002535 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002536 * to be notified whenever the connection completes.
2537 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002538 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002539 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002540 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002541 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002542 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002543 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544
2545 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002546 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002547
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002548 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002549 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002550 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002551
2552 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet0dbc16b2024-02-16 15:33:44 +01002553 if (!channel_is_empty(sc_oc(sc))) {
Willy Tarreau5321da92022-05-06 11:57:34 +02002554 notification_wake(&ctx->wake_on_read);
Christopher Faulet0dbc16b2024-02-16 15:33:44 +01002555 applet_wont_consume(appctx);
2556 }
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002557
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002558 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002559 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002560 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002561 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002562 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002563}
2564
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002565static int hlua_socket_init(struct appctx *appctx)
2566{
Christopher Fauletcb068552023-09-27 17:34:24 +02002567 struct hlua_csk_ctx *csk_ctx = appctx->svcctx;
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002568 struct stream *s;
2569
2570 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2571 goto error;
2572
2573 s = appctx_strm(appctx);
2574
Willy Tarreau4596fe22022-05-17 19:07:51 +02002575 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002576 * and retrieve data from the server. The connection is initialized
2577 * with the "struct server".
2578 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002579 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002580
2581 /* Force destination server. */
2582 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Christopher Faulet9a278fd2023-09-27 17:47:45 +02002583 s->target = &csk_ctx->srv->obj_type;
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002584
Christopher Fauletcb068552023-09-27 17:34:24 +02002585 if (csk_ctx->timeout) {
2586 s->sess->fe->timeout.connect = csk_ctx->timeout;
2587 s->scf->ioto = csk_ctx->timeout;
2588 s->scb->ioto = csk_ctx->timeout;
2589 }
2590
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002591 return 0;
2592
2593 error:
2594 return -1;
2595}
2596
Willy Tarreau87b09662015-04-03 00:22:06 +02002597/* This function is called when the "struct stream" is destroyed.
2598 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002599 * Wake all the pending signals.
2600 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002601static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002602{
Willy Tarreau5321da92022-05-06 11:57:34 +02002603 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002604 struct xref *peer;
2605
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002606 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002607 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002608 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002609 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610
2611 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002612 notification_wake(&ctx->wake_on_read);
2613 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614}
2615
2616/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002617 * uses this object. If the stream does not exists, just quit.
2618 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619 * pending signal can rest in the read and write lists. destroy
2620 * it.
2621 */
2622__LJMP static int hlua_socket_gc(lua_State *L)
2623{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002624 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002625 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002626 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002627
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002628 MAY_LJMP(check_args(L, 1, "__gc"));
2629
2630 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002631 peer = xref_get_peer_and_lock(&socket->xref);
2632 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002634
2635 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002636
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002637 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002638 xref_disconnect(&socket->xref, peer);
Christopher Faulet5b62e092024-02-16 15:00:54 +01002639
2640 if (se_fl_test(ctx->appctx->sedesc, SE_FL_ORPHAN)) {
2641 /* The applet was never initialized, just release it */
2642 appctx_free(ctx->appctx);
2643 }
2644 else {
2645 /* Otherwise, notify it that is must die and wake it up */
2646 ctx->die = 1;
2647 appctx_wakeup(ctx->appctx);
2648 }
2649
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002650 return 0;
2651}
2652
2653/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002654 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002655 */
sada05ed3302018-05-11 11:48:18 -07002656__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002658 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002659 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002661 struct hlua *hlua;
2662
2663 /* Get hlua struct, or NULL if we execute from main lua state */
2664 hlua = hlua_gethlua(L);
2665 if (!hlua)
2666 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002668 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002669
2670 /* Check if we run on the same thread than the xreator thread.
2671 * We cannot access to the socket if the thread is different.
2672 */
2673 if (socket->tid != tid)
2674 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2675
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002676 peer = xref_get_peer_and_lock(&socket->xref);
2677 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002678 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002679
2680 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002681 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002683 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002684 ctx->die = 1;
2685 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002686
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002687 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002688 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689 return 0;
2690}
2691
sada05ed3302018-05-11 11:48:18 -07002692/* The close function calls close_helper.
2693 */
2694__LJMP static int hlua_socket_close(lua_State *L)
2695{
2696 MAY_LJMP(check_args(L, 1, "close"));
2697 return hlua_socket_close_helper(L);
2698}
2699
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002700/* This Lua function assumes that the stack contain three parameters.
2701 * 1 - USERDATA containing a struct socket
2702 * 2 - INTEGER with values of the macro defined below
2703 * If the integer is -1, we must read at most one line.
2704 * If the integer is -2, we ust read all the data until the
2705 * end of the stream.
2706 * If the integer is positive value, we must read a number of
2707 * bytes corresponding to this value.
2708 */
2709#define HLSR_READ_LINE (-1)
2710#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002711__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712{
2713 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2714 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002715 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002716 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002717 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002718 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002720 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002721 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002722 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002723 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002724 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002725 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002726 struct stream *s;
2727 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002728 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002729
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002730 /* Get hlua struct, or NULL if we execute from main lua state */
2731 hlua = hlua_gethlua(L);
2732
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733 /* Check if this lua stack is schedulable. */
2734 if (!hlua || !hlua->task)
2735 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2736 "'frontend', 'backend' or 'task'"));
2737
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002738 /* Check if we run on the same thread than the xreator thread.
2739 * We cannot access to the socket if the thread is different.
2740 */
2741 if (socket->tid != tid)
2742 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2743
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002744 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002745 peer = xref_get_peer_and_lock(&socket->xref);
2746 if (!peer)
2747 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002748
2749 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
Christopher Faulet714476c2023-09-27 17:22:41 +02002750 if (!csk_ctx->connected)
2751 goto connection_closed;
2752
Willy Tarreau5321da92022-05-06 11:57:34 +02002753 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002754 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002755
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002756 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002757 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002758 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002759 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002760 if (nblk < 0) /* Connection close. */
2761 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002762 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002763 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002764
2765 /* remove final \r\n. */
2766 if (nblk == 1) {
2767 if (blk1[len1-1] == '\n') {
2768 len1--;
2769 skip_at_end++;
2770 if (blk1[len1-1] == '\r') {
2771 len1--;
2772 skip_at_end++;
2773 }
2774 }
2775 }
2776 else {
2777 if (blk2[len2-1] == '\n') {
2778 len2--;
2779 skip_at_end++;
2780 if (blk2[len2-1] == '\r') {
2781 len2--;
2782 skip_at_end++;
2783 }
2784 }
2785 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002786 }
2787
2788 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002790 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002791 if (nblk < 0) /* Connection close. */
2792 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002793 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002794 goto connection_empty;
2795 }
2796
2797 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002798 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002799 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002800 if (nblk < 0) /* Connection close. */
2801 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002802 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002803 goto connection_empty;
2804
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002805 missing_bytes = wanted - socket->b.n;
2806 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002807 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002808 len1 = missing_bytes;
2809 } if (nblk == 2 && len1 + len2 > missing_bytes)
2810 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002811 }
2812
2813 len = len1;
2814
2815 luaL_addlstring(&socket->b, blk1, len1);
2816 if (nblk == 2) {
2817 len += len2;
2818 luaL_addlstring(&socket->b, blk2, len2);
2819 }
2820
2821 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002822 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002823
2824 /* Don't wait anything. */
Christopher Faulet0dbc16b2024-02-16 15:33:44 +01002825 applet_will_consume(appctx);
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002826 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827
2828 /* If the pattern reclaim to read all the data
2829 * in the connection, got out.
2830 */
2831 if (wanted == HLSR_READ_ALL)
2832 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002833 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002834 goto connection_empty;
2835
2836 /* Return result. */
2837 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002838 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002839 return 1;
2840
2841connection_closed:
2842
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002843 xref_unlock(&socket->xref, peer);
2844
2845no_peer:
2846
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002847 /* If the buffer containds data. */
2848 if (socket->b.n > 0) {
2849 luaL_pushresult(&socket->b);
2850 return 1;
2851 }
2852 lua_pushnil(L);
2853 lua_pushstring(L, "connection closed.");
2854 return 2;
2855
2856connection_empty:
2857
Willy Tarreau5321da92022-05-06 11:57:34 +02002858 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002859 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002860 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002861 }
2862 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002863 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002864 return 0;
2865}
2866
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002867/* This Lua function gets two parameters. The first one can be string
2868 * or a number. If the string is "*l", the user requires one line. If
2869 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002870 * If the value is a number, the user require a number of bytes equal
2871 * to the value. The default value is "*l" (a line).
2872 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002873 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002874 * integer takes this values:
2875 * -1 : read a line
2876 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002877 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002878 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002879 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002880 * concatenated with the read data.
2881 */
2882__LJMP static int hlua_socket_receive(struct lua_State *L)
2883{
2884 int wanted = HLSR_READ_LINE;
2885 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002886 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002887 char *error;
2888 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002889 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002890
2891 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2892 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2893
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002894 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002895
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002896 /* Check if we run on the same thread than the xreator thread.
2897 * We cannot access to the socket if the thread is different.
2898 */
2899 if (socket->tid != tid)
2900 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2901
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002902 /* check for pattern. */
2903 if (lua_gettop(L) >= 2) {
2904 type = lua_type(L, 2);
2905 if (type == LUA_TSTRING) {
2906 pattern = lua_tostring(L, 2);
2907 if (strcmp(pattern, "*a") == 0)
2908 wanted = HLSR_READ_ALL;
2909 else if (strcmp(pattern, "*l") == 0)
2910 wanted = HLSR_READ_LINE;
2911 else {
2912 wanted = strtoll(pattern, &error, 10);
2913 if (*error != '\0')
2914 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2915 }
2916 }
2917 else if (type == LUA_TNUMBER) {
2918 wanted = lua_tointeger(L, 2);
2919 if (wanted < 0)
2920 WILL_LJMP(luaL_error(L, "Unsupported size."));
2921 }
2922 }
2923
2924 /* Set pattern. */
2925 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002926
2927 /* Check if we would replace the top by itself. */
2928 if (lua_gettop(L) != 2)
2929 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002930
Christopher Fauletc31b2002021-05-03 10:11:13 +02002931 /* Save index of the top of the stack because since buffers are used, it
2932 * may change
2933 */
2934 lastarg = lua_gettop(L);
2935
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002936 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002937 luaL_buffinit(L, &socket->b);
2938
2939 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002940 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002941 if (lua_type(L, 3) != LUA_TSTRING)
2942 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2943 pattern = lua_tolstring(L, 3, &len);
2944 luaL_addlstring(&socket->b, pattern, len);
2945 }
2946
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002947 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002948}
2949
2950/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002951 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002953static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002954{
2955 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002956 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002957 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002958 struct appctx *appctx;
2959 size_t buf_len;
2960 const char *buf;
2961 int len;
2962 int send_len;
2963 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002964 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002965 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002966 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002967
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002968 /* Get hlua struct, or NULL if we execute from main lua state */
2969 hlua = hlua_gethlua(L);
2970
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002971 /* Check if this lua stack is schedulable. */
2972 if (!hlua || !hlua->task)
2973 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2974 "'frontend', 'backend' or 'task'"));
2975
2976 /* Get object */
2977 socket = MAY_LJMP(hlua_checksocket(L, 1));
2978 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002979 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002980
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002981 /* Check if we run on the same thread than the xreator thread.
2982 * We cannot access to the socket if the thread is different.
2983 */
2984 if (socket->tid != tid)
2985 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2986
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002987 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002988 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002989 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002990 lua_pushinteger(L, -1);
2991 return 1;
2992 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002993
2994 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
Christopher Faulet714476c2023-09-27 17:22:41 +02002995 if (!csk_ctx->connected) {
2996 xref_unlock(&socket->xref, peer);
2997 lua_pushinteger(L, -1);
2998 return 1;
2999 }
3000
Willy Tarreau5321da92022-05-06 11:57:34 +02003001 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003002 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003003 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003004
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003005 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003006 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003007 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003008 lua_pushinteger(L, -1);
3009 return 1;
3010 }
3011
3012 /* Update the input buffer data. */
3013 buf += sent;
3014 send_len = buf_len - sent;
3015
3016 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003017 if (sent >= buf_len) {
3018 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003019 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003020 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003022 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01003023 * the request buffer if its not required.
3024 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003025 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02003026 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01003027 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01003028 }
3029
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003030 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003031 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01003032 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003033 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01003034 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003035
3036 /* send data */
3037 if (len < send_len)
3038 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02003039 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003040
3041 /* "Not enough space" (-1), "Buffer too little to contain
3042 * the data" (-2) are not expected because the available length
3043 * is tested.
3044 * Other unknown error are also not expected.
3045 */
3046 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01003047 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003048 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01003049
sada05ed3302018-05-11 11:48:18 -07003050 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003051 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003052 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003053 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003054 return 1;
3055 }
3056
3057 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02003058 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02003059
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003060 /* Update length sent. */
3061 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003062 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003063
3064 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003065 if (sent + len >= buf_len) {
3066 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003067 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003068 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003069
3070hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02003071 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02003072 xref_unlock(&socket->xref, peer);
3073 WILL_LJMP(luaL_error(L, "out of memory"));
3074 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003075 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003076 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003077 return 0;
3078}
3079
3080/* This function initiate the send of data. It just check the input
3081 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003082 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003083 * "hlua_socket_write_yield" that can yield.
3084 *
3085 * The Lua function gets between 3 and 4 parameters. The first one is
3086 * the associated object. The second is a string buffer. The third is
3087 * a facultative integer that represents where is the buffer position
3088 * of the start of the data that can send. The first byte is the
3089 * position "1". The default value is "1". The fourth argument is a
3090 * facultative integer that represents where is the buffer position
3091 * of the end of the data that can send. The default is the last byte.
3092 */
3093static int hlua_socket_send(struct lua_State *L)
3094{
3095 int i;
3096 int j;
3097 const char *buf;
3098 size_t buf_len;
3099
3100 /* Check number of arguments. */
3101 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3102 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
3103
3104 /* Get the string. */
3105 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
3106
3107 /* Get and check j. */
3108 if (lua_gettop(L) == 4) {
3109 j = MAY_LJMP(luaL_checkinteger(L, 4));
3110 if (j < 0)
3111 j = buf_len + j + 1;
3112 if (j > buf_len)
3113 j = buf_len + 1;
3114 lua_pop(L, 1);
3115 }
3116 else
3117 j = buf_len;
3118
3119 /* Get and check i. */
3120 if (lua_gettop(L) == 3) {
3121 i = MAY_LJMP(luaL_checkinteger(L, 3));
3122 if (i < 0)
3123 i = buf_len + i + 1;
3124 if (i > buf_len)
3125 i = buf_len + 1;
3126 lua_pop(L, 1);
3127 } else
3128 i = 1;
3129
3130 /* Check bth i and j. */
3131 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003132 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003133 return 1;
3134 }
3135 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003136 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003137 return 1;
3138 }
3139 if (i == 0)
3140 i = 1;
3141 if (j == 0)
3142 j = 1;
3143
3144 /* Pop the string. */
3145 lua_pop(L, 1);
3146
3147 /* Update the buffer length. */
3148 buf += i - 1;
3149 buf_len = j - i + 1;
3150 lua_pushlstring(L, buf, buf_len);
3151
3152 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003153 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003154
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003155 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003156}
3157
Willy Tarreau22b0a682015-06-17 19:43:49 +02003158#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02003159__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003160{
3161 static char buffer[SOCKET_INFO_MAX_LEN];
3162 int ret;
3163 int len;
3164 char *p;
3165
3166 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
3167 if (ret <= 0) {
3168 lua_pushnil(L);
3169 return 1;
3170 }
3171
3172 if (ret == AF_UNIX) {
3173 lua_pushstring(L, buffer+1);
3174 return 1;
3175 }
3176 else if (ret == AF_INET6) {
3177 buffer[0] = '[';
3178 len = strlen(buffer);
3179 buffer[len] = ']';
3180 len++;
3181 buffer[len] = ':';
3182 len++;
3183 p = buffer;
3184 }
3185 else if (ret == AF_INET) {
3186 p = buffer + 1;
3187 len = strlen(p);
3188 p[len] = ':';
3189 len++;
3190 }
3191 else {
3192 lua_pushnil(L);
3193 return 1;
3194 }
3195
3196 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
3197 lua_pushnil(L);
3198 return 1;
3199 }
3200
3201 lua_pushstring(L, p);
3202 return 1;
3203}
3204
3205/* Returns information about the peer of the connection. */
3206__LJMP static int hlua_socket_getpeername(struct lua_State *L)
3207{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003208 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003209 struct xref *peer;
Christopher Faulet714476c2023-09-27 17:22:41 +02003210 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003211 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003212 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02003213 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003214 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003215
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003216 MAY_LJMP(check_args(L, 1, "getpeername"));
3217
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003218 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003219
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003220 /* Check if we run on the same thread than the xreator thread.
3221 * We cannot access to the socket if the thread is different.
3222 */
3223 if (socket->tid != tid)
3224 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3225
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003226 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003227 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003228 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003229 lua_pushnil(L);
3230 return 1;
3231 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003232
Christopher Faulet714476c2023-09-27 17:22:41 +02003233 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3234 if (!csk_ctx->connected) {
3235 xref_unlock(&socket->xref, peer);
3236 lua_pushnil(L);
3237 return 1;
3238 }
3239
3240 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003241 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003242 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02003243 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003244 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01003245 lua_pushnil(L);
3246 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003247 }
3248
Christopher Faulet16f16af2021-10-27 09:34:56 +02003249 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003250 xref_unlock(&socket->xref, peer);
3251 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003252}
3253
3254/* Returns information about my connection side. */
3255static int hlua_socket_getsockname(struct lua_State *L)
3256{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003257 struct hlua_socket *socket;
3258 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003259 struct appctx *appctx;
3260 struct xref *peer;
Christopher Faulet714476c2023-09-27 17:22:41 +02003261 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003262 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003263 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003264
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003265 MAY_LJMP(check_args(L, 1, "getsockname"));
3266
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003267 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003268
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003269 /* Check if we run on the same thread than the xreator thread.
3270 * We cannot access to the socket if the thread is different.
3271 */
3272 if (socket->tid != tid)
3273 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3274
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003275 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003276 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003277 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003278 lua_pushnil(L);
3279 return 1;
3280 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003281
Christopher Faulet714476c2023-09-27 17:22:41 +02003282 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3283 if (!csk_ctx->connected) {
3284 xref_unlock(&socket->xref, peer);
3285 lua_pushnil(L);
3286 return 1;
3287 }
3288
3289 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003290 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003291
Willy Tarreaufd9417b2022-05-18 16:23:22 +02003292 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02003293 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003294 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003295 lua_pushnil(L);
3296 return 1;
3297 }
3298
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003299 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003300 xref_unlock(&socket->xref, peer);
3301 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003302}
3303
3304/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02003305static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003306 .obj_type = OBJ_TYPE_APPLET,
3307 .name = "<LUA_TCP>",
3308 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003309 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003310 .release = hlua_socket_release,
3311};
3312
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003313__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003314{
3315 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003316 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003317 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02003318 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003319 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003320 struct stream *s;
3321
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003322 /* Get hlua struct, or NULL if we execute from main lua state */
3323 hlua = hlua_gethlua(L);
3324 if (!hlua)
3325 return 0;
3326
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003327 /* Check if we run on the same thread than the xreator thread.
3328 * We cannot access to the socket if the thread is different.
3329 */
3330 if (socket->tid != tid)
3331 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3332
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003333 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003334 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003335 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003336 lua_pushnil(L);
3337 lua_pushstring(L, "Can't connect");
3338 return 2;
3339 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003340
3341 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3342 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003343 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003344
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003345 /* Check if we run on the same thread than the xreator thread.
3346 * We cannot access to the socket if the thread is different.
3347 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003348 if (socket->tid != tid) {
3349 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003350 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003351 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003352
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003353 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003354 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003355 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003356 lua_pushnil(L);
3357 lua_pushstring(L, "Can't connect");
3358 return 2;
3359 }
3360
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02003361 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003362
3363 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003364 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003365 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003366 lua_pushinteger(L, 1);
3367 return 1;
3368 }
3369
Willy Tarreau5321da92022-05-06 11:57:34 +02003370 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003371 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003372 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003373 }
3374 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003375 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003376 return 0;
3377}
3378
3379/* This function fail or initite the connection. */
3380__LJMP static int hlua_socket_connect(struct lua_State *L)
3381{
3382 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003383 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003384 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003385 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003386 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003387 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003388 int low, high;
3389 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003390 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003391 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003392
Christopher Faulet6db178d2023-09-27 17:42:38 +02003393 /* Get hlua struct, or NULL if we execute from main lua state */
3394 hlua = hlua_gethlua(L);
3395 if (!hlua)
3396 return 0;
3397
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003398 if (lua_gettop(L) < 2)
3399 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003400
3401 /* Get args. */
3402 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003403
3404 /* Check if we run on the same thread than the xreator thread.
3405 * We cannot access to the socket if the thread is different.
3406 */
3407 if (socket->tid != tid)
3408 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3409
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003410 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003411 if (lua_gettop(L) >= 3) {
3412 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003413 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003414
Tim Duesterhus6edab862018-01-06 19:04:45 +01003415 /* Force the ip to end with a colon, to support IPv6 addresses
3416 * that are not enclosed within square brackets.
3417 */
3418 if (port > 0) {
3419 luaL_buffinit(L, &b);
3420 luaL_addstring(&b, ip);
3421 luaL_addchar(&b, ':');
3422 luaL_pushresult(&b);
3423 ip = lua_tolstring(L, lua_gettop(L), NULL);
3424 }
3425 }
3426
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003427 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003428 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003429 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003430 lua_pushnil(L);
3431 return 1;
3432 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003433
Christopher Faulet26786572023-09-27 17:39:44 +02003434 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3435 if (!csk_ctx->srv)
3436 csk_ctx->srv = socket_tcp;
3437
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003438 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003439 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, NULL, NULL, PA_O_PORT_OK | PA_O_STREAM);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003440 if (!addr) {
3441 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003442 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003443 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003444
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003445 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003446 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003447 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003448 if (port == -1) {
3449 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003450 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003451 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003452 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3453 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003454 if (port == -1) {
3455 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003456 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003457 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003458 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003459 }
3460 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003461
Willy Tarreau5321da92022-05-06 11:57:34 +02003462 appctx = csk_ctx->appctx;
Christopher Faulet9a278fd2023-09-27 17:47:45 +02003463 if (appctx_sc(appctx)) {
3464 xref_unlock(&socket->xref, peer);
3465 WILL_LJMP(luaL_error(L, "connect: connect already performed\n"));
3466 }
3467
3468 if (appctx_init(appctx) == -1) {
3469 xref_unlock(&socket->xref, peer);
3470 WILL_LJMP(luaL_error(L, "connect: fail to init applet."));
3471 }
3472
Willy Tarreauc12b3212022-05-27 11:08:15 +02003473 sc = appctx_sc(appctx);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003474
Willy Tarreau3e7be362022-05-27 10:35:27 +02003475 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003476 xref_unlock(&socket->xref, peer);
3477 WILL_LJMP(luaL_error(L, "connect: internal error"));
3478 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003479
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003480 /* inform the stream that we want to be notified whenever the
3481 * connection completes.
3482 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003483 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003484 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003485 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003486
Willy Tarreau5321da92022-05-06 11:57:34 +02003487 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003488 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003489 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003490 }
3491 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003492
PiBa-NL706d5ee2018-05-05 23:51:42 +02003493 /* Return yield waiting for connection. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003494 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003495
3496 return 0;
3497}
3498
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003499#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003500__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3501{
3502 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003503 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003504
3505 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3506 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003507
3508 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003509 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003510 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003511 lua_pushnil(L);
3512 return 1;
3513 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003514
Christopher Faulet26786572023-09-27 17:39:44 +02003515 container_of(peer, struct hlua_csk_ctx, xref)->srv = socket_ssl;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003516
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003517 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003518 return MAY_LJMP(hlua_socket_connect(L));
3519}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003520#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003521
3522__LJMP static int hlua_socket_setoption(struct lua_State *L)
3523{
3524 return 0;
3525}
3526
3527__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3528{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003529 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003530 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003531 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003532 struct xref *peer;
Christopher Fauletcb068552023-09-27 17:34:24 +02003533 struct hlua_csk_ctx *csk_ctx;
3534 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003535 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003536
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003537 MAY_LJMP(check_args(L, 2, "settimeout"));
3538
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003539 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003540
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003541 /* convert the timeout to millis */
3542 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003543
Thierry Fournier17a921b2018-03-08 09:59:02 +01003544 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003545 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003546 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3547
Mark Lakes56cc1252018-03-27 09:48:06 +02003548 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003549 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003550
3551 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003552 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003553 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003554
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003555 /* Check if we run on the same thread than the xreator thread.
3556 * We cannot access to the socket if the thread is different.
3557 */
3558 if (socket->tid != tid)
3559 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3560
Mark Lakes56cc1252018-03-27 09:48:06 +02003561 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003562 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003563 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003564 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3565 WILL_LJMP(lua_error(L));
3566 return 0;
3567 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003568
Christopher Fauletcb068552023-09-27 17:34:24 +02003569 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3570 csk_ctx->timeout = tmout;
3571
3572 appctx = csk_ctx->appctx;
3573 if (!appctx_sc(appctx))
3574 goto end;
3575
3576 s = appctx_strm(csk_ctx->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003577
Cyril Bonté7bb63452018-08-17 23:51:02 +02003578 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003579 s->scf->ioto = tmout;
3580 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003581
Christopher Fauletcb068552023-09-27 17:34:24 +02003582 s->task->expire = (tick_is_expired(s->task->expire, now_ms) ? 0 : s->task->expire);
3583 s->task->expire = tick_first(s->task->expire, tick_add_ifset(now_ms, tmout));
Cyril Bonté7bb63452018-08-17 23:51:02 +02003584 task_queue(s->task);
3585
Christopher Fauletcb068552023-09-27 17:34:24 +02003586 end:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003587 xref_unlock(&socket->xref, peer);
Thierry Fourniere9636f12018-03-08 09:54:32 +01003588 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003589 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003590}
3591
3592__LJMP static int hlua_socket_new(lua_State *L)
3593{
3594 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003595 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003596 struct appctx *appctx;
Christopher Faulet5b62e092024-02-16 15:00:54 +01003597 struct hlua *hlua;
3598
3599 /* Get hlua struct, or NULL if we execute from main lua state */
3600 hlua = hlua_gethlua(L);
3601 if (!hlua)
3602 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003603
3604 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003605 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003606 hlua_pusherror(L, "socket: full stack");
3607 goto out_fail_conf;
3608 }
3609
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003610 /* Create the object: obj[0] = userdata. */
3611 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003612 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003613 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003614 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003615 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003616
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003617 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003618 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003619 hlua_pusherror(L, "socket: uninitialized pools.");
3620 goto out_fail_conf;
3621 }
3622
Willy Tarreau87b09662015-04-03 00:22:06 +02003623 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003624 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3625 lua_setmetatable(L, -2);
3626
Willy Tarreaud420a972015-04-06 00:39:18 +02003627 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003628 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003629 if (!appctx) {
3630 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003631 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003632 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003633 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3634 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003635 ctx->die = 0;
Christopher Faulet26786572023-09-27 17:39:44 +02003636 ctx->srv = NULL;
Christopher Fauletcb068552023-09-27 17:34:24 +02003637 ctx->timeout = 0;
Christopher Faulet75d1bfb2023-09-27 17:17:48 +02003638 ctx->appctx = appctx;
Willy Tarreau5321da92022-05-06 11:57:34 +02003639 LIST_INIT(&ctx->wake_on_write);
3640 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003641
Christopher Faulet5b62e092024-02-16 15:00:54 +01003642 hlua->gc_count++;
3643
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003644 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003645 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003646 return 1;
3647
Christopher Faulet13a35e52021-12-20 15:34:16 +01003648 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003649 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003650 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003651 WILL_LJMP(lua_error(L));
3652 return 0;
3653}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003654
3655/*
3656 *
3657 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003658 * Class Channel
3659 *
3660 *
3661 */
3662
3663/* Returns the struct hlua_channel join to the class channel in the
3664 * stack entry "ud" or throws an argument error.
3665 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003666__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003667{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003668 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003669}
3670
Willy Tarreau47860ed2015-03-10 14:07:50 +01003671/* Pushes the channel onto the top of the stack. If the stask does not have a
3672 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003673 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003674static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003675{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003676 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003677 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003678 return 0;
3679
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003680 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003681 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003682 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003683
3684 /* Pop a class sesison metatable and affect it to the userdata. */
3685 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3686 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003687 return 1;
3688}
3689
Christopher Faulet9f55a502020-02-25 15:21:02 +01003690/* Helper function returning a filter attached to a channel at the position <ud>
3691 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003692 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003693 * initialized.
3694 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003695static struct filter *hlua_channel_filter(lua_State *L, int ud, struct channel *chn, size_t *offset, size_t *len)
Christopher Faulet9f55a502020-02-25 15:21:02 +01003696{
3697 struct filter *filter = NULL;
3698
3699 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3700 struct hlua_flt_ctx *flt_ctx;
3701
3702 filter = lua_touserdata (L, -1);
3703 flt_ctx = filter->ctx;
3704 if (hlua_filter_from_payload(filter)) {
3705 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3706 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3707 }
3708 }
3709
3710 lua_pop(L, 1);
3711 return filter;
3712}
3713
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003714/* Copies <len> bytes of data present in the channel's buffer, starting at the
3715* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003716* responsibility to ensure <len> and <offset> are valid. It always return the
3717* length of the built string. <len> may be 0, in this case, an empty string is
3718* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003719*/
3720static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003721{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003722 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003723 luaL_Buffer b;
3724
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003725 block1 = len;
3726 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3727 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3728 block2 = len - block1;
3729
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003730 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003731 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3732 if (block2)
3733 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003734 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003735 return len;
3736}
3737
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003738/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3739 * function returns -1 if data cannot be copied. Otherwise, it returns the
3740 * number of bytes copied.
3741 */
3742static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3743{
3744 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003745
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003746 /* Nothing to do, just return */
3747 if (unlikely(istlen(str) == 0))
3748 goto end;
3749
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003750 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003751 ret = -1;
3752 goto end;
3753 }
3754 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3755
3756 end:
3757 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003758}
3759
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003760/* Removes <len> bytes of data at the absolute position <offset>.
3761 */
3762static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3763{
3764 size_t end = offset + len;
3765
3766 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3767 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3768 b_data(&chn->buf) - end, -len);
3769 b_sub(&chn->buf, len);
3770}
3771
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003772/* Copies input data in the channel's buffer. It is possible to set a specific
3773 * offset (0 by default) and a length (all remaining input data starting for the
3774 * offset by default). If there is not enough input data and more data can be
3775 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003776 *
3777 * From an action, All input data are considered. For a filter, the offset and
3778 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003779 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003780__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003781{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003782 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003783 struct filter *filter;
3784 size_t input, output;
3785 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003786
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003787 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003788
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003789 output = co_data(chn);
3790 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003791
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003792 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3793 if (filter && !hlua_filter_from_payload(filter))
3794 WILL_LJMP(lua_error(L));
3795
3796 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003797 if (lua_gettop(L) > 1) {
3798 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3799 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003800 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003801 offset += output;
3802 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003803 lua_pushfstring(L, "offset out of range.");
3804 WILL_LJMP(lua_error(L));
3805 }
3806 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003807 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003808 if (lua_gettop(L) == 3) {
3809 len = MAY_LJMP(luaL_checkinteger(L, 3));
3810 if (!len)
3811 goto dup;
3812 if (len == -1)
3813 len = global.tune.bufsize;
3814 if (len < 0) {
3815 lua_pushfstring(L, "length out of range.");
3816 WILL_LJMP(lua_error(L));
3817 }
3818 }
3819
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003820 /* Wait for more data if possible if no length was specified and there
3821 * is no data or not enough data was received.
3822 */
3823 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003824 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3825 /* Yield waiting for more data, as requested */
3826 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3827 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003828
3829 /* Return 'nil' if there is no data and the channel can't receive more data */
3830 if (!len) {
3831 lua_pushnil(L);
3832 return -1;
3833 }
3834
3835 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003836 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003837 }
3838
3839 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003840 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003841 return 1;
3842}
3843
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003844/* Copies the first line (including the trailing LF) of input data in the
3845 * channel's buffer. It is possible to set a specific offset (0 by default) and
3846 * a length (all remaining input data starting for the offset by default). If
3847 * there is not enough input data and more data can be received, the function
3848 * yields. If a length is explicitly specified, no more data are
3849 * copied. Otherwise, if no LF is found and more data can be received, this
3850 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003851 *
3852 * From an action, All input data are considered. For a filter, the offset and
3853 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003854 */
3855__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003856{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003857 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003858 struct filter *filter;
3859 size_t l, input, output;
3860 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003862 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003863 output = co_data(chn);
3864 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003865
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003866 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3867 if (filter && !hlua_filter_from_payload(filter))
3868 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003869
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003870 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003871 if (lua_gettop(L) > 1) {
3872 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3873 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003874 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003875 offset += output;
3876 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003877 lua_pushfstring(L, "offset out of range.");
3878 WILL_LJMP(lua_error(L));
3879 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003880 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003881
3882 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003883 if (lua_gettop(L) == 3) {
3884 len = MAY_LJMP(luaL_checkinteger(L, 3));
3885 if (!len)
3886 goto dup;
3887 if (len == -1)
3888 len = global.tune.bufsize;
3889 if (len < 0) {
3890 lua_pushfstring(L, "length out of range.");
3891 WILL_LJMP(lua_error(L));
3892 }
3893 }
3894
3895 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003896 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003897 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003898 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003899 len = l+1;
3900 goto dup;
3901 }
3902 }
3903
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003904 /* Wait for more data if possible if no line is found and no length was
3905 * specified or not enough data was received.
3906 */
3907 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003908 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3909 /* Yield waiting for more data */
3910 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3911 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003912
3913 /* Return 'nil' if there is no data and the channel can't receive more data */
3914 if (!len) {
3915 lua_pushnil(L);
3916 return -1;
3917 }
3918
3919 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003920 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003921 }
3922
3923 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003924 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003925 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003926}
3927
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003928/* [ DEPRECATED ]
3929 *
3930 * Duplicate all input data foud in the channel's buffer. The data are not
3931 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003932 *
3933 * From an action, All input data are considered. For a filter, the offset and
3934 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003935 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003936__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003937{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003938 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003939 struct filter *filter;
3940 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003941
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003942 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003943 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003944 if (IS_HTX_STRM(chn_strm(chn))) {
3945 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3946 WILL_LJMP(lua_error(L));
3947 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003948
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003949 offset = co_data(chn);
3950 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003951
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003952 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3953 if (filter && !hlua_filter_from_payload(filter))
3954 WILL_LJMP(lua_error(L));
3955
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003956 if (!ci_data(chn) && channel_input_closed(chn)) {
3957 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003958 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003959 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003960
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003961 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003962 return 1;
3963}
3964
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003965/* [ DEPRECATED ]
3966 *
3967 * Get all input data foud in the channel's buffer. The data are removed from
3968 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3969 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003970 *
3971 * From an action, All input data are considered. For a filter, the offset and
3972 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003973 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003974__LJMP static int hlua_channel_get(lua_State *L)
3975{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003976 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003977 struct filter *filter;
3978 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003979 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003980
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003981 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003982 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3983 if (IS_HTX_STRM(chn_strm(chn))) {
3984 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3985 WILL_LJMP(lua_error(L));
3986 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003987
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003988 offset = co_data(chn);
3989 len = ci_data(chn);
3990
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003991 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3992 if (filter && !hlua_filter_from_payload(filter))
3993 WILL_LJMP(lua_error(L));
3994
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003995 if (!ci_data(chn) && channel_input_closed(chn)) {
3996 lua_pushnil(L);
3997 return 1;
3998 }
3999
4000 ret = _hlua_channel_dup(chn, L, offset, len);
4001 _hlua_channel_delete(chn, offset, ret);
4002 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004003}
4004
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004005/* This functions consumes and returns one line. If the channel is closed,
4006 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004007 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004008 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004009 *
4010 * From an action, All input data are considered. For a filter, the offset and
4011 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004012 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004013__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004014{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004015 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004016 struct filter *filter;
4017 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004018 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004019
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004020 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004021
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004022 offset = co_data(chn);
4023 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004024
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004025 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4026 if (filter && !hlua_filter_from_payload(filter))
4027 WILL_LJMP(lua_error(L));
4028
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004029 if (!ci_data(chn) && channel_input_closed(chn)) {
4030 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004031 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004032 }
4033
4034 for (l = 0; l < len; l++) {
4035 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
4036 len = l+1;
4037 goto dup;
4038 }
4039 }
4040
4041 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
4042 /* Yield waiting for more data */
4043 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
4044 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004045
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004046 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004047 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004048 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004049 return 1;
4050}
4051
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004052/* [ DEPRECATED ]
4053 *
4054 * Check arguments for the function "hlua_channel_getline_yield".
4055 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004056__LJMP static int hlua_channel_getline(lua_State *L)
4057{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004058 struct channel *chn;
4059
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004060 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004061 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4062 if (IS_HTX_STRM(chn_strm(chn))) {
4063 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4064 WILL_LJMP(lua_error(L));
4065 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004066 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
4067}
4068
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004069/* Retrieves a given amount of input data at the given offset. By default all
4070 * available input data are returned. The offset may be negactive to start from
4071 * the end of input data. The length may be -1 to set it to the maximum buffer
4072 * size.
4073 */
4074__LJMP static int hlua_channel_get_data(lua_State *L)
4075{
4076 struct channel *chn;
4077
4078 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
4079 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
4080 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4081 if (IS_HTX_STRM(chn_strm(chn))) {
4082 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4083 WILL_LJMP(lua_error(L));
4084 }
4085 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
4086}
4087
4088/* Retrieves a given amount of input data at the given offset. By default all
4089 * available input data are returned. The offset may be negactive to start from
4090 * the end of input data. The length may be -1 to set it to the maximum buffer
4091 * size.
4092 */
4093__LJMP static int hlua_channel_get_line(lua_State *L)
4094{
4095 struct channel *chn;
4096
4097 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
4098 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
4099 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4100 if (IS_HTX_STRM(chn_strm(chn))) {
4101 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4102 WILL_LJMP(lua_error(L));
4103 }
4104 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
4105}
4106
4107/* Appends a string into the input side of channel. It returns the length of the
4108 * written string, or -1 if the channel is closed or if the buffer size is too
4109 * little for the data. 0 may be returned if nothing is copied. This function
4110 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004111 *
4112 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004113 */
Christopher Faulet23976d92021-08-06 09:59:49 +02004114__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004115{
Christopher Faulet23976d92021-08-06 09:59:49 +02004116 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004117 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02004118 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004119 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004120 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02004121
4122 MAY_LJMP(check_args(L, 2, "append"));
4123 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004124 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01004125 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02004126 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01004127 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02004128 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004129
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004130 offset = co_data(chn);
4131 len = ci_data(chn);
4132
4133 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4134 if (filter && !hlua_filter_from_payload(filter))
4135 WILL_LJMP(lua_error(L));
4136
4137 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4138 if (ret > 0 && filter) {
4139 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4140
4141 flt_update_offsets(filter, chn, ret);
4142 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
4143 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004144 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004145 return 1;
4146}
4147
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004148/* Prepends a string into the input side of channel. It returns the length of the
4149 * written string, or -1 if the channel is closed or if the buffer size is too
4150 * little for the data. 0 may be returned if nothing is copied. This function
4151 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004152 *
4153 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004154 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004155__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004156{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004157 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004158 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02004159 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004160 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004161 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004162
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004163 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004164 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004165 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4166 if (IS_HTX_STRM(chn_strm(chn))) {
4167 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4168 WILL_LJMP(lua_error(L));
4169 }
4170
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004171 offset = co_data(chn);
4172 len = ci_data(chn);
4173
4174 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4175 if (filter && !hlua_filter_from_payload(filter))
4176 WILL_LJMP(lua_error(L));
4177
4178 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4179 if (ret > 0 && filter) {
4180 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4181
4182 flt_update_offsets(filter, chn, ret);
4183 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
4184 }
4185
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004186 lua_pushinteger(L, ret);
4187 return 1;
4188}
4189
4190/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02004191 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004192 * returns the length of the written string, or -1 if the channel is closed or
4193 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004194 *
4195 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004196 */
4197__LJMP static int hlua_channel_insert_data(lua_State *L)
4198{
4199 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004200 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004201 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004202 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004203 int ret, offset;
4204
4205 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
4206 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
4207 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4208 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004209
4210 output = co_data(chn);
4211 input = ci_data(chn);
4212
4213 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4214 if (filter && !hlua_filter_from_payload(filter))
4215 WILL_LJMP(lua_error(L));
4216
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02004217 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004218 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004219 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004220 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004221 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004222 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02004223 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004224 lua_pushfstring(L, "offset out of range.");
4225 WILL_LJMP(lua_error(L));
4226 }
4227 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004228 if (IS_HTX_STRM(chn_strm(chn))) {
4229 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4230 WILL_LJMP(lua_error(L));
4231 }
4232
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004233 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4234 if (ret > 0 && filter) {
4235 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004236
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004237 flt_update_offsets(filter, chn, ret);
4238 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004239 }
4240
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004241 lua_pushinteger(L, ret);
4242 return 1;
4243}
4244/* Replaces a given amount of input data at the given offset by a string
4245 * content. By default all remaining data are removed (offset = 0 and len =
4246 * -1). It returns the length of the written string, or -1 if the channel is
4247 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004248 *
4249 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004250 */
4251__LJMP static int hlua_channel_set_data(lua_State *L)
4252{
4253 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004254 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004255 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004256 size_t sz, input, output;
4257 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004258
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004259 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
4260 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
4261 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4262 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004263
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01004264 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02004265 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01004266 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02004267 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004268
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004269 output = co_data(chn);
4270 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004271
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004272 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4273 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004274 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004275
4276 offset = output;
4277 if (lua_gettop(L) > 2) {
4278 offset = MAY_LJMP(luaL_checkinteger(L, 3));
4279 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004280 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004281 offset += output;
4282 if (offset < output || offset > input + output) {
4283 lua_pushfstring(L, "offset out of range.");
4284 WILL_LJMP(lua_error(L));
4285 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004286 }
4287
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004288 len = output + input - offset;
4289 if (lua_gettop(L) == 4) {
4290 len = MAY_LJMP(luaL_checkinteger(L, 4));
4291 if (!len)
4292 goto set;
4293 if (len == -1)
4294 len = output + input - offset;
4295 if (len < 0 || offset + len > output + input) {
4296 lua_pushfstring(L, "length out of range.");
4297 WILL_LJMP(lua_error(L));
4298 }
4299 }
4300
4301 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02004302 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004303 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02004304 lua_pushinteger(L, -1);
4305 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004306 _hlua_channel_delete(chn, offset, len);
4307 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4308 if (filter) {
4309 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4310
4311 len -= (ret > 0 ? ret : 0);
4312 flt_update_offsets(filter, chn, -len);
4313 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4314 }
4315
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004316 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02004317 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004318 return 1;
4319}
4320
4321/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004322 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004323 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004324 *
4325 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004326 */
4327__LJMP static int hlua_channel_del_data(lua_State *L)
4328{
4329 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004330 struct filter *filter;
4331 size_t input, output;
4332 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004333
4334 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
4335 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
4336 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004337
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004338 if (IS_HTX_STRM(chn_strm(chn))) {
4339 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4340 WILL_LJMP(lua_error(L));
4341 }
4342
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004343 output = co_data(chn);
4344 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004345
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004346 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4347 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004348 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004349
4350 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00004351 if (lua_gettop(L) > 1) {
4352 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004353 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004354 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004355 offset += output;
4356 if (offset < output || offset > input + output) {
4357 lua_pushfstring(L, "offset out of range.");
4358 WILL_LJMP(lua_error(L));
4359 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004360 }
4361
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004362 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00004363 if (lua_gettop(L) == 3) {
4364 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004365 if (!len)
4366 goto end;
4367 if (len == -1)
4368 len = output + input - offset;
4369 if (len < 0 || offset + len > output + input) {
4370 lua_pushfstring(L, "length out of range.");
4371 WILL_LJMP(lua_error(L));
4372 }
4373 }
4374
4375 _hlua_channel_delete(chn, offset, len);
4376 if (filter) {
4377 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4378
4379 flt_update_offsets(filter, chn, -len);
4380 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4381 }
4382
4383 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004384 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02004385 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004386}
4387
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004388/* Append data in the output side of the buffer. This data is immediately
4389 * sent. The function returns the amount of data written. If the buffer
4390 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004391 * if the channel is closed.
4392 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004393__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004394{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004395 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004396 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004397 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004398 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004399 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004400 struct hlua *hlua;
4401
4402 /* Get hlua struct, or NULL if we execute from main lua state */
4403 hlua = hlua_gethlua(L);
4404 if (!hlua) {
4405 lua_pushnil(L);
4406 return 1;
4407 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004408
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004409 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4410 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4411 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004412
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004413 offset = co_data(chn);
4414 len = ci_data(chn);
4415
4416 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4417 if (filter && !hlua_filter_from_payload(filter))
4418 WILL_LJMP(lua_error(L));
4419
4420
Willy Tarreau47860ed2015-03-10 14:07:50 +01004421 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004422 lua_pushinteger(L, -1);
4423 return 1;
4424 }
4425
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004426 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004427 if (len > sz -l) {
4428 if (filter) {
4429 lua_pushinteger(L, -1);
4430 return 1;
4431 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004432 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004433 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004434
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004435 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004436 if (ret == -1) {
4437 lua_pop(L, 1);
4438 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004439 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004440 }
4441 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004442 if (filter) {
4443 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4444
4445
4446 flt_update_offsets(filter, chn, ret);
4447 FLT_OFF(filter, chn) += ret;
4448 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4449 }
4450 else
4451 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004452
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004453 l += ret;
4454 lua_pop(L, 1);
4455 lua_pushinteger(L, l);
4456 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004457
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004458 if (l < sz) {
4459 /* Yield only if the channel's output is not empty.
4460 * Otherwise it means we cannot add more data. */
4461 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004462 return 1;
4463
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004464 /* If we are waiting for space in the response buffer, we
4465 * must set the flag WAKERESWR. This flag required the task
4466 * wake up if any activity is detected on the response buffer.
4467 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004468 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004469 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004470 else
4471 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004472 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004473 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004474
4475 return 1;
4476}
4477
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004478/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004479 * yield the LUA process, and resume it without checking the
4480 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004481 *
4482 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004483 */
4484__LJMP static int hlua_channel_send(lua_State *L)
4485{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004486 struct channel *chn;
4487
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004488 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004489 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4490 if (IS_HTX_STRM(chn_strm(chn))) {
4491 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4492 WILL_LJMP(lua_error(L));
4493 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004494 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004495 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004496}
4497
4498/* This function forward and amount of butes. The data pass from
4499 * the input side of the buffer to the output side, and can be
4500 * forwarded. This function never fails.
4501 *
4502 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004503 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004504 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004505__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004506{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004507 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004508 struct filter *filter;
4509 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004510 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004511 struct hlua *hlua;
4512
4513 /* Get hlua struct, or NULL if we execute from main lua state */
4514 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004515 if (!hlua) {
4516 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004517 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004518 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004519
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004520 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004521 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004522 l = MAY_LJMP(luaL_checkinteger(L, -1));
4523
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004524 offset = co_data(chn);
4525 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004526
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004527 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4528 if (filter && !hlua_filter_from_payload(filter))
4529 WILL_LJMP(lua_error(L));
4530
4531 max = fwd - l;
4532 if (max > len)
4533 max = len;
4534
4535 if (filter) {
4536 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4537
4538 FLT_OFF(filter, chn) += max;
4539 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4540 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4541 }
4542 else
4543 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004544
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004545 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004546 lua_pop(L, 1);
4547 lua_pushinteger(L, l);
4548
4549 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004550 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004551 /* The the input channel or the output channel are closed, we
4552 * must return the amount of data forwarded.
4553 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004554 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004555 return 1;
4556
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004557 /* If we are waiting for space data in the response buffer, we
4558 * must set the flag WAKERESWR. This flag required the task
4559 * wake up if any activity is detected on the response buffer.
4560 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004561 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004562 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004563 else
4564 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004565
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004566 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004567 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004568 }
4569
4570 return 1;
4571}
4572
4573/* Just check the input and prepare the stack for the previous
4574 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004575 *
4576 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004577 */
4578__LJMP static int hlua_channel_forward(lua_State *L)
4579{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004580 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004581
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004582 MAY_LJMP(check_args(L, 2, "forward"));
4583 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4584 if (IS_HTX_STRM(chn_strm(chn))) {
4585 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4586 WILL_LJMP(lua_error(L));
4587 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004588 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004589 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004590}
4591
4592/* Just returns the number of bytes available in the input
4593 * side of the buffer. This function never fails.
4594 */
4595__LJMP static int hlua_channel_get_in_len(lua_State *L)
4596{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004597 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004598 struct filter *filter;
4599 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004600
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004601 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004602 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004603
4604 output = co_data(chn);
4605 input = ci_data(chn);
4606 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4607 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4608 lua_pushinteger(L, input);
4609 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004610 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004611
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004612 lua_pushinteger(L, htx->data - co_data(chn));
4613 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004614 return 1;
4615}
4616
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004617/* Returns true if the channel is full. */
4618__LJMP static int hlua_channel_is_full(lua_State *L)
4619{
4620 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004621
4622 MAY_LJMP(check_args(L, 1, "is_full"));
4623 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004624 /* ignore the reserve, we are not on a producer side (ie in an
4625 * applet).
4626 */
4627 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004628 return 1;
4629}
4630
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004631/* Returns true if the channel may still receive data. */
4632__LJMP static int hlua_channel_may_recv(lua_State *L)
4633{
4634 struct channel *chn;
4635
4636 MAY_LJMP(check_args(L, 1, "may_recv"));
4637 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4638 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4639 return 1;
4640}
4641
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004642/* Returns true if the channel is the response channel. */
4643__LJMP static int hlua_channel_is_resp(lua_State *L)
4644{
4645 struct channel *chn;
4646
4647 MAY_LJMP(check_args(L, 1, "is_resp"));
4648 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4649
4650 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4651 return 1;
4652}
4653
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004654/* Just returns the number of bytes available in the output
4655 * side of the buffer. This function never fails.
4656 */
4657__LJMP static int hlua_channel_get_out_len(lua_State *L)
4658{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004659 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004660 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004661
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004662 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004663 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004664
4665 output = co_data(chn);
4666 input = ci_data(chn);
4667 hlua_channel_filter(L, 1, chn, &output, &input);
4668
4669 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004670 return 1;
4671}
4672
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004673/*
4674 *
4675 *
4676 * Class Fetches
4677 *
4678 *
4679 */
4680
4681/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004682 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004683 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004684__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004685{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004686 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004687}
4688
4689/* This function creates and push in the stack a fetch object according
4690 * with a current TXN.
4691 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004692static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004693{
Willy Tarreau7073c472015-04-06 11:15:40 +02004694 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004695
4696 /* Check stack size. */
4697 if (!lua_checkstack(L, 3))
4698 return 0;
4699
4700 /* Create the object: obj[0] = userdata.
4701 * Note that the base of the Fetches object is the
4702 * transaction object.
4703 */
4704 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004705 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004706 lua_rawseti(L, -2, 0);
4707
Willy Tarreau7073c472015-04-06 11:15:40 +02004708 hsmp->s = txn->s;
4709 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004710 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004711 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004712
4713 /* Pop a class sesison metatable and affect it to the userdata. */
4714 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4715 lua_setmetatable(L, -2);
4716
4717 return 1;
4718}
4719
4720/* This function is an LUA binding. It is called with each sample-fetch.
4721 * It uses closure argument to store the associated sample-fetch. It
4722 * returns only one argument or throws an error. An error is thrown
4723 * only if an error is encountered during the argument parsing. If
4724 * the "sample-fetch" function fails, nil is returned.
4725 */
4726__LJMP static int hlua_run_sample_fetch(lua_State *L)
4727{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004728 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004729 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004730 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004731 int i;
4732 struct sample smp;
4733
4734 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004735 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004736
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004737 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004738 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004739
Thierry FOURNIERca988662015-12-20 18:43:03 +01004740 /* Check execution authorization. */
4741 if (f->use & SMP_USE_HTTP_ANY &&
4742 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4743 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4744 "is not available in Lua services", f->kw);
4745 WILL_LJMP(lua_error(L));
4746 }
4747
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004748 /* Get extra arguments. */
4749 for (i = 0; i < lua_gettop(L) - 1; i++) {
4750 if (i >= ARGM_NBARGS)
4751 break;
4752 hlua_lua2arg(L, i + 2, &args[i]);
4753 }
4754 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004755 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004756
4757 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004758 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004759
4760 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004761 if (f->val_args && !f->val_args(args, NULL)) {
Aurelien DARRAGON03c406c2024-06-03 23:18:24 +02004762 hlua_pushfstring_safe(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004763 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004764 }
4765
4766 /* Initialise the sample. */
4767 memset(&smp, 0, sizeof(smp));
4768
4769 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004770 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004771 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004772 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004773 lua_pushstring(L, "");
4774 else
4775 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004776 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004777 }
4778
4779 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004780 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004781 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004782 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004783 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004784
4785 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004786 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004787 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004788
4789 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004790 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004791 WILL_LJMP(lua_error(L));
4792 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004793}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004794
4795/*
4796 *
4797 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004798 * Class Converters
4799 *
4800 *
4801 */
4802
4803/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004804 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004805 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004806__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004807{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004808 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004809}
4810
4811/* This function creates and push in the stack a Converters object
4812 * according with a current TXN.
4813 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004814static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004815{
Willy Tarreau7073c472015-04-06 11:15:40 +02004816 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004817
4818 /* Check stack size. */
4819 if (!lua_checkstack(L, 3))
4820 return 0;
4821
4822 /* Create the object: obj[0] = userdata.
4823 * Note that the base of the Converters object is the
4824 * same than the TXN object.
4825 */
4826 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004827 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004828 lua_rawseti(L, -2, 0);
4829
Willy Tarreau7073c472015-04-06 11:15:40 +02004830 hsmp->s = txn->s;
4831 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004832 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004833 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004834
Willy Tarreau87b09662015-04-03 00:22:06 +02004835 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004836 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4837 lua_setmetatable(L, -2);
4838
4839 return 1;
4840}
4841
4842/* This function is an LUA binding. It is called with each converter.
4843 * It uses closure argument to store the associated converter. It
4844 * returns only one argument or throws an error. An error is thrown
4845 * only if an error is encountered during the argument parsing. If
4846 * the converter function function fails, nil is returned.
4847 */
4848__LJMP static int hlua_run_sample_conv(lua_State *L)
4849{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004850 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004851 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004852 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004853 int i;
4854 struct sample smp;
4855
4856 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004857 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004858
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004859 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004860 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004861
4862 /* Get extra arguments. */
4863 for (i = 0; i < lua_gettop(L) - 2; i++) {
4864 if (i >= ARGM_NBARGS)
4865 break;
4866 hlua_lua2arg(L, i + 3, &args[i]);
4867 }
4868 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004869 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004870
4871 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004872 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004873
4874 /* Run the special args checker. */
4875 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4876 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004877 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004878 }
4879
4880 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004881 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004882 if (!hlua_lua2smp(L, 2, &smp)) {
4883 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004884 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004885 }
4886
Willy Tarreau1777ea62016-03-10 16:15:46 +01004887 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4888
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004889 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004890 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004891 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004892 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004893 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004894 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004895 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4896 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004897 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004898 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004899 }
4900
4901 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004902 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004903 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004904 lua_pushstring(L, "");
4905 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004906 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004907 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004908 }
4909
4910 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004911 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004912 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004913 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004914 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004915 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004916 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004917 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004918
4919 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004920 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004921 WILL_LJMP(lua_error(L));
4922 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004923}
4924
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004925/*
4926 *
4927 *
4928 * Class AppletTCP
4929 *
4930 *
4931 */
4932
4933/* Returns a struct hlua_txn if the stack entry "ud" is
4934 * a class stream, otherwise it throws an error.
4935 */
4936__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4937{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004938 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004939}
4940
4941/* This function creates and push in the stack an Applet object
4942 * according with a current TXN.
4943 */
4944static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4945{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004946 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004947 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004948 struct proxy *p;
4949
4950 ALREADY_CHECKED(s);
4951 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004952
4953 /* Check stack size. */
4954 if (!lua_checkstack(L, 3))
4955 return 0;
4956
4957 /* Create the object: obj[0] = userdata.
4958 * Note that the base of the Converters object is the
4959 * same than the TXN object.
4960 */
4961 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004962 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004963 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004964 luactx->appctx = ctx;
4965 luactx->htxn.s = s;
4966 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004967
4968 /* Create the "f" field that contains a list of fetches. */
4969 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004970 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004971 return 0;
4972 lua_settable(L, -3);
4973
4974 /* Create the "sf" field that contains a list of stringsafe fetches. */
4975 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004976 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004977 return 0;
4978 lua_settable(L, -3);
4979
4980 /* Create the "c" field that contains a list of converters. */
4981 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004982 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004983 return 0;
4984 lua_settable(L, -3);
4985
4986 /* Create the "sc" field that contains a list of stringsafe converters. */
4987 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004988 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004989 return 0;
4990 lua_settable(L, -3);
4991
4992 /* Pop a class stream metatable and affect it to the table. */
4993 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4994 lua_setmetatable(L, -2);
4995
4996 return 1;
4997}
4998
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004999__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
5000{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005001 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005002 struct stream *s;
5003 const char *name;
5004 size_t len;
5005 struct sample smp;
5006
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005007 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5008 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005009
5010 /* It is useles to retrieve the stream, but this function
5011 * runs only in a stream context.
5012 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005013 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005014 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005015 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005016
5017 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005018 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005019 hlua_lua2smp(L, 3, &smp);
5020
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02005021 /* Store the sample in a variable. We don't need to dup the smp, vars API
5022 * already takes care of duplicating dynamic var data.
5023 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005024 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005025
5026 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5027 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5028 else
5029 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5030
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005031 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005032}
5033
5034__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
5035{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005036 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005037 struct stream *s;
5038 const char *name;
5039 size_t len;
5040 struct sample smp;
5041
5042 MAY_LJMP(check_args(L, 2, "unset_var"));
5043
5044 /* It is useles to retrieve the stream, but this function
5045 * runs only in a stream context.
5046 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005047 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005048 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005049 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005050
5051 /* Unset the variable. */
5052 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005053 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5054 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005055}
5056
5057__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
5058{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005059 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005060 struct stream *s;
5061 const char *name;
5062 size_t len;
5063 struct sample smp;
5064
5065 MAY_LJMP(check_args(L, 2, "get_var"));
5066
5067 /* It is useles to retrieve the stream, but this function
5068 * runs only in a stream context.
5069 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005070 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005071 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005072 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005073
5074 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005075 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005076 lua_pushnil(L);
5077 return 1;
5078 }
5079
Aurelien DARRAGON41217722023-05-17 10:44:47 +02005080 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005081}
5082
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005083__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
5084{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005085 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005086 struct hlua_cli_ctx *cli_ctx = luactx->appctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005087 struct stream *s = luactx->htxn.s;
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005088 struct hlua *hlua = hlua_stream_ctx_get(s, cli_ctx->hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005089
5090 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01005091 if (!hlua)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005092 return 0;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005093
5094 MAY_LJMP(check_args(L, 2, "set_priv"));
5095
5096 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005097 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005098
5099 /* Get and store new value. */
5100 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5101 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5102
5103 return 0;
5104}
5105
5106__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
5107{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005108 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005109 struct hlua_cli_ctx *cli_ctx = luactx->appctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005110 struct stream *s = luactx->htxn.s;
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005111 struct hlua *hlua = hlua_stream_ctx_get(s, cli_ctx->hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005112
5113 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01005114 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005115 lua_pushnil(L);
5116 return 1;
5117 }
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005118
5119 /* Push configuration index in the stack. */
5120 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5121
5122 return 1;
5123}
5124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005125/* If expected data not yet available, it returns a yield. This function
5126 * consumes the data in the buffer. It returns a string containing the
5127 * data. This string can be empty.
5128 */
5129__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
5130{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005131 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005132 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005133 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02005134 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005135 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02005136 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005137 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005138
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005139 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02005140 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005141
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005142 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005143 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005144 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005145 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005146 }
5147
5148 /* End of data: commit the total strings and return. */
5149 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02005150 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005151 return 1;
5152 }
5153
5154 /* Ensure that the block 2 length is usable. */
5155 if (ret == 1)
5156 len2 = 0;
5157
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005158 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005159 luaL_addlstring(&luactx->b, blk1, len1);
5160 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005161
5162 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02005163 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005164 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005165 return 1;
5166}
5167
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005168/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005169__LJMP static int hlua_applet_tcp_getline(lua_State *L)
5170{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005171 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005172
5173 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005174 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005175
5176 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
5177}
5178
5179/* If expected data not yet available, it returns a yield. This function
5180 * consumes the data in the buffer. It returns a string containing the
5181 * data. This string can be empty.
5182 */
5183__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
5184{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005185 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005186 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005187 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005188 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02005189 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005190 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02005191 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005192 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005193
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005194 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02005195 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005196
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005197 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005198 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005199 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005200 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005201 }
5202
5203 /* End of data: commit the total strings and return. */
5204 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02005205 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005206 return 1;
5207 }
5208
5209 /* Ensure that the block 2 length is usable. */
5210 if (ret == 1)
5211 len2 = 0;
5212
5213 if (len == -1) {
5214
5215 /* If len == -1, catenate all the data avalaile and
5216 * yield because we want to get all the data until
5217 * the end of data stream.
5218 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005219 luaL_addlstring(&luactx->b, blk1, len1);
5220 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005221 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02005222 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005223 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005224
5225 } else {
5226
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005227 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005228 if (len1 > len)
5229 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005230 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005231 len -= len1;
5232
5233 /* Copy the second block. */
5234 if (len2 > len)
5235 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005236 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005237 len -= len2;
5238
5239 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02005240 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005241
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005242 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005243 if (len > 0) {
5244 lua_pushinteger(L, len);
5245 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02005246 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005247 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005248 }
5249
5250 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005251 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005252 return 1;
5253 }
5254
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005255 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005256 hlua_pusherror(L, "Lua: internal error");
5257 WILL_LJMP(lua_error(L));
5258 return 0;
5259}
5260
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005261/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005262__LJMP static int hlua_applet_tcp_recv(lua_State *L)
5263{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005264 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005265 int len = -1;
5266
5267 if (lua_gettop(L) > 2)
5268 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5269 if (lua_gettop(L) >= 2) {
5270 len = MAY_LJMP(luaL_checkinteger(L, 2));
5271 lua_pop(L, 1);
5272 }
5273
5274 /* Confirm or set the required length */
5275 lua_pushinteger(L, len);
5276
5277 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005278 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005279
5280 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
5281}
5282
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005283/* Append data in the output side of the buffer. This data is immediately
5284 * sent. The function returns the amount of data written. If the buffer
5285 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005286 * if the channel is closed.
5287 */
5288__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
5289{
5290 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005291 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005292 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
5293 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005294 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005295 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005296 int max;
5297
5298 /* Get the max amount of data which can write as input in the channel. */
5299 max = channel_recv_max(chn);
5300 if (max > (len - l))
5301 max = len - l;
5302
5303 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005304 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005305
5306 /* update counters. */
5307 l += max;
5308 lua_pop(L, 1);
5309 lua_pushinteger(L, l);
5310
5311 /* If some data is not send, declares the situation to the
5312 * applet, and returns a yield.
5313 */
5314 if (l < len) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005315 sc_need_room(sc, channel_recv_max(chn) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005316 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005317 }
5318
5319 return 1;
5320}
5321
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005322/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005323 * yield the LUA process, and resume it without checking the
5324 * input arguments.
5325 */
5326__LJMP static int hlua_applet_tcp_send(lua_State *L)
5327{
5328 MAY_LJMP(check_args(L, 2, "send"));
5329 lua_pushinteger(L, 0);
5330
5331 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
5332}
5333
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005334/*
5335 *
5336 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005337 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005338 *
5339 *
5340 */
5341
5342/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005343 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005344 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005345__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005346{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005347 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005348}
5349
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005350/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005351 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005352 * It relies on the caller to have already reserved the room in ctx->svcctx
5353 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005354 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005355static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005356{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005357 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005358 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01005359 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02005360 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005361 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02005362 struct htx *htx;
5363 struct htx_blk *blk;
5364 struct htx_sl *sl;
5365 struct ist path;
5366 unsigned long long len = 0;
5367 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02005368 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005369
5370 /* Check stack size. */
5371 if (!lua_checkstack(L, 3))
5372 return 0;
5373
5374 /* Create the object: obj[0] = userdata.
5375 * Note that the base of the Converters object is the
5376 * same than the TXN object.
5377 */
5378 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005379 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005380 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005381 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005382 http_ctx->status = 200; /* Default status code returned. */
5383 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005384 luactx->htxn.s = s;
5385 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005386
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005387 /* Create the "f" field that contains a list of fetches. */
5388 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005389 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005390 return 0;
5391 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005392
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005393 /* Create the "sf" field that contains a list of stringsafe fetches. */
5394 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005395 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005396 return 0;
5397 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005398
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005399 /* Create the "c" field that contains a list of converters. */
5400 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005401 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005402 return 0;
5403 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005404
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005405 /* Create the "sc" field that contains a list of stringsafe converters. */
5406 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005407 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005408 return 0;
5409 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005410
Christopher Fauleta2097962019-07-15 16:25:33 +02005411 htx = htxbuf(&s->req.buf);
5412 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005413 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005414 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005415
Christopher Fauleta2097962019-07-15 16:25:33 +02005416 /* Stores the request method. */
5417 lua_pushstring(L, "method");
5418 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5419 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005420
Christopher Fauleta2097962019-07-15 16:25:33 +02005421 /* Stores the http version. */
5422 lua_pushstring(L, "version");
5423 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5424 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005425
Christopher Fauleta2097962019-07-15 16:25:33 +02005426 /* creates an array of headers. hlua_http_get_headers() crates and push
5427 * the array on the top of the stack.
5428 */
5429 lua_pushstring(L, "headers");
5430 htxn.s = s;
5431 htxn.p = px;
5432 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005433 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005434 return 0;
5435 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005436
Amaury Denoyellec453f952021-07-06 11:40:12 +02005437 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5438 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005439 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005440 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005441
Christopher Fauleta2097962019-07-15 16:25:33 +02005442 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005443 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005444 q = p;
5445 while (q < end && *q != '?')
5446 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005447
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005448 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005449 lua_pushstring(L, "path");
5450 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005451 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005452
Christopher Fauleta2097962019-07-15 16:25:33 +02005453 /* Stores the query string. */
5454 lua_pushstring(L, "qs");
5455 if (*q == '?')
5456 q++;
5457 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005458 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005459 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005460
Christopher Fauleta2097962019-07-15 16:25:33 +02005461 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5462 struct htx_blk *blk = htx_get_blk(htx, pos);
5463 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005464
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005465 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005466 break;
5467 if (type == HTX_BLK_DATA)
5468 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005470 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005471 len += htx->extra;
5472
5473 /* Stores the request path. */
5474 lua_pushstring(L, "length");
5475 lua_pushinteger(L, len);
5476 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005477
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005478 /* Create an empty array of HTTP request headers. */
5479 lua_pushstring(L, "response");
5480 lua_newtable(L);
5481 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005482
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005483 /* Pop a class stream metatable and affect it to the table. */
5484 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5485 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005486
5487 return 1;
5488}
5489
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005490__LJMP static int hlua_applet_http_set_var(lua_State *L)
5491{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005492 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005493 struct stream *s;
5494 const char *name;
5495 size_t len;
5496 struct sample smp;
5497
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005498 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5499 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005500
5501 /* It is useles to retrieve the stream, but this function
5502 * runs only in a stream context.
5503 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005504 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005505 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005506 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005507
5508 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005509 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005510 hlua_lua2smp(L, 3, &smp);
5511
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02005512 /* Store the sample in a variable. We don't need to dup the smp, vars API
5513 * already takes care of duplicating dynamic var data.
5514 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005515 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005516
5517 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5518 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5519 else
5520 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5521
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005522 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005523}
5524
5525__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5526{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005527 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005528 struct stream *s;
5529 const char *name;
5530 size_t len;
5531 struct sample smp;
5532
5533 MAY_LJMP(check_args(L, 2, "unset_var"));
5534
5535 /* It is useles to retrieve the stream, but this function
5536 * runs only in a stream context.
5537 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005538 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005539 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005540 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005541
5542 /* Unset the variable. */
5543 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005544 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5545 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005546}
5547
5548__LJMP static int hlua_applet_http_get_var(lua_State *L)
5549{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005550 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005551 struct stream *s;
5552 const char *name;
5553 size_t len;
5554 struct sample smp;
5555
5556 MAY_LJMP(check_args(L, 2, "get_var"));
5557
5558 /* It is useles to retrieve the stream, but this function
5559 * runs only in a stream context.
5560 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005561 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005562 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005563 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005564
5565 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005566 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005567 lua_pushnil(L);
5568 return 1;
5569 }
5570
Aurelien DARRAGON41217722023-05-17 10:44:47 +02005571 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005572}
5573
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005574__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5575{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005576 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005577 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005578 struct stream *s = luactx->htxn.s;
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005579 struct hlua *hlua = hlua_stream_ctx_get(s, http_ctx->hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005580
5581 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01005582 if (!hlua)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005583 return 0;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005584
5585 MAY_LJMP(check_args(L, 2, "set_priv"));
5586
5587 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005588 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005589
5590 /* Get and store new value. */
5591 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5592 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5593
5594 return 0;
5595}
5596
5597__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5598{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005599 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005600 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005601 struct stream *s = luactx->htxn.s;
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +01005602 struct hlua *hlua = hlua_stream_ctx_get(s, http_ctx->hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005603
5604 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +01005605 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005606 lua_pushnil(L);
5607 return 1;
5608 }
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005609
5610 /* Push configuration index in the stack. */
5611 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5612
5613 return 1;
5614}
5615
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005616/* If expected data not yet available, it returns a yield. This function
5617 * consumes the data in the buffer. It returns a string containing the
5618 * data. This string can be empty.
5619 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005620__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005621{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005622 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005623 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005624 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005625 struct htx *htx;
5626 struct htx_blk *blk;
5627 size_t count;
5628 int stop = 0;
5629
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005630 htx = htx_from_buf(&req->buf);
5631 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005632 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005633
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005634 while (count && !stop && blk) {
5635 enum htx_blk_type type = htx_get_blk_type(blk);
5636 uint32_t sz = htx_get_blksz(blk);
5637 struct ist v;
5638 uint32_t vlen;
5639 char *nl;
5640
5641 vlen = sz;
5642 if (vlen > count) {
5643 if (type != HTX_BLK_DATA)
5644 break;
5645 vlen = count;
5646 }
5647
5648 switch (type) {
5649 case HTX_BLK_UNUSED:
5650 break;
5651
5652 case HTX_BLK_DATA:
5653 v = htx_get_blk_value(htx, blk);
5654 v.len = vlen;
5655 nl = istchr(v, '\n');
5656 if (nl != NULL) {
5657 stop = 1;
5658 vlen = nl - v.ptr + 1;
5659 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005660 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005661 break;
5662
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005663 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005664 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005665 stop = 1;
5666 break;
5667
5668 default:
5669 break;
5670 }
5671
Willy Tarreau84240042022-02-28 16:51:23 +01005672 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005673 count -= vlen;
5674 if (sz == vlen)
5675 blk = htx_remove_blk(htx, blk);
5676 else {
5677 htx_cut_data_blk(htx, blk, vlen);
5678 break;
5679 }
5680 }
5681
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005682 /* The message was fully consumed and no more data are expected
5683 * (EOM flag set).
5684 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005685 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005686 stop = 1;
5687
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005688 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005689 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005690 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005691 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005692 }
5693
5694 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005695 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005696 return 1;
5697}
5698
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005699
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005700/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005702{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005703 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005704
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005705 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005706 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005707
Christopher Fauleta2097962019-07-15 16:25:33 +02005708 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005709}
5710
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005711/* If expected data not yet available, it returns a yield. This function
5712 * consumes the data in the buffer. It returns a string containing the
5713 * data. This string can be empty.
5714 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005715__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005716{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005717 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005718 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005719 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005720 struct htx *htx;
5721 struct htx_blk *blk;
5722 size_t count;
5723 int len;
5724
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005725 htx = htx_from_buf(&req->buf);
5726 len = MAY_LJMP(luaL_checkinteger(L, 2));
5727 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005728 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005729 while (count && len && blk) {
5730 enum htx_blk_type type = htx_get_blk_type(blk);
5731 uint32_t sz = htx_get_blksz(blk);
5732 struct ist v;
5733 uint32_t vlen;
5734
5735 vlen = sz;
5736 if (len > 0 && vlen > len)
5737 vlen = len;
5738 if (vlen > count) {
5739 if (type != HTX_BLK_DATA)
5740 break;
5741 vlen = count;
5742 }
5743
5744 switch (type) {
5745 case HTX_BLK_UNUSED:
5746 break;
5747
5748 case HTX_BLK_DATA:
5749 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005750 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005751 break;
5752
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005753 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005754 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005755 len = 0;
5756 break;
5757
5758 default:
5759 break;
5760 }
5761
Willy Tarreau84240042022-02-28 16:51:23 +01005762 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005763 count -= vlen;
5764 if (len > 0)
5765 len -= vlen;
5766 if (sz == vlen)
5767 blk = htx_remove_blk(htx, blk);
5768 else {
5769 htx_cut_data_blk(htx, blk, vlen);
5770 break;
5771 }
5772 }
5773
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005774 /* The message was fully consumed and no more data are expected
5775 * (EOM flag set).
5776 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005777 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005778 len = 0;
5779
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005780 htx_to_buf(htx, &req->buf);
5781
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005782 /* If we are no other data available, yield waiting for new data. */
5783 if (len) {
5784 if (len > 0) {
5785 lua_pushinteger(L, len);
5786 lua_replace(L, 2);
5787 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005788 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005789 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005790 }
5791
5792 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005793 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005794 return 1;
5795}
5796
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005797/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005798__LJMP static int hlua_applet_http_recv(lua_State *L)
5799{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005800 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005801 int len = -1;
5802
5803 /* Check arguments. */
5804 if (lua_gettop(L) > 2)
5805 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5806 if (lua_gettop(L) >= 2) {
5807 len = MAY_LJMP(luaL_checkinteger(L, 2));
5808 lua_pop(L, 1);
5809 }
5810
Christopher Fauleta2097962019-07-15 16:25:33 +02005811 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005812
Christopher Fauleta2097962019-07-15 16:25:33 +02005813 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005814 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005815
Christopher Fauleta2097962019-07-15 16:25:33 +02005816 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005817}
5818
5819/* Append data in the output side of the buffer. This data is immediately
5820 * sent. The function returns the amount of data written. If the buffer
5821 * cannot contain the data, the function yields. The function returns -1
5822 * if the channel is closed.
5823 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005824__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005825{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005826 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005827 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005828 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005829 struct htx *htx = htx_from_buf(&res->buf);
5830 const char *data;
5831 size_t len;
5832 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5833 int max;
5834
Christopher Faulet9060fc02019-07-03 11:39:30 +02005835 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005836 if (!max)
5837 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005838
5839 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5840
5841 /* Get the max amount of data which can write as input in the channel. */
5842 if (max > (len - l))
5843 max = len - l;
5844
5845 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005846 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005847 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005848
5849 /* update counters. */
5850 l += max;
5851 lua_pop(L, 1);
5852 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005853
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005854 /* If some data is not send, declares the situation to the
5855 * applet, and returns a yield.
5856 */
5857 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005858 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005859 htx_to_buf(htx, &res->buf);
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005860 sc_need_room(sc, channel_recv_max(res) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005861 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005862 }
5863
Christopher Fauleta2097962019-07-15 16:25:33 +02005864 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005865 return 1;
5866}
5867
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005868/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005869 * yield the LUA process, and resume it without checking the
5870 * input arguments.
5871 */
5872__LJMP static int hlua_applet_http_send(lua_State *L)
5873{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005874 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005875 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005876
5877 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005878 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005879 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5880 WILL_LJMP(lua_error(L));
5881 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005882
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005883 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005884 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005885
Christopher Fauleta2097962019-07-15 16:25:33 +02005886 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005887}
5888
5889__LJMP static int hlua_applet_http_addheader(lua_State *L)
5890{
5891 const char *name;
5892 int ret;
5893
5894 MAY_LJMP(hlua_checkapplet_http(L, 1));
5895 name = MAY_LJMP(luaL_checkstring(L, 2));
5896 MAY_LJMP(luaL_checkstring(L, 3));
5897
5898 /* Push in the stack the "response" entry. */
5899 ret = lua_getfield(L, 1, "response");
5900 if (ret != LUA_TTABLE) {
5901 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5902 "is expected as an array. %s found", lua_typename(L, ret));
5903 WILL_LJMP(lua_error(L));
5904 }
5905
5906 /* check if the header is already registered if it is not
5907 * the case, register it.
5908 */
5909 ret = lua_getfield(L, -1, name);
5910 if (ret == LUA_TNIL) {
5911
5912 /* Entry not found. */
5913 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5914
5915 /* Insert the new header name in the array in the top of the stack.
5916 * It left the new array in the top of the stack.
5917 */
5918 lua_newtable(L);
5919 lua_pushvalue(L, 2);
5920 lua_pushvalue(L, -2);
5921 lua_settable(L, -4);
5922
5923 } else if (ret != LUA_TTABLE) {
5924
5925 /* corruption error. */
5926 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5927 "is expected as an array. %s found", name, lua_typename(L, ret));
5928 WILL_LJMP(lua_error(L));
5929 }
5930
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005931 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005932 * the header value as new entry.
5933 */
5934 lua_pushvalue(L, 3);
5935 ret = lua_rawlen(L, -2);
5936 lua_rawseti(L, -2, ret + 1);
5937 lua_pushboolean(L, 1);
5938 return 1;
5939}
5940
5941__LJMP static int hlua_applet_http_status(lua_State *L)
5942{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005943 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005944 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005945 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005946 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005947
5948 if (status < 100 || status > 599) {
5949 lua_pushboolean(L, 0);
5950 return 1;
5951 }
5952
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005953 http_ctx->status = status;
5954 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005955 lua_pushboolean(L, 1);
5956 return 1;
5957}
5958
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005959
Christopher Fauleta2097962019-07-15 16:25:33 +02005960__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005961{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005962 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005963 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005964 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005965 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005966 struct htx *htx;
5967 struct htx_sl *sl;
5968 struct h1m h1m;
5969 const char *status, *reason;
5970 const char *name, *value;
5971 size_t nlen, vlen;
5972 unsigned int flags;
5973
5974 /* Send the message at once. */
5975 htx = htx_from_buf(&res->buf);
5976 h1m_init_res(&h1m);
5977
5978 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005979 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5980 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005981 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005982 reason = http_get_reason(http_ctx->status);
5983 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005984 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5985 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5986 }
5987 else {
5988 flags = HTX_SL_F_IS_RESP;
5989 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5990 }
5991 if (!sl) {
5992 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005993 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005994 WILL_LJMP(lua_error(L));
5995 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005996 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005997
5998 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005999 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
6000 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006001 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006002 WILL_LJMP(lua_error(L));
6003 }
6004
6005 /* Browse the list of headers. */
6006 lua_pushnil(L);
6007 while(lua_next(L, -2) != 0) {
6008 /* We expect a string as -2. */
6009 if (lua_type(L, -2) != LUA_TSTRING) {
6010 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006011 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006012 lua_typename(L, lua_type(L, -2)));
6013 WILL_LJMP(lua_error(L));
6014 }
6015 name = lua_tolstring(L, -2, &nlen);
6016
6017 /* We expect an array as -1. */
6018 if (lua_type(L, -1) != LUA_TTABLE) {
6019 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006020 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006021 name,
6022 lua_typename(L, lua_type(L, -1)));
6023 WILL_LJMP(lua_error(L));
6024 }
6025
6026 /* Browse the table who is on the top of the stack. */
6027 lua_pushnil(L);
6028 while(lua_next(L, -2) != 0) {
6029 int id;
6030
6031 /* We expect a number as -2. */
6032 if (lua_type(L, -2) != LUA_TNUMBER) {
6033 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006034 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006035 name,
6036 lua_typename(L, lua_type(L, -2)));
6037 WILL_LJMP(lua_error(L));
6038 }
6039 id = lua_tointeger(L, -2);
6040
6041 /* We expect a string as -2. */
6042 if (lua_type(L, -1) != LUA_TSTRING) {
6043 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006044 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006045 name, id,
6046 lua_typename(L, lua_type(L, -1)));
6047 WILL_LJMP(lua_error(L));
6048 }
6049 value = lua_tolstring(L, -1, &vlen);
6050
6051 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02006052 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
6053 int ret;
6054
6055 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
6056 if (ret < 0) {
6057 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
6058 luactx->appctx->rule->arg.hlua_rule->fcn->name,
6059 name);
6060 WILL_LJMP(lua_error(L));
6061 }
6062 else if (ret == 0)
6063 goto next; /* Skip it */
6064 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006065 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
6066 struct ist v = ist2(value, vlen);
6067 int ret;
6068
6069 ret = h1_parse_cont_len_header(&h1m, &v);
6070 if (ret < 0) {
6071 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006072 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006073 name);
6074 WILL_LJMP(lua_error(L));
6075 }
6076 else if (ret == 0)
6077 goto next; /* Skip it */
6078 }
6079
6080 /* Add a new header */
6081 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
6082 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006083 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006084 name);
6085 WILL_LJMP(lua_error(L));
6086 }
6087 next:
6088 /* Remove the array from the stack, and get next element with a remaining string. */
6089 lua_pop(L, 1);
6090 }
6091
6092 /* Remove the array from the stack, and get next element with a remaining string. */
6093 lua_pop(L, 1);
6094 }
6095
6096 if (h1m.flags & H1_MF_CHNK)
6097 h1m.flags &= ~H1_MF_CLEN;
6098 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
6099 h1m.flags |= H1_MF_XFER_LEN;
6100
6101 /* Uset HTX start-line flags */
6102 if (h1m.flags & H1_MF_XFER_ENC)
6103 flags |= HTX_SL_F_XFER_ENC;
6104 if (h1m.flags & H1_MF_XFER_LEN) {
6105 flags |= HTX_SL_F_XFER_LEN;
6106 if (h1m.flags & H1_MF_CHNK)
6107 flags |= HTX_SL_F_CHNK;
6108 else if (h1m.flags & H1_MF_CLEN)
6109 flags |= HTX_SL_F_CLEN;
6110 if (h1m.body_len == 0)
6111 flags |= HTX_SL_F_BODYLESS;
6112 }
6113 sl->flags |= flags;
6114
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07006115 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006116 * and the status code implies the presence of a message body, we must
6117 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05006118 * for the keepalive compliance. If the applet announces a transfer-encoding
6119 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006120 */
6121 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02006122 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006123 /* Add a new header */
6124 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
6125 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
6126 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006127 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006128 WILL_LJMP(lua_error(L));
6129 }
6130 }
6131
6132 /* Finalize headers. */
6133 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
6134 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02006135 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006136 WILL_LJMP(lua_error(L));
6137 }
6138
6139 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
6140 b_reset(&res->buf);
6141 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
6142 WILL_LJMP(lua_error(L));
6143 }
6144
6145 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01006146 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006147
6148 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02006149 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006150 return 0;
6151
6152}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006153/* We will build the status line and the headers of the HTTP response.
6154 * We will try send at once if its not possible, we give back the hand
6155 * waiting for more room.
6156 */
Christopher Fauleta2097962019-07-15 16:25:33 +02006157__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006158{
Willy Tarreau7e702d12021-04-28 17:59:21 +02006159 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02006160 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02006161 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006162
6163 if (co_data(res)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02006164 sc_need_room(sc, -1);
Christopher Fauleta2097962019-07-15 16:25:33 +02006165 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006166 }
Christopher Fauleta2097962019-07-15 16:25:33 +02006167 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006168}
6169
6170
Christopher Fauleta2097962019-07-15 16:25:33 +02006171__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006172{
Christopher Fauleta2097962019-07-15 16:25:33 +02006173 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006174}
6175
Christopher Fauleta2097962019-07-15 16:25:33 +02006176/*
6177 *
6178 *
6179 * Class HTTP
6180 *
6181 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006182 */
Christopher Fauleta2097962019-07-15 16:25:33 +02006183
6184/* Returns a struct hlua_txn if the stack entry "ud" is
6185 * a class stream, otherwise it throws an error.
6186 */
6187__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006188{
Christopher Fauleta2097962019-07-15 16:25:33 +02006189 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
6190}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006191
Christopher Fauleta2097962019-07-15 16:25:33 +02006192/* This function creates and push in the stack a HTTP object
6193 * according with a current TXN.
6194 */
6195static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
6196{
6197 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006198
Christopher Fauleta2097962019-07-15 16:25:33 +02006199 /* Check stack size. */
6200 if (!lua_checkstack(L, 3))
6201 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006202
Christopher Fauleta2097962019-07-15 16:25:33 +02006203 /* Create the object: obj[0] = userdata.
6204 * Note that the base of the Converters object is the
6205 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006206 */
Christopher Fauleta2097962019-07-15 16:25:33 +02006207 lua_newtable(L);
6208 htxn = lua_newuserdata(L, sizeof(*htxn));
6209 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006210
6211 htxn->s = txn->s;
6212 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02006213 htxn->dir = txn->dir;
6214 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006215
6216 /* Pop a class stream metatable and affect it to the table. */
6217 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
6218 lua_setmetatable(L, -2);
6219
6220 return 1;
6221}
6222
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006223/* This function creates and returns an array containing the status-line
6224 * elements. This function does not fails.
6225 */
6226__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
6227{
6228 /* Create the table. */
6229 lua_newtable(L);
6230
6231 if (sl->flags & HTX_SL_F_IS_RESP) {
6232 lua_pushstring(L, "version");
6233 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
6234 lua_settable(L, -3);
6235 lua_pushstring(L, "code");
6236 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
6237 lua_settable(L, -3);
6238 lua_pushstring(L, "reason");
6239 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
6240 lua_settable(L, -3);
6241 }
6242 else {
6243 lua_pushstring(L, "method");
6244 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
6245 lua_settable(L, -3);
6246 lua_pushstring(L, "uri");
6247 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
6248 lua_settable(L, -3);
6249 lua_pushstring(L, "version");
6250 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
6251 lua_settable(L, -3);
6252 }
6253 return 1;
6254}
6255
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006256/* This function creates ans returns an array of HTTP headers.
6257 * This function does not fails. It is used as wrapper with the
6258 * 2 following functions.
6259 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006260__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006261{
Christopher Fauleta2097962019-07-15 16:25:33 +02006262 struct htx *htx;
6263 int32_t pos;
6264
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006265 /* Create the table. */
6266 lua_newtable(L);
6267
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006268
Christopher Fauleta2097962019-07-15 16:25:33 +02006269 htx = htxbuf(&msg->chn->buf);
6270 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
6271 struct htx_blk *blk = htx_get_blk(htx, pos);
6272 enum htx_blk_type type = htx_get_blk_type(blk);
6273 struct ist n, v;
6274 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006275
Christopher Fauleta2097962019-07-15 16:25:33 +02006276 if (type == HTX_BLK_HDR) {
6277 n = htx_get_blk_name(htx,blk);
6278 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01006279 }
Christopher Fauleta2097962019-07-15 16:25:33 +02006280 else if (type == HTX_BLK_EOH)
6281 break;
6282 else
6283 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006284
Christopher Fauleta2097962019-07-15 16:25:33 +02006285 /* Check for existing entry:
6286 * assume that the table is on the top of the stack, and
6287 * push the key in the stack, the function lua_gettable()
6288 * perform the lookup.
6289 */
6290 lua_pushlstring(L, n.ptr, n.len);
6291 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01006292
Christopher Fauleta2097962019-07-15 16:25:33 +02006293 switch (lua_type(L, -1)) {
6294 case LUA_TNIL:
6295 /* Table not found, create it. */
6296 lua_pop(L, 1); /* remove the nil value. */
6297 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
6298 lua_newtable(L); /* create and push empty table. */
6299 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
6300 lua_rawseti(L, -2, 0); /* index header value (pop it). */
6301 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01006302 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006303
Christopher Fauleta2097962019-07-15 16:25:33 +02006304 case LUA_TTABLE:
6305 /* Entry found: push the value in the table. */
6306 len = lua_rawlen(L, -1);
6307 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
6308 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
6309 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
6310 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006311
Christopher Fauleta2097962019-07-15 16:25:33 +02006312 default:
6313 /* Other cases are errors. */
6314 hlua_pusherror(L, "internal error during the parsing of headers.");
6315 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006316 }
6317 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006318 return 1;
6319}
6320
6321__LJMP static int hlua_http_req_get_headers(lua_State *L)
6322{
6323 struct hlua_txn *htxn;
6324
6325 MAY_LJMP(check_args(L, 1, "req_get_headers"));
6326 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6327
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006328 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006329 WILL_LJMP(lua_error(L));
6330
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006331 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006332}
6333
6334__LJMP static int hlua_http_res_get_headers(lua_State *L)
6335{
6336 struct hlua_txn *htxn;
6337
6338 MAY_LJMP(check_args(L, 1, "res_get_headers"));
6339 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6340
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006341 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006342 WILL_LJMP(lua_error(L));
6343
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006344 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006345}
6346
6347/* This function replace full header, or just a value in
6348 * the request or in the response. It is a wrapper fir the
6349 * 4 following functions.
6350 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006351__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006352{
6353 size_t name_len;
6354 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6355 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
6356 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02006357 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02006358 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006359
Dragan Dosen26743032019-04-30 15:54:36 +02006360 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006361 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
6362
Christopher Fauleta2097962019-07-15 16:25:33 +02006363 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006364 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02006365 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006366 return 0;
6367}
6368
6369__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
6370{
6371 struct hlua_txn *htxn;
6372
6373 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6374 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6375
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006376 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006377 WILL_LJMP(lua_error(L));
6378
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006379 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006380}
6381
6382__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
6383{
6384 struct hlua_txn *htxn;
6385
6386 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
6387 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6388
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006389 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006390 WILL_LJMP(lua_error(L));
6391
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006392 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006393}
6394
6395__LJMP static int hlua_http_req_rep_val(lua_State *L)
6396{
6397 struct hlua_txn *htxn;
6398
6399 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6400 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6401
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006402 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006403 WILL_LJMP(lua_error(L));
6404
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006405 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006406}
6407
6408__LJMP static int hlua_http_res_rep_val(lua_State *L)
6409{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006410 struct hlua_txn *htxn;
6411
6412 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6413 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6414
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006415 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006416 WILL_LJMP(lua_error(L));
6417
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006418 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006419}
6420
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006421/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006422 * It is a wrapper for the 2 following functions.
6423 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006424__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006425{
6426 size_t len;
6427 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006428 struct htx *htx = htxbuf(&msg->chn->buf);
6429 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006430
Christopher Fauleta2097962019-07-15 16:25:33 +02006431 ctx.blk = NULL;
6432 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6433 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006434 return 0;
6435}
6436
6437__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6438{
6439 struct hlua_txn *htxn;
6440
6441 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6442 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6443
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006444 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006445 WILL_LJMP(lua_error(L));
6446
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006447 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006448}
6449
6450__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6451{
6452 struct hlua_txn *htxn;
6453
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006454 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006455 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6456
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006457 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006458 WILL_LJMP(lua_error(L));
6459
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006460 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006461}
6462
6463/* This function adds an header. It is a wrapper used by
6464 * the 2 following functions.
6465 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006466__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006467{
6468 size_t name_len;
6469 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6470 size_t value_len;
6471 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006472 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006473
Christopher Fauleta2097962019-07-15 16:25:33 +02006474 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6475 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006476 return 0;
6477}
6478
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006479__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6480{
6481 struct hlua_txn *htxn;
6482
6483 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6484 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6485
6486 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6487 WILL_LJMP(lua_error(L));
6488
6489 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6490}
6491
6492__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6493{
6494 struct hlua_txn *htxn;
6495
6496 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6497 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6498
6499 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6500 WILL_LJMP(lua_error(L));
6501
6502 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6503}
6504
6505static int hlua_http_req_set_hdr(lua_State *L)
6506{
6507 struct hlua_txn *htxn;
6508
6509 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6510 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6511
6512 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6513 WILL_LJMP(lua_error(L));
6514
6515 hlua_http_del_hdr(L, &htxn->s->txn->req);
6516 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6517}
6518
6519static int hlua_http_res_set_hdr(lua_State *L)
6520{
6521 struct hlua_txn *htxn;
6522
6523 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6524 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6525
6526 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6527 WILL_LJMP(lua_error(L));
6528
6529 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6530 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6531}
6532
6533/* This function set the method. */
6534static int hlua_http_req_set_meth(lua_State *L)
6535{
6536 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6537 size_t name_len;
6538 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6539
6540 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6541 WILL_LJMP(lua_error(L));
6542
6543 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6544 return 1;
6545}
6546
6547/* This function set the method. */
6548static int hlua_http_req_set_path(lua_State *L)
6549{
6550 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6551 size_t name_len;
6552 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6553
6554 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6555 WILL_LJMP(lua_error(L));
6556
6557 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6558 return 1;
6559}
6560
6561/* This function set the query-string. */
6562static int hlua_http_req_set_query(lua_State *L)
6563{
6564 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6565 size_t name_len;
6566 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6567
6568 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6569 WILL_LJMP(lua_error(L));
6570
6571 /* Check length. */
6572 if (name_len > trash.size - 1) {
6573 lua_pushboolean(L, 0);
6574 return 1;
6575 }
6576
6577 /* Add the mark question as prefix. */
6578 chunk_reset(&trash);
6579 trash.area[trash.data++] = '?';
6580 memcpy(trash.area + trash.data, name, name_len);
6581 trash.data += name_len;
6582
6583 lua_pushboolean(L,
6584 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6585 return 1;
6586}
6587
6588/* This function set the uri. */
6589static int hlua_http_req_set_uri(lua_State *L)
6590{
6591 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6592 size_t name_len;
6593 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6594
6595 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6596 WILL_LJMP(lua_error(L));
6597
6598 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6599 return 1;
6600}
6601
6602/* This function set the response code & optionally reason. */
6603static int hlua_http_res_set_status(lua_State *L)
6604{
6605 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6606 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6607 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6608 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6609
6610 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6611 WILL_LJMP(lua_error(L));
6612
6613 http_res_set_status(code, reason, htxn->s);
6614 return 0;
6615}
6616
6617/*
6618 *
6619 *
6620 * Class HTTPMessage
6621 *
6622 *
6623 */
6624
6625/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6626 * otherwise it throws an error.
6627 */
6628__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6629{
6630 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6631}
6632
6633/* Creates and pushes on the stack a HTTP object according with a current TXN.
6634 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006635static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006636{
6637 /* Check stack size. */
6638 if (!lua_checkstack(L, 3))
6639 return 0;
6640
6641 lua_newtable(L);
6642 lua_pushlightuserdata(L, msg);
6643 lua_rawseti(L, -2, 0);
6644
6645 /* Create the "channel" field that contains the request channel object. */
6646 lua_pushstring(L, "channel");
6647 if (!hlua_channel_new(L, msg->chn))
6648 return 0;
6649 lua_rawset(L, -3);
6650
6651 /* Pop a class stream metatable and affect it to the table. */
6652 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6653 lua_setmetatable(L, -2);
6654
6655 return 1;
6656}
6657
6658/* Helper function returning a filter attached to the HTTP message at the
6659 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006660 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006661 * filled with output and input length respectively.
6662 */
6663static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6664{
6665 struct channel *chn = msg->chn;
6666 struct htx *htx = htxbuf(&chn->buf);
6667 struct filter *filter = NULL;
6668
6669 *offset = co_data(msg->chn);
6670 *len = htx->data - co_data(msg->chn);
6671
6672 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6673 filter = lua_touserdata (L, -1);
6674 if (msg->msg_state >= HTTP_MSG_DATA) {
6675 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6676
6677 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6678 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6679 }
6680 }
6681
6682 lua_pop(L, 1);
6683 return filter;
6684}
6685
6686/* Returns true if the channel attached to the HTTP message is the response
6687 * channel.
6688 */
6689__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6690{
6691 struct http_msg *msg;
6692
6693 MAY_LJMP(check_args(L, 1, "is_resp"));
6694 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6695
6696 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6697 return 1;
6698}
6699
6700/* Returns an array containing the elements status-line of the HTTP message. It relies
6701 * on hlua_http_get_stline().
6702 */
6703__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6704{
6705 struct http_msg *msg;
6706 struct htx *htx;
6707 struct htx_sl *sl;
6708
6709 MAY_LJMP(check_args(L, 1, "get_stline"));
6710 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6711
6712 if (msg->msg_state > HTTP_MSG_BODY)
6713 WILL_LJMP(lua_error(L));
6714
6715 htx = htxbuf(&msg->chn->buf);
6716 sl = http_get_stline(htx);
6717 if (!sl)
6718 return 0;
6719 return hlua_http_get_stline(L, sl);
6720}
6721
6722/* Returns an array containing all headers of the HTTP message. it relies on
6723 * hlua_http_get_headers().
6724 */
6725__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6726{
6727 struct http_msg *msg;
6728
6729 MAY_LJMP(check_args(L, 1, "get_headers"));
6730 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6731
6732 if (msg->msg_state > HTTP_MSG_BODY)
6733 WILL_LJMP(lua_error(L));
6734
6735 return hlua_http_get_headers(L, msg);
6736}
6737
6738/* Deletes all occurrences of an header in the HTTP message matching on its
6739 * name. It relies on hlua_http_del_hdr().
6740 */
6741__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6742{
6743 struct http_msg *msg;
6744
6745 MAY_LJMP(check_args(L, 2, "del_header"));
6746 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6747
6748 if (msg->msg_state > HTTP_MSG_BODY)
6749 WILL_LJMP(lua_error(L));
6750
6751 return hlua_http_del_hdr(L, msg);
6752}
6753
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006754/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006755 * message given its name against a regex and replaces it if it matches. It
6756 * relies on hlua_http_rep_hdr().
6757 */
6758__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6759{
6760 struct http_msg *msg;
6761
6762 MAY_LJMP(check_args(L, 4, "rep_header"));
6763 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6764
6765 if (msg->msg_state > HTTP_MSG_BODY)
6766 WILL_LJMP(lua_error(L));
6767
6768 return hlua_http_rep_hdr(L, msg, 1);
6769}
6770
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006771/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 * message given its name against a regex and replaces it if it matches. It
6773 * relies on hlua_http_rep_hdr().
6774 */
6775__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6776{
6777 struct http_msg *msg;
6778
6779 MAY_LJMP(check_args(L, 4, "rep_value"));
6780 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6781
6782 if (msg->msg_state > HTTP_MSG_BODY)
6783 WILL_LJMP(lua_error(L));
6784
6785 return hlua_http_rep_hdr(L, msg, 0);
6786}
6787
6788/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6789__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6790{
6791 struct http_msg *msg;
6792
6793 MAY_LJMP(check_args(L, 3, "add_header"));
6794 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6795
6796 if (msg->msg_state > HTTP_MSG_BODY)
6797 WILL_LJMP(lua_error(L));
6798
6799 return hlua_http_add_hdr(L, msg);
6800}
6801
6802/* Add an header in the HTTP message removing existing headers with the same
6803 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6804 */
6805__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6806{
6807 struct http_msg *msg;
6808
6809 MAY_LJMP(check_args(L, 3, "set_header"));
6810 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6811
6812 if (msg->msg_state > HTTP_MSG_BODY)
6813 WILL_LJMP(lua_error(L));
6814
6815 hlua_http_del_hdr(L, msg);
6816 return hlua_http_add_hdr(L, msg);
6817}
6818
6819/* Rewrites the request method. It relies on http_req_replace_stline(). */
6820__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6821{
6822 struct stream *s;
6823 struct http_msg *msg;
6824 const char *name;
6825 size_t name_len;
6826
6827 MAY_LJMP(check_args(L, 2, "set_method"));
6828 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6829 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6830
6831 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6832 WILL_LJMP(lua_error(L));
6833
6834 s = chn_strm(msg->chn);
6835 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6836 return 1;
6837}
6838
6839/* Rewrites the request path. It relies on http_req_replace_stline(). */
6840__LJMP static int hlua_http_msg_set_path(lua_State *L)
6841{
6842 struct stream *s;
6843 struct http_msg *msg;
6844 const char *name;
6845 size_t name_len;
6846
6847 MAY_LJMP(check_args(L, 2, "set_path"));
6848 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6849 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6850
6851 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6852 WILL_LJMP(lua_error(L));
6853
6854 s = chn_strm(msg->chn);
6855 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6856 return 1;
6857}
6858
6859/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6860__LJMP static int hlua_http_msg_set_query(lua_State *L)
6861{
6862 struct stream *s;
6863 struct http_msg *msg;
6864 const char *name;
6865 size_t name_len;
6866
6867 MAY_LJMP(check_args(L, 2, "set_query"));
6868 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6869 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6870
6871 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6872 WILL_LJMP(lua_error(L));
6873
6874 /* Check length. */
6875 if (name_len > trash.size - 1) {
6876 lua_pushboolean(L, 0);
6877 return 1;
6878 }
6879
6880 /* Add the mark question as prefix. */
6881 chunk_reset(&trash);
6882 trash.area[trash.data++] = '?';
6883 memcpy(trash.area + trash.data, name, name_len);
6884 trash.data += name_len;
6885
6886 s = chn_strm(msg->chn);
6887 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6888 return 1;
6889}
6890
6891/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6892__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6893{
6894 struct stream *s;
6895 struct http_msg *msg;
6896 const char *name;
6897 size_t name_len;
6898
6899 MAY_LJMP(check_args(L, 2, "set_uri"));
6900 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6901 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6902
6903 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6904 WILL_LJMP(lua_error(L));
6905
6906 s = chn_strm(msg->chn);
6907 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6908 return 1;
6909}
6910
6911/* Rewrites the response status code. It relies on http_res_set_status(). */
6912__LJMP static int hlua_http_msg_set_status(lua_State *L)
6913{
6914 struct http_msg *msg;
6915 unsigned int code;
6916 const char *reason;
6917 size_t reason_len;
6918
6919 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6920 code = MAY_LJMP(luaL_checkinteger(L, 2));
6921 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6922
6923 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6924 WILL_LJMP(lua_error(L));
6925
6926 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6927 return 1;
6928}
6929
6930/* Returns true if the HTTP message is full. */
6931__LJMP static int hlua_http_msg_is_full(lua_State *L)
6932{
6933 struct http_msg *msg;
6934
6935 MAY_LJMP(check_args(L, 1, "is_full"));
6936 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6937 lua_pushboolean(L, channel_full(msg->chn, 0));
6938 return 1;
6939}
6940
6941/* Returns true if the HTTP message may still receive data. */
6942__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6943{
6944 struct http_msg *msg;
6945 struct htx *htx;
6946
6947 MAY_LJMP(check_args(L, 1, "may_recv"));
6948 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6949 htx = htxbuf(&msg->chn->buf);
6950 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6951 return 1;
6952}
6953
6954/* Returns true if the HTTP message EOM was received */
6955__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6956{
6957 struct http_msg *msg;
6958 struct htx *htx;
6959
6960 MAY_LJMP(check_args(L, 1, "may_recv"));
6961 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6962 htx = htxbuf(&msg->chn->buf);
6963 lua_pushboolean(L, !htx_expect_more(htx));
6964 return 1;
6965}
6966
6967/* Returns the number of bytes available in the input side of the HTTP
6968 * message. This function never fails.
6969 */
6970__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6971{
6972 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006973 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006974
6975 MAY_LJMP(check_args(L, 1, "input"));
6976 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006977 hlua_http_msg_filter(L, 1, msg, &output, &input);
6978 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006979 return 1;
6980}
6981
6982/* Returns the number of bytes available in the output side of the HTTP
6983 * message. This function never fails.
6984 */
6985__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6986{
6987 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006988 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006989
6990 MAY_LJMP(check_args(L, 1, "output"));
6991 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006992 hlua_http_msg_filter(L, 1, msg, &output, &input);
6993 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006994 return 1;
6995}
6996
6997/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6998 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006999 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007000 * block. This function is called during the payload filtering, so the headers
7001 * are already scheduled for output (from the filter point of view).
7002 */
7003static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
7004{
7005 struct htx *htx = htxbuf(&msg->chn->buf);
7006 struct htx_blk *blk;
7007 struct htx_ret htxret;
7008 luaL_Buffer b;
7009 int ret = 0;
7010
7011 luaL_buffinit(L, &b);
7012 htxret = htx_find_offset(htx, offset);
7013 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
7014 enum htx_blk_type type = htx_get_blk_type(blk);
7015 struct ist v;
7016
7017 switch (type) {
7018 case HTX_BLK_UNUSED:
7019 break;
7020
7021 case HTX_BLK_DATA:
7022 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02007023 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01007024 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007025
7026 luaL_addlstring(&b, v.ptr, v.len);
7027 ret += v.len;
7028 break;
7029
7030 default:
vishnu0af4bd72021-10-24 06:46:24 +05307031 if (!ret)
7032 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007033 goto end;
7034 }
7035 offset = 0;
7036 }
7037
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007038end:
vishnu0af4bd72021-10-24 06:46:24 +05307039 if (!ret && (htx->flags & HTX_FL_EOM))
7040 goto no_data;
7041 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007042 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05307043
7044 no_data:
7045 /* Remove the empty string and push nil on the stack */
7046 lua_pop(L, 1);
7047 lua_pushnil(L);
7048 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007049}
7050
7051/* Copies the string <str> to the HTTP message <msg> at the offset
7052 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007053 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007054 * the filter context.
7055 */
7056static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
7057{
7058 struct htx *htx = htx_from_buf(&msg->chn->buf);
7059 struct htx_ret htxret;
7060 int /*max, */ret = 0;
7061
7062 /* Nothing to do, just return */
7063 if (unlikely(istlen(str) == 0))
7064 goto end;
7065
7066 if (istlen(str) > htx_free_data_space(htx)) {
7067 ret = -1;
7068 goto end;
7069 }
7070
7071 htxret = htx_find_offset(htx, offset);
7072 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
7073 if (!htx_add_last_data(htx, str))
7074 goto end;
7075 }
7076 else {
7077 struct ist v = htx_get_blk_value(htx, htxret.blk);
7078 v.ptr += htxret.ret;
7079 v.len = 0;
7080 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
7081 goto end;
7082 }
7083 ret = str.len;
7084 if (ret) {
7085 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7086 flt_update_offsets(filter, msg->chn, ret);
7087 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
7088 }
7089
7090 end:
7091 htx_to_buf(htx, &msg->chn->buf);
7092 return ret;
7093}
7094
7095/* Helper function removing at most <len> bytes of DATA blocks at the absolute
7096 * position <offset>. It stops on the first non-DATA HTX block. This function is
7097 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007098 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007099 * update the filter context.
7100 */
7101static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
7102{
7103 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7104 struct htx *htx = htx_from_buf(&msg->chn->buf);
7105 struct htx_blk *blk;
7106 struct htx_ret htxret;
7107 size_t ret = 0;
7108
7109 /* Be sure <len> is always the amount of DATA to remove */
7110 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007111 /* When htx tail type == HTX_BLK_DATA, no need to take care
7112 * of special blocks like HTX_BLK_EOT.
7113 * We simply truncate after offset
7114 * (truncate targeted blk and discard the following ones)
7115 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007116 htx_truncate(htx, offset);
7117 ret = len;
7118 goto end;
7119 }
7120
7121 htxret = htx_find_offset(htx, offset);
7122 blk = htxret.blk;
7123 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007124 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007125 struct ist v;
7126
7127 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
7128 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007129
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007130 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02007131 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007132
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01007133 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007134 /* trimming data in blk: discard everything after the offset
7135 * (replace 'v' with 'IST_NULL')
7136 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02007137 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007138 if (blk && v.len < len) {
7139 /* In this case, caller wants to keep removing data,
7140 * but we need to spare current blk
7141 * because it was already trimmed
7142 */
7143 blk = htx_get_next_blk(htx, blk);
7144 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007145 len -= v.len;
7146 ret += v.len;
7147 }
7148
7149
7150 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007151 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007152 enum htx_blk_type type = htx_get_blk_type(blk);
7153 uint32_t sz = htx_get_blksz(blk);
7154
7155 switch (type) {
7156 case HTX_BLK_UNUSED:
7157 break;
7158
7159 case HTX_BLK_DATA:
7160 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007161 /* don't discard whole blk, only part of it
7162 * (from the beginning)
7163 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007164 htx_cut_data_blk(htx, blk, len);
7165 ret += len;
7166 goto end;
7167 }
7168 break;
7169
7170 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007171 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007172 goto end;
7173 }
7174
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007175 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007176 len -= sz;
7177 ret += sz;
7178 blk = htx_remove_blk(htx, blk);
7179 }
7180
7181end:
7182 flt_update_offsets(filter, msg->chn, -ret);
7183 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7184 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
7185 * to loose the EOM flag if the message is empty.
7186 */
7187}
7188
7189/* Copies input data found in an HTTP message. Unlike the channel function used
7190 * to duplicate raw data, this one can only be called inside a filter, from
7191 * http_payload callback. So it cannot yield. An exception is returned if it is
7192 * called from another callback. If nothing was copied, a nil value is pushed on
7193 * the stack.
7194 */
7195__LJMP static int hlua_http_msg_get_body(lua_State *L)
7196{
7197 struct http_msg *msg;
7198 struct filter *filter;
7199 size_t output, input;
7200 int offset, len;
7201
7202 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
7203 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
7204 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7205
7206 if (msg->msg_state < HTTP_MSG_DATA)
7207 WILL_LJMP(lua_error(L));
7208
7209 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7210 if (!filter || !hlua_filter_from_payload(filter))
7211 WILL_LJMP(lua_error(L));
7212
7213 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
7214 lua_pushnil(L);
7215 return 1;
7216 }
7217
7218 offset = output;
7219 if (lua_gettop(L) > 1) {
7220 offset = MAY_LJMP(luaL_checkinteger(L, 2));
7221 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007222 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007223 offset += output;
7224 if (offset < output || offset > input + output) {
7225 lua_pushfstring(L, "offset out of range.");
7226 WILL_LJMP(lua_error(L));
7227 }
7228 }
7229 len = output + input - offset;
7230 if (lua_gettop(L) == 3) {
7231 len = MAY_LJMP(luaL_checkinteger(L, 3));
7232 if (!len)
7233 goto dup;
7234 if (len == -1)
7235 len = global.tune.bufsize;
7236 if (len < 0) {
7237 lua_pushfstring(L, "length out of range.");
7238 WILL_LJMP(lua_error(L));
7239 }
7240 }
7241
7242 dup:
7243 _hlua_http_msg_dup(msg, L, offset, len);
7244 return 1;
7245}
7246
7247/* Appends a string to the HTTP message, after all existing DATA blocks but
7248 * before the trailers, if any. It returns the amount of data written or -1 if
7249 * nothing was copied. Unlike the channel function used to append data, this one
7250 * can only be called inside a filter, from http_payload callback. So it cannot
7251 * yield. An exception is returned if it is called from another callback.
7252 */
7253__LJMP static int hlua_http_msg_append(lua_State *L)
7254{
7255 struct http_msg *msg;
7256 struct filter *filter;
7257 const char *str;
7258 size_t offset, len, sz;
7259 int ret;
7260
7261 MAY_LJMP(check_args(L, 2, "append"));
7262 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7263
7264 if (msg->msg_state < HTTP_MSG_DATA)
7265 WILL_LJMP(lua_error(L));
7266
7267 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7268 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7269 if (!filter || !hlua_filter_from_payload(filter))
7270 WILL_LJMP(lua_error(L));
7271
7272 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
7273 lua_pushinteger(L, ret);
7274 return 1;
7275}
7276
7277/* Prepends a string to the HTTP message, before all existing DATA blocks. It
7278 * returns the amount of data written or -1 if nothing was copied. Unlike the
7279 * channel function used to prepend data, this one can only be called inside a
7280 * filter, from http_payload callback. So it cannot yield. An exception is
7281 * returned if it is called from another callback.
7282 */
7283__LJMP static int hlua_http_msg_prepend(lua_State *L)
7284{
7285 struct http_msg *msg;
7286 struct filter *filter;
7287 const char *str;
7288 size_t offset, len, sz;
7289 int ret;
7290
7291 MAY_LJMP(check_args(L, 2, "prepend"));
7292 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007293
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007294 if (msg->msg_state < HTTP_MSG_DATA)
7295 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007296
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007297 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7298 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7299 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007300 WILL_LJMP(lua_error(L));
7301
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007302 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7303 lua_pushinteger(L, ret);
7304 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007305}
7306
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007307/* Inserts a string to the HTTP message at a given offset. By default the string
7308 * is appended at the end of DATA blocks. It returns the amount of data written
7309 * or -1 if nothing was copied. Unlike the channel function used to insert data,
7310 * this one can only be called inside a filter, from http_payload callback. So
7311 * it cannot yield. An exception is returned if it is called from another
7312 * callback.
7313 */
7314__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007315{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007316 struct http_msg *msg;
7317 struct filter *filter;
7318 const char *str;
7319 size_t input, output, sz;
7320 int offset;
7321 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007322
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007323 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
7324 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007325 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007326
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007327 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007328 WILL_LJMP(lua_error(L));
7329
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007330 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007331 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007332 if (!filter || !hlua_filter_from_payload(filter))
7333 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007334
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007335 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007336 if (lua_gettop(L) > 2) {
7337 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7338 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007339 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007340 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007341 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007342 lua_pushfstring(L, "offset out of range.");
7343 WILL_LJMP(lua_error(L));
7344 }
7345 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007346
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007347 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7348 lua_pushinteger(L, ret);
7349 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007350}
7351
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007352/* Removes a given amount of data from the HTTP message at a given offset. By
7353 * default all DATA blocks are removed. It returns the amount of data
7354 * removed. Unlike the channel function used to remove data, this one can only
7355 * be called inside a filter, from http_payload callback. So it cannot yield. An
7356 * exception is returned if it is called from another callback.
7357 */
7358__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007359{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007360 struct http_msg *msg;
7361 struct filter *filter;
7362 size_t input, output;
7363 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007364
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007365 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00007366 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007367 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007368
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007369 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007370 WILL_LJMP(lua_error(L));
7371
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007372 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007373 if (!filter || !hlua_filter_from_payload(filter))
7374 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007375
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007376 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00007377 if (lua_gettop(L) > 1) {
7378 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007379 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007380 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007381 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007382 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007383 lua_pushfstring(L, "offset out of range.");
7384 WILL_LJMP(lua_error(L));
7385 }
7386 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007387
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007388 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00007389 if (lua_gettop(L) == 3) {
7390 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007391 if (!len)
7392 goto end;
7393 if (len == -1)
7394 len = output + input - offset;
7395 if (len < 0 || offset + len > output + input) {
7396 lua_pushfstring(L, "length out of range.");
7397 WILL_LJMP(lua_error(L));
7398 }
7399 }
7400
7401 _hlua_http_msg_delete(msg, filter, offset, len);
7402
7403 end:
7404 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007405 return 1;
7406}
7407
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007408/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007409 * all remaining data are removed, accordingly to the filter context. It returns
7410 * the amount of data written or -1 if nothing was copied. Unlike the channel
7411 * function used to replace data, this one can only be called inside a filter,
7412 * from http_payload callback. So it cannot yield. An exception is returned if
7413 * it is called from another callback.
7414 */
7415__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007416{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007417 struct http_msg *msg;
7418 struct filter *filter;
7419 struct htx *htx;
7420 const char *str;
7421 size_t input, output, sz;
7422 int offset, len;
7423 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007424
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007425 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7426 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7427 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7428
7429 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007430 WILL_LJMP(lua_error(L));
7431
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007432 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7433 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7434 if (!filter || !hlua_filter_from_payload(filter))
7435 WILL_LJMP(lua_error(L));
7436
7437 offset = output;
7438 if (lua_gettop(L) > 2) {
7439 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7440 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007441 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007442 offset += output;
7443 if (offset < output || offset > input + output) {
7444 lua_pushfstring(L, "offset out of range.");
7445 WILL_LJMP(lua_error(L));
7446 }
7447 }
7448
7449 len = output + input - offset;
7450 if (lua_gettop(L) == 4) {
7451 len = MAY_LJMP(luaL_checkinteger(L, 4));
7452 if (!len)
7453 goto set;
7454 if (len == -1)
7455 len = output + input - offset;
7456 if (len < 0 || offset + len > output + input) {
7457 lua_pushfstring(L, "length out of range.");
7458 WILL_LJMP(lua_error(L));
7459 }
7460 }
7461
7462 set:
7463 /* Be sure we can copied the string once input data will be removed. */
7464 htx = htx_from_buf(&msg->chn->buf);
7465 if (sz > htx_free_data_space(htx) + len)
7466 lua_pushinteger(L, -1);
7467 else {
7468 _hlua_http_msg_delete(msg, filter, offset, len);
7469 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7470 lua_pushinteger(L, ret);
7471 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007472 return 1;
7473}
7474
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007475/* Prepends data into an HTTP message and forward it, from the filter point of
7476 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7477 * the channel function used to send data, this one can only be called inside a
7478 * filter, from http_payload callback. So it cannot yield. An exception is
7479 * returned if it is called from another callback.
7480 */
7481__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007482{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007483 struct http_msg *msg;
7484 struct filter *filter;
7485 struct htx *htx;
7486 const char *str;
7487 size_t offset, len, sz;
7488 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007489
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007490 MAY_LJMP(check_args(L, 2, "send"));
7491 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7492
7493 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007494 WILL_LJMP(lua_error(L));
7495
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007496 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7497 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7498 if (!filter || !hlua_filter_from_payload(filter))
7499 WILL_LJMP(lua_error(L));
7500
7501 /* Return an error if the channel's output is closed */
7502 if (unlikely(channel_output_closed(msg->chn))) {
7503 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007504 return 1;
7505 }
7506
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007507 htx = htx_from_buf(&msg->chn->buf);
7508 if (sz > htx_free_data_space(htx)) {
7509 lua_pushinteger(L, -1);
7510 return 1;
7511 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007512
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007513 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7514 if (ret > 0) {
7515 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7516
7517 FLT_OFF(filter, msg->chn) += ret;
7518 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7519 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7520 }
7521
7522 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007523 return 1;
7524}
7525
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007526/* Forwards a given amount of bytes. It return -1 if the channel's output is
7527 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7528 * channel function used to forward data, this one can only be called inside a
7529 * filter, from http_payload callback. So it cannot yield. An exception is
7530 * returned if it is called from another callback. All other functions deal with
7531 * DATA block, this one not.
7532*/
7533__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007534{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007535 struct http_msg *msg;
7536 struct filter *filter;
7537 size_t offset, len;
7538 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007539
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007540 MAY_LJMP(check_args(L, 2, "forward"));
7541 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7542
7543 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007544 WILL_LJMP(lua_error(L));
7545
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007546 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7547 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7548 if (!filter || !hlua_filter_from_payload(filter))
7549 WILL_LJMP(lua_error(L));
7550
7551 /* Nothing to do, just return */
7552 if (!fwd)
7553 goto end;
7554
7555 /* Return an error if the channel's output is closed */
7556 if (unlikely(channel_output_closed(msg->chn))) {
7557 ret = -1;
7558 goto end;
7559 }
7560
7561 ret = fwd;
7562 if (ret > len)
7563 ret = len;
7564
7565 if (ret) {
7566 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7567
7568 FLT_OFF(filter, msg->chn) += ret;
7569 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7570 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7571 }
7572
7573 end:
7574 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007575 return 1;
7576}
7577
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007578/* Set EOM flag on the HTX message.
7579 *
7580 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7581 * really know how to do without this feature.
7582 */
7583__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007584{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007585 struct http_msg *msg;
7586 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007587
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007588 MAY_LJMP(check_args(L, 1, "set_eom"));
7589 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7590 htx = htxbuf(&msg->chn->buf);
7591 htx->flags |= HTX_FL_EOM;
7592 return 0;
7593}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007594
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007595/* Unset EOM flag on the HTX message.
7596 *
7597 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7598 * really know how to do without this feature.
7599 */
7600__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7601{
7602 struct http_msg *msg;
7603 struct htx *htx;
7604
7605 MAY_LJMP(check_args(L, 1, "set_eom"));
7606 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7607 htx = htxbuf(&msg->chn->buf);
7608 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007609 return 0;
7610}
7611
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007612/*
7613 *
7614 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007615 * Class HTTPClient
7616 *
7617 *
7618 */
7619__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7620{
7621 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7622}
7623
William Lallemandf77f1de2021-09-28 19:10:38 +02007624
7625/* stops the httpclient and ask it to kill itself */
7626__LJMP static int hlua_httpclient_gc(lua_State *L)
7627{
7628 struct hlua_httpclient *hlua_hc;
7629
7630 MAY_LJMP(check_args(L, 1, "__gc"));
7631
7632 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7633
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007634 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7635 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007636 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007637 hlua_hc->hc = NULL;
7638 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007639
7640 return 0;
7641}
7642
7643
William Lallemand3956c4e2021-09-21 16:25:15 +02007644__LJMP static int hlua_httpclient_new(lua_State *L)
7645{
7646 struct hlua_httpclient *hlua_hc;
7647 struct hlua *hlua;
7648
7649 /* Get hlua struct, or NULL if we execute from main lua state */
7650 hlua = hlua_gethlua(L);
7651 if (!hlua)
7652 return 0;
7653
7654 /* Check stack size. */
7655 if (!lua_checkstack(L, 3)) {
7656 hlua_pusherror(L, "httpclient: full stack");
7657 goto err;
7658 }
7659 /* Create the object: obj[0] = userdata. */
7660 lua_newtable(L);
7661 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7662 lua_rawseti(L, -2, 0);
7663 memset(hlua_hc, 0, sizeof(*hlua_hc));
7664
7665 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7666 if (!hlua_hc->hc)
7667 goto err;
7668
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007669 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007670
William Lallemand3956c4e2021-09-21 16:25:15 +02007671 /* Pop a class stream metatable and affect it to the userdata. */
7672 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7673 lua_setmetatable(L, -2);
7674
7675 return 1;
7676
7677 err:
7678 WILL_LJMP(lua_error(L));
7679 return 0;
7680}
7681
7682
7683/*
7684 * Callback of the httpclient, this callback wakes the lua task up, once the
7685 * httpclient receives some data
7686 *
7687 */
7688
William Lallemandbd5739e2021-10-28 15:41:38 +02007689static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007690{
7691 struct hlua *hlua = hc->caller;
7692
7693 if (!hlua || !hlua->task)
7694 return;
7695
7696 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7697}
7698
7699/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007700 * Fill the lua stack with headers from the httpclient response
7701 * This works the same way as the hlua_http_get_headers() function
7702 */
7703__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7704{
7705 struct http_hdr *hdr;
7706
7707 lua_newtable(L);
7708
William Lallemandef574b22021-10-05 16:19:31 +02007709 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007710 struct ist n, v;
7711 int len;
7712
7713 n = hdr->n;
7714 v = hdr->v;
7715
7716 /* Check for existing entry:
7717 * assume that the table is on the top of the stack, and
7718 * push the key in the stack, the function lua_gettable()
7719 * perform the lookup.
7720 */
7721
7722 lua_pushlstring(L, n.ptr, n.len);
7723 lua_gettable(L, -2);
7724
7725 switch (lua_type(L, -1)) {
7726 case LUA_TNIL:
7727 /* Table not found, create it. */
7728 lua_pop(L, 1); /* remove the nil value. */
7729 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7730 lua_newtable(L); /* create and push empty table. */
7731 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7732 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7733 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7734 break;
7735
7736 case LUA_TTABLE:
7737 /* Entry found: push the value in the table. */
7738 len = lua_rawlen(L, -1);
7739 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7740 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7741 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7742 break;
7743
7744 default:
7745 /* Other cases are errors. */
7746 hlua_pusherror(L, "internal error during the parsing of headers.");
7747 WILL_LJMP(lua_error(L));
7748 }
7749 }
7750 return 1;
7751}
7752
7753/*
William Lallemand746e6f32021-10-06 10:57:44 +02007754 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7755 *
7756 * Caller must free the result
7757 */
7758struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7759{
7760 struct http_hdr hdrs[global.tune.max_http_hdr];
7761 struct http_hdr *result = NULL;
7762 uint32_t hdr_num = 0;
7763
7764 lua_pushnil(L);
7765 while (lua_next(L, -2) != 0) {
7766 struct ist name, value;
7767 const char *n, *v;
7768 size_t nlen, vlen;
7769
7770 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7771 /* Skip element if the key is not a string or if the value is not a table */
7772 goto next_hdr;
7773 }
7774
7775 n = lua_tolstring(L, -2, &nlen);
7776 name = ist2(n, nlen);
7777
7778 /* Loop on header's values */
7779 lua_pushnil(L);
7780 while (lua_next(L, -2)) {
7781 if (!lua_isstring(L, -1)) {
7782 /* Skip the value if it is not a string */
7783 goto next_value;
7784 }
7785
7786 v = lua_tolstring(L, -1, &vlen);
7787 value = ist2(v, vlen);
7788 name = ist2(n, nlen);
7789
7790 hdrs[hdr_num].n = istdup(name);
7791 hdrs[hdr_num].v = istdup(value);
7792
7793 hdr_num++;
7794
7795 next_value:
7796 lua_pop(L, 1);
7797 }
7798
7799 next_hdr:
7800 lua_pop(L, 1);
7801
7802 }
7803
7804 if (hdr_num) {
7805 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007806 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007807 if (!result)
7808 goto skip_headers;
7809 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7810
7811 result[hdr_num].n = IST_NULL;
7812 result[hdr_num].v = IST_NULL;
7813 }
7814
7815skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007816
7817 return result;
7818}
7819
7820
William Lallemandbd5739e2021-10-28 15:41:38 +02007821/*
7822 * For each yield, checks if there is some data in the httpclient and push them
7823 * in the lua buffer, once the httpclient finished its job, push the result on
7824 * the stack
7825 */
7826__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7827{
7828 struct buffer *tr;
7829 int res;
7830 struct hlua *hlua = hlua_gethlua(L);
7831 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7832
7833
7834 tr = get_trash_chunk();
7835
7836 res = httpclient_res_xfer(hlua_hc->hc, tr);
7837 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7838
7839 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7840
7841 luaL_pushresult(&hlua_hc->b);
7842 lua_settable(L, -3);
7843
7844 lua_pushstring(L, "status");
7845 lua_pushinteger(L, hlua_hc->hc->res.status);
7846 lua_settable(L, -3);
7847
7848
7849 lua_pushstring(L, "reason");
7850 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7851 lua_settable(L, -3);
7852
7853 lua_pushstring(L, "headers");
7854 hlua_httpclient_get_headers(L, hlua_hc);
7855 lua_settable(L, -3);
7856
7857 return 1;
7858 }
7859
7860 if (httpclient_data(hlua_hc->hc))
7861 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7862
7863 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7864
7865 return 0;
7866}
7867
7868/*
7869 * Call this when trying to stream a body during a request
7870 */
7871__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7872{
7873 struct hlua *hlua;
7874 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7875 const char *body_str = NULL;
7876 int ret;
7877 int end = 0;
7878 size_t buf_len;
7879 size_t to_send = 0;
7880
7881 hlua = hlua_gethlua(L);
7882
7883 if (!hlua || !hlua->task)
7884 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7885 "'frontend', 'backend' or 'task'"));
7886
7887 ret = lua_getfield(L, -1, "body");
7888 if (ret != LUA_TSTRING)
7889 goto rcv;
7890
7891 body_str = lua_tolstring(L, -1, &buf_len);
7892 lua_pop(L, 1);
7893
Christopher Fauletfc591292022-01-12 14:46:03 +01007894 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007895
7896 if ((hlua_hc->sent + to_send) >= buf_len)
7897 end = 1;
7898
7899 /* the end flag is always set since we are using the whole remaining size */
7900 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7901
7902 if (buf_len > hlua_hc->sent) {
7903 /* still need to process the buffer */
7904 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7905 } else {
7906 goto rcv;
7907 /* we sent the whole request buffer we can recv */
7908 }
7909 return 0;
7910
7911rcv:
7912
7913 /* we return a "res" object */
7914 lua_newtable(L);
7915
William Lallemandbd5739e2021-10-28 15:41:38 +02007916 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007917 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007918
William Lallemand933fe392021-11-04 09:45:58 +01007919 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007920 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7921
7922 return 1;
7923}
William Lallemand746e6f32021-10-06 10:57:44 +02007924
William Lallemand3956c4e2021-09-21 16:25:15 +02007925/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007926 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007927 */
7928
William Lallemanddc2cc902021-10-26 11:43:26 +02007929__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007930{
7931 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007932 struct http_hdr *hdrs = NULL;
7933 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007934 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007935 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007936 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007937 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007938 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007939
7940 hlua = hlua_gethlua(L);
7941
7942 if (!hlua || !hlua->task)
7943 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7944 "'frontend', 'backend' or 'task'"));
7945
William Lallemand746e6f32021-10-06 10:57:44 +02007946 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7947 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7948
William Lallemand4f4f2b72022-02-17 20:00:23 +01007949 hlua_hc = hlua_checkhttpclient(L, 1);
7950
William Lallemand7177a952022-03-03 15:33:12 +01007951 lua_pushnil(L); /* first key */
7952 while (lua_next(L, 2)) {
7953 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7954 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7955 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007956
William Lallemand7177a952022-03-03 15:33:12 +01007957 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7958 if (lua_type(L, -1) != LUA_TSTRING)
7959 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7960 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007961
William Lallemand7177a952022-03-03 15:33:12 +01007962 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7963 if (lua_type(L, -1) != LUA_TNUMBER)
7964 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7965 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007966
William Lallemand7177a952022-03-03 15:33:12 +01007967 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7968 if (lua_type(L, -1) != LUA_TTABLE)
7969 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7970 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007971
William Lallemand7177a952022-03-03 15:33:12 +01007972 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7973 if (lua_type(L, -1) != LUA_TSTRING)
7974 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7975 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007976
William Lallemand7177a952022-03-03 15:33:12 +01007977 } else {
7978 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7979 }
7980 /* removes 'value'; keeps 'key' for next iteration */
7981 lua_pop(L, 1);
7982 }
William Lallemanddec25c32021-10-25 19:48:37 +02007983
William Lallemand746e6f32021-10-06 10:57:44 +02007984 if (!url_str) {
7985 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7986 return 0;
7987 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007988
William Lallemand10a37362022-03-02 16:18:26 +01007989 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007990
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007991 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007992 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007993 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007994
7995 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007996 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7997 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7998 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007999 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02008000
William Lallemandbd5739e2021-10-28 15:41:38 +02008001 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02008002 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02008003 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
8004 }
William Lallemand3956c4e2021-09-21 16:25:15 +02008005
William Lallemandbd5739e2021-10-28 15:41:38 +02008006 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02008007
William Lallemand746e6f32021-10-06 10:57:44 +02008008 /* free the temporary headers array */
8009 hdrs_i = hdrs;
8010 while (hdrs_i && isttest(hdrs_i->n)) {
8011 istfree(&hdrs_i->n);
8012 istfree(&hdrs_i->v);
8013 hdrs_i++;
8014 }
8015 ha_free(&hdrs);
8016
8017
William Lallemand6137a9e2021-10-26 15:01:53 +02008018 if (ret != ERR_NONE) {
8019 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
8020 return 0;
8021 }
8022
William Lallemandc2d3db42022-04-26 11:46:13 +02008023 if (!httpclient_start(hlua_hc->hc))
8024 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02008025
William Lallemandbd5739e2021-10-28 15:41:38 +02008026 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02008027
William Lallemand3956c4e2021-09-21 16:25:15 +02008028 return 0;
8029}
8030
8031/*
William Lallemanddc2cc902021-10-26 11:43:26 +02008032 * Sends an HTTP HEAD request and wait for a response
8033 *
8034 * httpclient:head(url, headers, payload)
8035 */
8036__LJMP static int hlua_httpclient_head(lua_State *L)
8037{
8038 return hlua_httpclient_send(L, HTTP_METH_HEAD);
8039}
8040
8041/*
8042 * Send an HTTP GET request and wait for a response
8043 *
8044 * httpclient:get(url, headers, payload)
8045 */
8046__LJMP static int hlua_httpclient_get(lua_State *L)
8047{
8048 return hlua_httpclient_send(L, HTTP_METH_GET);
8049
8050}
8051
8052/*
8053 * Sends an HTTP PUT request and wait for a response
8054 *
8055 * httpclient:put(url, headers, payload)
8056 */
8057__LJMP static int hlua_httpclient_put(lua_State *L)
8058{
8059 return hlua_httpclient_send(L, HTTP_METH_PUT);
8060}
8061
8062/*
8063 * Send an HTTP POST request and wait for a response
8064 *
8065 * httpclient:post(url, headers, payload)
8066 */
8067__LJMP static int hlua_httpclient_post(lua_State *L)
8068{
8069 return hlua_httpclient_send(L, HTTP_METH_POST);
8070}
8071
8072
8073/*
8074 * Sends an HTTP DELETE request and wait for a response
8075 *
8076 * httpclient:delete(url, headers, payload)
8077 */
8078__LJMP static int hlua_httpclient_delete(lua_State *L)
8079{
8080 return hlua_httpclient_send(L, HTTP_METH_DELETE);
8081}
8082
8083/*
William Lallemand3956c4e2021-09-21 16:25:15 +02008084 *
8085 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008086 * Class TXN
8087 *
8088 *
8089 */
8090
8091/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02008092 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008093 */
8094__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
8095{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008096 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008097}
8098
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008099__LJMP static int hlua_set_var(lua_State *L)
8100{
8101 struct hlua_txn *htxn;
8102 const char *name;
8103 size_t len;
8104 struct sample smp;
8105
Tim Duesterhus4e172c92020-05-19 13:49:42 +02008106 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
8107 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008108
8109 /* It is useles to retrieve the stream, but this function
8110 * runs only in a stream context.
8111 */
8112 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8113 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
8114
8115 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01008116 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008117 hlua_lua2smp(L, 3, &smp);
8118
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02008119 /* Store the sample in a variable. We don't need to dup the smp, vars API
8120 * already takes care of duplicating dynamic var data.
8121 */
Willy Tarreau7560dd42016-03-10 16:28:58 +01008122 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02008123
8124 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
8125 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
8126 else
8127 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
8128
Tim Duesterhus84ebc132020-05-19 13:49:41 +02008129 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008130}
8131
Christopher Faulet85d79c92016-11-09 16:54:56 +01008132__LJMP static int hlua_unset_var(lua_State *L)
8133{
8134 struct hlua_txn *htxn;
8135 const char *name;
8136 size_t len;
8137 struct sample smp;
8138
8139 MAY_LJMP(check_args(L, 2, "unset_var"));
8140
8141 /* It is useles to retrieve the stream, but this function
8142 * runs only in a stream context.
8143 */
8144 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8145 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
8146
8147 /* Unset the variable. */
8148 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02008149 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
8150 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01008151}
8152
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008153__LJMP static int hlua_get_var(lua_State *L)
8154{
8155 struct hlua_txn *htxn;
8156 const char *name;
8157 size_t len;
8158 struct sample smp;
8159
8160 MAY_LJMP(check_args(L, 2, "get_var"));
8161
8162 /* It is useles to retrieve the stream, but this function
8163 * runs only in a stream context.
8164 */
8165 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8166 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
8167
Willy Tarreau7560dd42016-03-10 16:28:58 +01008168 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02008169 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008170 lua_pushnil(L);
8171 return 1;
8172 }
8173
Aurelien DARRAGON41217722023-05-17 10:44:47 +02008174 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008175}
8176
Willy Tarreau59551662015-03-10 14:23:13 +01008177__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008178{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008179 struct hlua *hlua;
8180
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008181 MAY_LJMP(check_args(L, 2, "set_priv"));
8182
Willy Tarreau87b09662015-04-03 00:22:06 +02008183 /* It is useles to retrieve the stream, but this function
8184 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008185 */
8186 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008187
8188 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008189 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008190 if (!hlua)
8191 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008192
8193 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02008194 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008195
8196 /* Get and store new value. */
8197 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
8198 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
8199
8200 return 0;
8201}
8202
Willy Tarreau59551662015-03-10 14:23:13 +01008203__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008204{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008205 struct hlua *hlua;
8206
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008207 MAY_LJMP(check_args(L, 1, "get_priv"));
8208
Willy Tarreau87b09662015-04-03 00:22:06 +02008209 /* It is useles to retrieve the stream, but this function
8210 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008211 */
8212 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008213
8214 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008215 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008216 if (!hlua) {
8217 lua_pushnil(L);
8218 return 1;
8219 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008220
8221 /* Push configuration index in the stack. */
8222 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
8223
8224 return 1;
8225}
8226
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008227/* Create stack entry containing a class TXN. This function
8228 * return 0 if the stack does not contains free slots,
8229 * otherwise it returns 1.
8230 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008231static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008232{
Willy Tarreaude491382015-04-06 11:04:28 +02008233 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008234
8235 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01008236 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008237 return 0;
8238
8239 /* NOTE: The allocation never fails. The failure
8240 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008241 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008242 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01008243 /* Create the object: obj[0] = userdata. */
8244 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02008245 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01008246 lua_rawseti(L, -2, 0);
8247
Willy Tarreaude491382015-04-06 11:04:28 +02008248 htxn->s = s;
8249 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01008250 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008251 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008252
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008253 /* Create the "f" field that contains a list of fetches. */
8254 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01008255 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008256 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008257 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008258
8259 /* Create the "sf" field that contains a list of stringsafe fetches. */
8260 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01008261 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008262 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008263 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008264
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008265 /* Create the "c" field that contains a list of converters. */
8266 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02008267 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008268 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008269 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008270
8271 /* Create the "sc" field that contains a list of stringsafe converters. */
8272 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01008273 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008274 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008275 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008276
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008277 /* Create the "req" field that contains the request channel object. */
8278 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01008279 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008280 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008281 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008282
8283 /* Create the "res" field that contains the response channel object. */
8284 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01008285 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008286 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008287 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008288
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008289 /* Creates the HTTP object is the current proxy allows http. */
8290 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01008291 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02008292 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008293 return 0;
8294 }
8295 else
8296 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008297 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008298
Christopher Faulet78c35472020-02-26 17:14:08 +01008299 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
8300 /* HTTPMessage object are created when a lua TXN is created from
8301 * a filter context only
8302 */
8303
8304 /* Creates the HTTP-Request object is the current proxy allows http. */
8305 lua_pushstring(L, "http_req");
8306 if (p->mode == PR_MODE_HTTP) {
8307 if (!hlua_http_msg_new(L, &s->txn->req))
8308 return 0;
8309 }
8310 else
8311 lua_pushnil(L);
8312 lua_rawset(L, -3);
8313
8314 /* Creates the HTTP-Response object is the current proxy allows http. */
8315 lua_pushstring(L, "http_res");
8316 if (p->mode == PR_MODE_HTTP) {
8317 if (!hlua_http_msg_new(L, &s->txn->rsp))
8318 return 0;
8319 }
8320 else
8321 lua_pushnil(L);
8322 lua_rawset(L, -3);
8323 }
8324
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008325 /* Pop a class sesison metatable and affect it to the userdata. */
8326 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
8327 lua_setmetatable(L, -2);
8328
8329 return 1;
8330}
8331
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008332__LJMP static int hlua_txn_deflog(lua_State *L)
8333{
8334 const char *msg;
8335 struct hlua_txn *htxn;
8336
8337 MAY_LJMP(check_args(L, 2, "deflog"));
8338 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8339 msg = MAY_LJMP(luaL_checkstring(L, 2));
8340
8341 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
8342 return 0;
8343}
8344
8345__LJMP static int hlua_txn_log(lua_State *L)
8346{
8347 int level;
8348 const char *msg;
8349 struct hlua_txn *htxn;
8350
8351 MAY_LJMP(check_args(L, 3, "log"));
8352 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8353 level = MAY_LJMP(luaL_checkinteger(L, 2));
8354 msg = MAY_LJMP(luaL_checkstring(L, 3));
8355
8356 if (level < 0 || level >= NB_LOG_LEVELS)
8357 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8358
8359 hlua_sendlog(htxn->s->be, level, msg);
8360 return 0;
8361}
8362
8363__LJMP static int hlua_txn_log_debug(lua_State *L)
8364{
8365 const char *msg;
8366 struct hlua_txn *htxn;
8367
8368 MAY_LJMP(check_args(L, 2, "Debug"));
8369 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8370 msg = MAY_LJMP(luaL_checkstring(L, 2));
8371 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
8372 return 0;
8373}
8374
8375__LJMP static int hlua_txn_log_info(lua_State *L)
8376{
8377 const char *msg;
8378 struct hlua_txn *htxn;
8379
8380 MAY_LJMP(check_args(L, 2, "Info"));
8381 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8382 msg = MAY_LJMP(luaL_checkstring(L, 2));
8383 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
8384 return 0;
8385}
8386
8387__LJMP static int hlua_txn_log_warning(lua_State *L)
8388{
8389 const char *msg;
8390 struct hlua_txn *htxn;
8391
8392 MAY_LJMP(check_args(L, 2, "Warning"));
8393 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8394 msg = MAY_LJMP(luaL_checkstring(L, 2));
8395 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
8396 return 0;
8397}
8398
8399__LJMP static int hlua_txn_log_alert(lua_State *L)
8400{
8401 const char *msg;
8402 struct hlua_txn *htxn;
8403
8404 MAY_LJMP(check_args(L, 2, "Alert"));
8405 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8406 msg = MAY_LJMP(luaL_checkstring(L, 2));
8407 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8408 return 0;
8409}
8410
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008411__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8412{
8413 struct hlua_txn *htxn;
8414 int ll;
8415
8416 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8417 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8418 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8419
Christopher Faulet12a5ee72024-02-29 15:41:17 +01008420 if (ll < -1 || ll > NB_LOG_LEVELS)
8421 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be one of the following value:"
8422 " core.silent(-1), core.emerg(0), core.alert(1), core.crit(2), core.error(3),"
8423 " core.warning(4), core.notice(5), core.info(6) or core.debug(7)"));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008424
Christopher Faulet12a5ee72024-02-29 15:41:17 +01008425 htxn->s->logs.level = (ll == -1) ? ll : ll + 1;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008426 return 0;
8427}
8428
8429__LJMP static int hlua_txn_set_tos(lua_State *L)
8430{
8431 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008432 int tos;
8433
8434 MAY_LJMP(check_args(L, 2, "set_tos"));
8435 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8436 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8437
Willy Tarreau1a18b542018-12-11 16:37:42 +01008438 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008439 return 0;
8440}
8441
8442__LJMP static int hlua_txn_set_mark(lua_State *L)
8443{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008444 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008445 int mark;
8446
8447 MAY_LJMP(check_args(L, 2, "set_mark"));
8448 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8449 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8450
Lukas Tribus579e3e32019-08-11 18:03:45 +02008451 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008452 return 0;
8453}
8454
Patrick Hemmer268a7072018-05-11 12:52:31 -04008455__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8456{
8457 struct hlua_txn *htxn;
8458
8459 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8460 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8461 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8462 return 0;
8463}
8464
8465__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8466{
8467 struct hlua_txn *htxn;
8468
8469 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8470 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8471 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8472 return 0;
8473}
8474
Christopher Faulet700d9e82020-01-31 12:21:52 +01008475/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008476 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008477 * message and terminate the transaction. It returns 1 on success and 0 on
8478 * error. The Reply must be on top of the stack.
8479 */
8480__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8481{
8482 struct htx *htx;
8483 struct htx_sl *sl;
8484 struct h1m h1m;
8485 const char *status, *reason, *body;
8486 size_t status_len, reason_len, body_len;
8487 int ret, code, flags;
8488
8489 code = 200;
8490 status = "200";
8491 status_len = 3;
8492 ret = lua_getfield(L, -1, "status");
8493 if (ret == LUA_TNUMBER) {
8494 code = lua_tointeger(L, -1);
8495 status = lua_tolstring(L, -1, &status_len);
8496 }
8497 lua_pop(L, 1);
8498
8499 reason = http_get_reason(code);
8500 reason_len = strlen(reason);
8501 ret = lua_getfield(L, -1, "reason");
8502 if (ret == LUA_TSTRING)
8503 reason = lua_tolstring(L, -1, &reason_len);
8504 lua_pop(L, 1);
8505
8506 body = NULL;
8507 body_len = 0;
8508 ret = lua_getfield(L, -1, "body");
8509 if (ret == LUA_TSTRING)
8510 body = lua_tolstring(L, -1, &body_len);
8511 lua_pop(L, 1);
8512
8513 /* Prepare the response before inserting the headers */
8514 h1m_init_res(&h1m);
8515 htx = htx_from_buf(&s->res.buf);
8516 channel_htx_truncate(&s->res, htx);
8517 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8518 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8519 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8520 ist2(status, status_len), ist2(reason, reason_len));
8521 }
8522 else {
8523 flags = HTX_SL_F_IS_RESP;
8524 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8525 ist2(status, status_len), ist2(reason, reason_len));
8526 }
8527 if (!sl)
8528 goto fail;
8529 sl->info.res.status = code;
8530
8531 /* Push in the stack the "headers" entry. */
8532 ret = lua_getfield(L, -1, "headers");
8533 if (ret != LUA_TTABLE)
8534 goto skip_headers;
8535
8536 lua_pushnil(L);
8537 while (lua_next(L, -2) != 0) {
8538 struct ist name, value;
8539 const char *n, *v;
8540 size_t nlen, vlen;
8541
8542 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8543 /* Skip element if the key is not a string or if the value is not a table */
8544 goto next_hdr;
8545 }
8546
8547 n = lua_tolstring(L, -2, &nlen);
8548 name = ist2(n, nlen);
8549 if (isteqi(name, ist("content-length"))) {
8550 /* Always skip content-length header. It will be added
8551 * later with the correct len
8552 */
8553 goto next_hdr;
8554 }
8555
8556 /* Loop on header's values */
8557 lua_pushnil(L);
8558 while (lua_next(L, -2)) {
8559 if (!lua_isstring(L, -1)) {
8560 /* Skip the value if it is not a string */
8561 goto next_value;
8562 }
8563
8564 v = lua_tolstring(L, -1, &vlen);
8565 value = ist2(v, vlen);
8566
8567 if (isteqi(name, ist("transfer-encoding")))
8568 h1_parse_xfer_enc_header(&h1m, value);
8569 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8570 goto fail;
8571
8572 next_value:
8573 lua_pop(L, 1);
8574 }
8575
8576 next_hdr:
8577 lua_pop(L, 1);
8578 }
8579 skip_headers:
8580 lua_pop(L, 1);
8581
8582 /* Update h1m flags: CLEN is set if CHNK is not present */
8583 if (!(h1m.flags & H1_MF_CHNK)) {
8584 const char *clen = ultoa(body_len);
8585
8586 h1m.flags |= H1_MF_CLEN;
8587 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8588 goto fail;
8589 }
8590 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8591 h1m.flags |= H1_MF_XFER_LEN;
8592
8593 /* Update HTX start-line flags */
8594 if (h1m.flags & H1_MF_XFER_ENC)
8595 flags |= HTX_SL_F_XFER_ENC;
8596 if (h1m.flags & H1_MF_XFER_LEN) {
8597 flags |= HTX_SL_F_XFER_LEN;
8598 if (h1m.flags & H1_MF_CHNK)
8599 flags |= HTX_SL_F_CHNK;
8600 else if (h1m.flags & H1_MF_CLEN)
8601 flags |= HTX_SL_F_CLEN;
8602 if (h1m.body_len == 0)
8603 flags |= HTX_SL_F_BODYLESS;
8604 }
8605 sl->flags |= flags;
8606
8607
8608 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008609 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008610 goto fail;
8611
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008612 htx->flags |= HTX_FL_EOM;
8613
Christopher Faulet700d9e82020-01-31 12:21:52 +01008614 /* Now, forward the response and terminate the transaction */
8615 s->txn->status = code;
8616 htx_to_buf(htx, &s->res.buf);
8617 if (!http_forward_proxy_resp(s, 1))
8618 goto fail;
8619
8620 return 1;
8621
8622 fail:
8623 channel_htx_truncate(&s->res, htx);
8624 return 0;
8625}
8626
8627/* Terminate a transaction if called from a lua action. For TCP streams,
8628 * processing is just aborted. Nothing is returned to the client and all
8629 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8630 * is forwarded to the client before terminating the transaction. On success,
8631 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8632 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8633 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008634 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008635__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008636{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008637 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008638 struct stream *s;
8639 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008640
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008641 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008642
Christopher Faulet700d9e82020-01-31 12:21:52 +01008643 /* If the flags NOTERM is set, we cannot terminate the session, so we
8644 * just end the execution of the current lua code. */
8645 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008646 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008647
Christopher Faulet700d9e82020-01-31 12:21:52 +01008648 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008649 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008650 struct channel *req = &s->req;
8651 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008652
Christopher Faulet700d9e82020-01-31 12:21:52 +01008653 channel_auto_read(req);
8654 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008655 channel_erase(req);
8656
Christopher Faulet700d9e82020-01-31 12:21:52 +01008657 channel_auto_read(res);
8658 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008659 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008660
8661 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8662 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008663 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008664
Christopher Faulet700d9e82020-01-31 12:21:52 +01008665 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8666 /* No reply or invalid reply */
8667 s->txn->status = 0;
8668 http_reply_and_close(s, 0, NULL);
8669 }
8670 else {
8671 /* Remove extra args to have the reply on top of the stack */
8672 if (lua_gettop(L) > 2)
8673 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008674
Christopher Faulet700d9e82020-01-31 12:21:52 +01008675 if (!hlua_txn_forward_reply(L, s)) {
8676 if (!(s->flags & SF_ERR_MASK))
8677 s->flags |= SF_ERR_PRXCOND;
8678 lua_pushinteger(L, ACT_RET_ERR);
8679 WILL_LJMP(hlua_done(L));
8680 return 0; /* Never reached */
8681 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008682 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008683
Christopher Faulet700d9e82020-01-31 12:21:52 +01008684 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8685 if (htxn->dir == SMP_OPT_DIR_REQ) {
8686 /* let's log the request time */
Willy Tarreau69530f52023-04-28 09:16:15 +02008687 s->logs.request_ts = now_ns;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008688 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008689 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008690 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008691
Christopher Faulet700d9e82020-01-31 12:21:52 +01008692 done:
8693 if (!(s->flags & SF_ERR_MASK))
8694 s->flags |= SF_ERR_LOCAL;
8695 if (!(s->flags & SF_FINST_MASK))
8696 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008697
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008698 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8699 lua_pushinteger(L, -1);
8700 else
8701 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008702 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008703 return 0;
8704}
8705
Christopher Faulet700d9e82020-01-31 12:21:52 +01008706/*
8707 *
8708 *
8709 * Class REPLY
8710 *
8711 *
8712 */
8713
8714/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8715 * free slots, the function fails and returns 0;
8716 */
8717static int hlua_txn_reply_new(lua_State *L)
8718{
8719 struct hlua_txn *htxn;
8720 const char *reason, *body = NULL;
8721 int ret, status;
8722
8723 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008724 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008725 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8726 WILL_LJMP(lua_error(L));
8727 }
8728
8729 /* Default value */
8730 status = 200;
8731 reason = http_get_reason(status);
8732
8733 if (lua_istable(L, 2)) {
8734 /* load status and reason from the table argument at index 2 */
8735 ret = lua_getfield(L, 2, "status");
8736 if (ret == LUA_TNIL)
8737 goto reason;
8738 else if (ret != LUA_TNUMBER) {
8739 /* invalid status: ignore the reason */
8740 goto body;
8741 }
8742 status = lua_tointeger(L, -1);
8743
8744 reason:
8745 lua_pop(L, 1); /* restore the stack: remove status */
8746 ret = lua_getfield(L, 2, "reason");
8747 if (ret == LUA_TSTRING)
8748 reason = lua_tostring(L, -1);
8749
8750 body:
8751 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8752 ret = lua_getfield(L, 2, "body");
8753 if (ret == LUA_TSTRING)
8754 body = lua_tostring(L, -1);
8755 lua_pop(L, 1); /* restore the stack: remove body */
8756 }
8757
8758 /* Create the Reply table */
8759 lua_newtable(L);
8760
8761 /* Add status element */
8762 lua_pushstring(L, "status");
8763 lua_pushinteger(L, status);
8764 lua_settable(L, -3);
8765
8766 /* Add reason element */
8767 reason = http_get_reason(status);
8768 lua_pushstring(L, "reason");
8769 lua_pushstring(L, reason);
8770 lua_settable(L, -3);
8771
8772 /* Add body element, nil if undefined */
8773 lua_pushstring(L, "body");
8774 if (body)
8775 lua_pushstring(L, body);
8776 else
8777 lua_pushnil(L);
8778 lua_settable(L, -3);
8779
8780 /* Add headers element */
8781 lua_pushstring(L, "headers");
8782 lua_newtable(L);
8783
8784 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8785 if (lua_istable(L, 2)) {
8786 /* load headers from the table argument at index 2. If it is a table, copy it. */
8787 ret = lua_getfield(L, 2, "headers");
8788 if (ret == LUA_TTABLE) {
8789 /* stack: [ ... <headers:table>, <table> ] */
8790 lua_pushnil(L);
8791 while (lua_next(L, -2) != 0) {
8792 /* stack: [ ... <headers:table>, <table>, k, v] */
8793 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8794 /* invalid value type, skip it */
8795 lua_pop(L, 1);
8796 continue;
8797 }
8798
8799
8800 /* Duplicate the key and swap it with the value. */
8801 lua_pushvalue(L, -2);
8802 lua_insert(L, -2);
8803 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8804
8805 lua_newtable(L);
8806 lua_insert(L, -2);
8807 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8808
8809 if (lua_isstring(L, -1)) {
8810 /* push the value in the inner table */
8811 lua_rawseti(L, -2, 1);
8812 }
8813 else { /* table */
8814 lua_pushnil(L);
8815 while (lua_next(L, -2) != 0) {
8816 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8817 if (!lua_isstring(L, -1)) {
8818 /* invalid value type, skip it*/
8819 lua_pop(L, 1);
8820 continue;
8821 }
8822 /* push the value in the inner table */
8823 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8824 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8825 }
8826 lua_pop(L, 1);
8827 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8828 }
8829
8830 /* push (k,v) on the stack in the headers table:
8831 * stack: [ ... <headers:table>, <table>, k, k, v ]
8832 */
8833 lua_settable(L, -5);
8834 /* stack: [ ... <headers:table>, <table>, k ] */
8835 }
8836 }
8837 lua_pop(L, 1);
8838 }
8839 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8840 lua_settable(L, -3);
8841 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8842
8843 /* Pop a class sesison metatable and affect it to the userdata. */
8844 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8845 lua_setmetatable(L, -2);
8846 return 1;
8847}
8848
8849/* Set the reply status code, and optionally the reason. If no reason is
8850 * provided, the default one corresponding to the status code is used.
8851 */
8852__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8853{
8854 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8855 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8856
8857 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008858 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008859
8860 if (status < 100 || status > 599) {
8861 lua_pushboolean(L, 0);
8862 return 1;
8863 }
8864 if (!reason)
8865 reason = http_get_reason(status);
8866
8867 lua_pushinteger(L, status);
8868 lua_setfield(L, 1, "status");
8869
8870 lua_pushstring(L, reason);
8871 lua_setfield(L, 1, "reason");
8872
8873 lua_pushboolean(L, 1);
8874 return 1;
8875}
8876
8877/* Add a header into the reply object. Each header name is associated to an
8878 * array of values in the "headers" table. If the header name is not found, a
8879 * new entry is created.
8880 */
8881__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8882{
8883 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8884 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8885 int ret;
8886
8887 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008888 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008889
8890 /* Push in the stack the "headers" entry. */
8891 ret = lua_getfield(L, 1, "headers");
8892 if (ret != LUA_TTABLE) {
8893 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8894 WILL_LJMP(lua_error(L));
8895 }
8896
8897 /* check if the header is already registered. If not, register it. */
8898 ret = lua_getfield(L, -1, name);
8899 if (ret == LUA_TNIL) {
8900 /* Entry not found. */
8901 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8902
8903 /* Insert the new header name in the array in the top of the stack.
8904 * It left the new array in the top of the stack.
8905 */
8906 lua_newtable(L);
8907 lua_pushstring(L, name);
8908 lua_pushvalue(L, -2);
8909 lua_settable(L, -4);
8910 }
8911 else if (ret != LUA_TTABLE) {
8912 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8913 WILL_LJMP(lua_error(L));
8914 }
8915
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008916 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008917 * the header value as new entry.
8918 */
8919 lua_pushstring(L, value);
8920 ret = lua_rawlen(L, -2);
8921 lua_rawseti(L, -2, ret + 1);
8922
8923 lua_pushboolean(L, 1);
8924 return 1;
8925}
8926
8927/* Remove all occurrences of a given header name. */
8928__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8929{
8930 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8931 int ret;
8932
8933 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008934 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008935
8936 /* Push in the stack the "headers" entry. */
8937 ret = lua_getfield(L, 1, "headers");
8938 if (ret != LUA_TTABLE) {
8939 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8940 WILL_LJMP(lua_error(L));
8941 }
8942
8943 lua_pushstring(L, name);
8944 lua_pushnil(L);
8945 lua_settable(L, -3);
8946
8947 lua_pushboolean(L, 1);
8948 return 1;
8949}
8950
8951/* Set the reply's body. Overwrite any existing entry. */
8952__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8953{
8954 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8955
8956 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008957 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008958
8959 lua_pushstring(L, payload);
8960 lua_setfield(L, 1, "body");
8961
8962 lua_pushboolean(L, 1);
8963 return 1;
8964}
8965
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008966__LJMP static int hlua_log(lua_State *L)
8967{
8968 int level;
8969 const char *msg;
8970
8971 MAY_LJMP(check_args(L, 2, "log"));
8972 level = MAY_LJMP(luaL_checkinteger(L, 1));
8973 msg = MAY_LJMP(luaL_checkstring(L, 2));
8974
8975 if (level < 0 || level >= NB_LOG_LEVELS)
8976 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8977
8978 hlua_sendlog(NULL, level, msg);
8979 return 0;
8980}
8981
8982__LJMP static int hlua_log_debug(lua_State *L)
8983{
8984 const char *msg;
8985
8986 MAY_LJMP(check_args(L, 1, "debug"));
8987 msg = MAY_LJMP(luaL_checkstring(L, 1));
8988 hlua_sendlog(NULL, LOG_DEBUG, msg);
8989 return 0;
8990}
8991
8992__LJMP static int hlua_log_info(lua_State *L)
8993{
8994 const char *msg;
8995
8996 MAY_LJMP(check_args(L, 1, "info"));
8997 msg = MAY_LJMP(luaL_checkstring(L, 1));
8998 hlua_sendlog(NULL, LOG_INFO, msg);
8999 return 0;
9000}
9001
9002__LJMP static int hlua_log_warning(lua_State *L)
9003{
9004 const char *msg;
9005
9006 MAY_LJMP(check_args(L, 1, "warning"));
9007 msg = MAY_LJMP(luaL_checkstring(L, 1));
9008 hlua_sendlog(NULL, LOG_WARNING, msg);
9009 return 0;
9010}
9011
9012__LJMP static int hlua_log_alert(lua_State *L)
9013{
9014 const char *msg;
9015
9016 MAY_LJMP(check_args(L, 1, "alert"));
9017 msg = MAY_LJMP(luaL_checkstring(L, 1));
9018 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01009019 return 0;
9020}
9021
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01009022__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009023{
9024 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02009025 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02009026 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009027 return 0;
9028}
9029
9030__LJMP static int hlua_sleep(lua_State *L)
9031{
9032 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02009033 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009034
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009035 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009036
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01009037 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009038 wakeup_ms = tick_add(now_ms, delay);
9039 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009040
Willy Tarreau9635e032018-10-16 17:52:55 +02009041 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009042 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009043}
9044
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009045__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009046{
9047 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02009048 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009049
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009050 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009051
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01009052 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009053 wakeup_ms = tick_add(now_ms, delay);
9054 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009055
Willy Tarreau9635e032018-10-16 17:52:55 +02009056 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009057 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01009058}
9059
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01009060/* This functionis an LUA binding. it permits to give back
9061 * the hand at the HAProxy scheduler. It is used when the
9062 * LUA processing consumes a lot of time.
9063 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01009064__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009065{
9066 return 0;
9067}
9068
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01009069__LJMP static int hlua_yield(lua_State *L)
9070{
Willy Tarreau9635e032018-10-16 17:52:55 +02009071 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01009072 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01009073}
9074
Thierry FOURNIER37196f42015-02-16 19:34:56 +01009075/* This function change the nice of the currently executed
9076 * task. It is used set low or high priority at the current
9077 * task.
9078 */
Willy Tarreau59551662015-03-10 14:23:13 +01009079__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01009080{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01009081 struct hlua *hlua;
9082 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01009083
Willy Tarreau80f5fae2015-02-27 16:38:20 +01009084 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01009085 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01009086
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009087 /* Get hlua struct, or NULL if we execute from main lua state */
9088 hlua = hlua_gethlua(L);
9089
9090 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01009091 if (!hlua || !hlua->task)
9092 return 0;
9093
9094 if (nice < -1024)
9095 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01009096 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01009097 nice = 1024;
9098
9099 hlua->task->nice = nice;
9100 return 0;
9101}
9102
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +02009103/* safe lua coroutine.create() function:
9104 *
9105 * This is a simple wrapper for coroutine.create() that
9106 * ensures the current hlua state ctx is available from
9107 * the new subroutine state
9108 */
9109__LJMP static int hlua_coroutine_create(lua_State *L)
9110{
9111 lua_State *new; /* new coroutine state */
9112 struct hlua **hlua_store;
9113 struct hlua *hlua = hlua_gethlua(L);
9114
9115 new = lua_newthread(L);
9116 if (!new)
9117 return 0;
9118
9119 hlua_store = lua_getextraspace(new);
9120 /* Expose current hlua ctx on new lua thread
9121 * (hlua_gethlua() will properly return the last "known"
9122 * hlua ctx instead of NULL when it is called from such coroutines)
9123 */
9124 *hlua_store = hlua;
9125
9126 /* new lua thread is on the top of the stack, we
9127 * need to duplicate first stack argument (<f> from coroutine.create(<f>))
9128 * on the top of the stack to be able to use xmove() to move it on the new
9129 * stack
9130 */
9131 lua_pushvalue(L, 1);
9132 /* move <f> function to the new stack */
9133 lua_xmove(L, new, 1);
9134 /* new lua thread is back at the top of the stack */
9135 return 1;
9136}
9137
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009138/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009139 * HAProxy task subsystem when the task is awaked. The LUA runtime can
9140 * return an E_AGAIN signal, the emmiter of this signal must set a
9141 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009142 *
9143 * Task wrapper are longjmp safe because the only one Lua code
9144 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009145 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01009146struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009147{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009148 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009149 enum hlua_exec status;
9150
Willy Tarreau6ef52f42022-06-15 14:19:48 +02009151 if (task->tid < 0)
9152 task->tid = tid;
9153
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009154 /* If it is the first call to the task, we must initialize the
9155 * execution timeouts.
9156 */
9157 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009158 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009159
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009160 /* Execute the Lua code. */
9161 status = hlua_ctx_resume(hlua, 1);
9162
9163 switch (status) {
9164 /* finished or yield */
9165 case HLUA_E_OK:
9166 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02009167 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02009168 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009169 break;
9170
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009171 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01009172 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02009173 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009174 break;
9175
9176 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01009177 case HLUA_E_ETMOUT:
9178 SEND_ERR(NULL, "Lua task: execution timeout.\n");
9179 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009180 case HLUA_E_ERRMSG:
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +01009181 hlua_lock(hlua);
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009182 SEND_ERR(NULL, "Lua task: %s.\n", hlua_tostring_safe(hlua->T, -1));
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +01009183 hlua_unlock(hlua);
Aurelien DARRAGON79544102022-11-24 14:27:15 +01009184 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009185 case HLUA_E_ERR:
9186 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009187 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01009188 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009189 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02009190 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02009191 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009192 break;
9193 }
Emeric Brun253e53e2017-10-17 18:58:40 +02009194 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009195}
9196
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009197/* This function is an LUA binding that register LUA function to be
9198 * executed after the HAProxy configuration parsing and before the
9199 * HAProxy scheduler starts. This function expect only one LUA
9200 * argument that is a function. This function returns nothing, but
9201 * throws if an error is encountered.
9202 */
9203__LJMP static int hlua_register_init(lua_State *L)
9204{
9205 struct hlua_init_function *init;
9206 int ref;
9207
9208 MAY_LJMP(check_args(L, 1, "register_init"));
9209
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009210 if (hlua_gethlua(L)) {
9211 /* runtime processing */
9212 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
9213 }
9214
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009215 ref = MAY_LJMP(hlua_checkfunction(L, 1));
9216
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009217 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009218 if (!init) {
9219 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009220 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009221 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009222
9223 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02009224 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009225 return 0;
9226}
9227
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05009228/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009229 * executed in parallel of the main HAroxy activity. The task is
9230 * created and it is set in the HAProxy scheduler. It can be called
9231 * from the "init" section, "post init" or during the runtime.
9232 *
9233 * Lua prototype:
9234 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009235 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
9236 *
9237 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009238 */
Aurelien DARRAGONe0b16352023-04-21 17:38:37 +02009239__LJMP static int hlua_register_task(lua_State *L)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009240{
Christopher Faulet5294ec02021-04-12 12:24:47 +02009241 struct hlua *hlua = NULL;
9242 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009243 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009244 int nb_arg;
9245 int it;
9246 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01009247 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009248
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009249 nb_arg = lua_gettop(L);
9250 if (nb_arg < 1)
9251 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
9252 else if (nb_arg > 5)
9253 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009254
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009255 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009256 ref = MAY_LJMP(hlua_checkfunction(L, 1));
9257
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009258 /* extract optional args (if any) */
9259 it = 0;
9260 while (--nb_arg) {
9261 lua_pushvalue(L, 2 + it);
9262 arg_ref[it] = hlua_ref(L); /* get arg reference */
9263 it += 1;
9264 }
9265 nb_arg = it;
9266
Thierry Fournier75fc0292020-11-28 13:18:56 +01009267 /* Get the reference state. If the reference is NULL, L is the master
9268 * state, otherwise hlua->T is.
9269 */
9270 hlua = hlua_gethlua(L);
9271 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01009272 /* we are in runtime processing */
9273 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01009274 else
Thierry Fournier021d9862020-11-28 23:42:03 +01009275 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01009276 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01009277
Willy Tarreaubafbe012017-11-24 17:34:44 +01009278 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009279 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02009280 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009281 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009282
Thierry Fournier59f11be2020-11-29 00:37:41 +01009283 /* We are in the common lua state, execute the task anywhere,
9284 * otherwise, inherit the current thread identifier
9285 */
9286 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009287 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01009288 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009289 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02009290 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02009291 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02009292
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009293 task->context = hlua;
9294 task->process = hlua_process_task;
9295
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009296 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02009297 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009298
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009299 /* Ensure there is enough space on the stack for the function
9300 * plus optional arguments
9301 */
9302 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
9303 goto alloc_error;
9304
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009305 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009306 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01009307 /* function ref not needed anymore since it was pushed to the substack */
9308 hlua_unref(L, ref);
9309
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009310 hlua->nargs = nb_arg;
9311
9312 /* push optional arguments to the function */
9313 for (it = 0; it < nb_arg; it++) {
9314 /* push arg to the stack */
9315 hlua_pushref(hlua->T, arg_ref[it]);
9316 /* arg ref not needed anymore since it was pushed to the substack */
9317 hlua_unref(L, arg_ref[it]);
9318 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009319
9320 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02009321 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009322
9323 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02009324
9325 alloc_error:
9326 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009327 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009328 for (it = 0; it < nb_arg; it++) {
9329 hlua_unref(L, arg_ref[it]);
9330 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02009331 hlua_ctx_destroy(hlua);
9332 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9333 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009334}
9335
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009336/* called from unsafe location */
9337static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
9338{
9339 /* hlua cleanup */
9340
9341 hlua_lock(hlua_sub->hlua);
9342 /* registry is shared between coroutines */
9343 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9344 hlua_unlock(hlua_sub->hlua);
9345
9346 hlua_ctx_destroy(hlua_sub->hlua);
9347
9348 /* free */
9349 pool_free(pool_head_hlua_event_sub, hlua_sub);
9350}
9351
9352/* single event handler: hlua ctx is shared between multiple events handlers
9353 * issued from the same subscription. Thus, it is not destroyed when the event
9354 * is processed: it is destroyed when no more events are expected for the
9355 * subscription (ie: when the subscription ends).
9356 *
9357 * Moreover, events are processed sequentially within the subscription:
9358 * one event must be fully processed before another one may be processed.
9359 * This ensures proper consistency for lua event handling from an ordering
9360 * point of view. This is especially useful with server events for example
9361 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
9362 * actions from lua (e.g.: sending emails or making API calls).
9363 *
9364 * Due to this design, each lua event handler is pleased to process the event
9365 * as fast as possible to prevent the event queue from growing up.
9366 * Strictly speaking, there is no runtime limit for the callback function
9367 * (timeout set to default task timeout), but if the event queue goes past
9368 * the limit of unconsumed events an error will be reported and the
9369 * susbscription will pause itself for as long as it takes for the handler to
9370 * catch up (events will be lost as a result).
9371 * If the event handler does not need the sequential ordering and wants to
9372 * process multiple events at a time, it may spawn a new side-task using
9373 * 'core.register_task' to delegate the event handling and make parallel event
9374 * processing within the same subscription set.
9375 */
9376static void hlua_event_handler(struct hlua *hlua)
9377{
9378 enum hlua_exec status;
9379
9380 /* If it is the first call to the task, we must initialize the
9381 * execution timeouts.
9382 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009383 if (!HLUA_IS_RUNNING(hlua))
9384 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009385
9386 /* make sure to reset the task expiry before each hlua_ctx_resume()
9387 * since the task is re-used for multiple cb function calls
9388 * We couldn't risk to have t->expire pointing to a past date because
9389 * it was set during last function invocation but was never reset since
9390 * (ie: E_AGAIN)
9391 */
9392 hlua->task->expire = TICK_ETERNITY;
9393
9394 /* Execute the Lua code. */
9395 status = hlua_ctx_resume(hlua, 1);
9396
9397 switch (status) {
9398 /* finished or yield */
9399 case HLUA_E_OK:
9400 break;
9401
9402 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
9403 notification_gc(&hlua->com);
9404 hlua->task->expire = hlua->wake_time;
9405 break;
9406
9407 /* finished with error. */
9408 case HLUA_E_ETMOUT:
9409 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
9410 break;
9411
9412 case HLUA_E_ERRMSG:
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +01009413 hlua_lock(hlua);
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009414 SEND_ERR(NULL, "Lua event_hdl: %s.\n", hlua_tostring_safe(hlua->T, -1));
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +01009415 hlua_unlock(hlua);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009416 break;
9417
9418 case HLUA_E_ERR:
9419 default:
9420 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
9421 break;
9422 }
9423}
9424
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009425__LJMP static void hlua_event_hdl_cb_push_event_checkres(lua_State *L,
9426 struct event_hdl_cb_data_server_checkres *check)
9427{
9428 lua_pushstring(L, "agent");
9429 lua_pushboolean(L, check->agent);
9430 lua_settable(L, -3);
9431 lua_pushstring(L, "result");
9432 switch (check->result) {
9433 case CHK_RES_FAILED:
9434 lua_pushstring(L, "FAILED");
9435 break;
9436 case CHK_RES_PASSED:
9437 lua_pushstring(L, "PASSED");
9438 break;
9439 case CHK_RES_CONDPASS:
9440 lua_pushstring(L, "CONDPASS");
9441 break;
9442 default:
9443 lua_pushnil(L);
9444 break;
9445 }
9446 lua_settable(L, -3);
9447
9448 lua_pushstring(L, "duration");
9449 lua_pushinteger(L, check->duration);
9450 lua_settable(L, -3);
9451
9452 lua_pushstring(L, "reason");
9453 lua_newtable(L);
9454
9455 lua_pushstring(L, "short");
9456 lua_pushstring(L, get_check_status_info(check->reason.status));
9457 lua_settable(L, -3);
9458 lua_pushstring(L, "desc");
9459 lua_pushstring(L, get_check_status_description(check->reason.status));
9460 lua_settable(L, -3);
9461 if (check->reason.status >= HCHK_STATUS_L57DATA) {
9462 /* code only available when the check reached data analysis stage */
9463 lua_pushstring(L, "code");
9464 lua_pushinteger(L, check->reason.code);
9465 lua_settable(L, -3);
9466 }
9467
9468 lua_settable(L, -3); /* reason table */
9469
9470 lua_pushstring(L, "health");
9471 lua_newtable(L);
9472
9473 lua_pushstring(L, "cur");
9474 lua_pushinteger(L, check->health.cur);
9475 lua_settable(L, -3);
9476 lua_pushstring(L, "rise");
9477 lua_pushinteger(L, check->health.rise);
9478 lua_settable(L, -3);
9479 lua_pushstring(L, "fall");
9480 lua_pushinteger(L, check->health.fall);
9481 lua_settable(L, -3);
9482
9483 lua_settable(L, -3); /* health table */
9484}
9485
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009486/* This function pushes various arguments such as event type and event data to
9487 * the lua function that will be called to consume the event.
9488 */
9489__LJMP static void hlua_event_hdl_cb_push_args(struct hlua_event_sub *hlua_sub,
9490 struct event_hdl_async_event *e)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009491{
9492 struct hlua *hlua = hlua_sub->hlua;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009493 struct event_hdl_sub_type event = e->type;
9494 void *data = e->data;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009495
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009496 /* push event type */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009497 hlua->nargs = 1;
9498 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009499
9500 /* push event data (according to event type) */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009501 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
9502 struct event_hdl_cb_data_server *e_server = data;
9503 struct proxy *px;
9504 struct server *server;
9505
9506 hlua->nargs += 1;
9507 lua_newtable(hlua->T);
9508 /* Add server name */
9509 lua_pushstring(hlua->T, "name");
9510 lua_pushstring(hlua->T, e_server->safe.name);
9511 lua_settable(hlua->T, -3);
9512 /* Add server puid */
9513 lua_pushstring(hlua->T, "puid");
9514 lua_pushinteger(hlua->T, e_server->safe.puid);
9515 lua_settable(hlua->T, -3);
9516 /* Add server rid */
9517 lua_pushstring(hlua->T, "rid");
9518 lua_pushinteger(hlua->T, e_server->safe.rid);
9519 lua_settable(hlua->T, -3);
9520 /* Add server proxy name */
9521 lua_pushstring(hlua->T, "proxy_name");
9522 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9523 lua_settable(hlua->T, -3);
Aurelien DARRAGON55f84c72023-03-22 17:49:04 +01009524 /* Add server proxy uuid */
9525 lua_pushstring(hlua->T, "proxy_uuid");
9526 lua_pushinteger(hlua->T, e_server->safe.proxy_uuid);
9527 lua_settable(hlua->T, -3);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009528
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009529 /* special events, fetch additional info with explicit type casting */
9530 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_STATE, event)) {
9531 struct event_hdl_cb_data_server_state *state = data;
9532 int it;
9533
9534 if (!lua_checkstack(hlua->T, 20))
9535 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9536
9537 /* state subclass */
9538 lua_pushstring(hlua->T, "state");
9539 lua_newtable(hlua->T);
9540
9541 lua_pushstring(hlua->T, "admin");
9542 lua_pushboolean(hlua->T, state->safe.type);
9543 lua_settable(hlua->T, -3);
9544
9545 /* is it because of a check ? */
9546 if (!state->safe.type &&
9547 (state->safe.op_st_chg.cause == SRV_OP_STCHGC_HEALTH ||
9548 state->safe.op_st_chg.cause == SRV_OP_STCHGC_AGENT)) {
9549 /* yes, provide check result */
9550 lua_pushstring(hlua->T, "check");
9551 lua_newtable(hlua->T);
9552 hlua_event_hdl_cb_push_event_checkres(hlua->T, &state->safe.op_st_chg.check);
9553 lua_settable(hlua->T, -3); /* check table */
9554 }
9555
9556 lua_pushstring(hlua->T, "cause");
9557 if (state->safe.type)
9558 lua_pushstring(hlua->T, srv_adm_st_chg_cause(state->safe.adm_st_chg.cause));
9559 else
9560 lua_pushstring(hlua->T, srv_op_st_chg_cause(state->safe.op_st_chg.cause));
9561 lua_settable(hlua->T, -3);
9562
9563 /* old_state, new_state */
9564 for (it = 0; it < 2; it++) {
9565 enum srv_state srv_state = (!it) ? state->safe.old_state : state->safe.new_state;
9566
9567 lua_pushstring(hlua->T, (!it) ? "old_state" : "new_state");
9568 switch (srv_state) {
9569 case SRV_ST_STOPPED:
9570 lua_pushstring(hlua->T, "STOPPED");
9571 break;
9572 case SRV_ST_STOPPING:
9573 lua_pushstring(hlua->T, "STOPPING");
9574 break;
9575 case SRV_ST_STARTING:
9576 lua_pushstring(hlua->T, "STARTING");
9577 break;
9578 case SRV_ST_RUNNING:
9579 lua_pushstring(hlua->T, "RUNNING");
9580 break;
9581 default:
9582 lua_pushnil(hlua->T);
9583 break;
9584 }
9585 lua_settable(hlua->T, -3);
9586 }
9587
9588 /* requeued */
9589 lua_pushstring(hlua->T, "requeued");
9590 lua_pushinteger(hlua->T, state->safe.requeued);
9591 lua_settable(hlua->T, -3);
9592
9593 lua_settable(hlua->T, -3); /* state table */
9594 }
Aurelien DARRAGON948dd3d2023-04-26 11:27:09 +02009595 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_ADMIN, event)) {
9596 struct event_hdl_cb_data_server_admin *admin = data;
9597 int it;
9598
9599 if (!lua_checkstack(hlua->T, 20))
9600 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9601
9602 /* admin subclass */
9603 lua_pushstring(hlua->T, "admin");
9604 lua_newtable(hlua->T);
9605
9606 lua_pushstring(hlua->T, "cause");
9607 lua_pushstring(hlua->T, srv_adm_st_chg_cause(admin->safe.cause));
9608 lua_settable(hlua->T, -3);
9609
9610 /* old_admin, new_admin */
9611 for (it = 0; it < 2; it++) {
9612 enum srv_admin srv_admin = (!it) ? admin->safe.old_admin : admin->safe.new_admin;
9613
9614 lua_pushstring(hlua->T, (!it) ? "old_admin" : "new_admin");
9615
9616 /* admin state matrix */
9617 lua_newtable(hlua->T);
9618
9619 lua_pushstring(hlua->T, "MAINT");
9620 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_MAINT);
9621 lua_settable(hlua->T, -3);
9622 lua_pushstring(hlua->T, "FMAINT");
9623 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FMAINT);
9624 lua_settable(hlua->T, -3);
9625 lua_pushstring(hlua->T, "IMAINT");
9626 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IMAINT);
9627 lua_settable(hlua->T, -3);
9628 lua_pushstring(hlua->T, "RMAINT");
9629 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_RMAINT);
9630 lua_settable(hlua->T, -3);
9631 lua_pushstring(hlua->T, "CMAINT");
9632 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_CMAINT);
9633 lua_settable(hlua->T, -3);
9634
9635 lua_pushstring(hlua->T, "DRAIN");
9636 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_DRAIN);
9637 lua_settable(hlua->T, -3);
9638 lua_pushstring(hlua->T, "FDRAIN");
9639 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FDRAIN);
9640 lua_settable(hlua->T, -3);
9641 lua_pushstring(hlua->T, "IDRAIN");
9642 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IDRAIN);
9643 lua_settable(hlua->T, -3);
9644
9645 lua_settable(hlua->T, -3); /* matrix table */
9646 }
9647 /* requeued */
9648 lua_pushstring(hlua->T, "requeued");
9649 lua_pushinteger(hlua->T, admin->safe.requeued);
9650 lua_settable(hlua->T, -3);
9651
9652 lua_settable(hlua->T, -3); /* admin table */
9653 }
Aurelien DARRAGON0bd53b22023-03-30 15:53:33 +02009654 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_CHECK, event)) {
9655 struct event_hdl_cb_data_server_check *check = data;
9656
9657 if (!lua_checkstack(hlua->T, 20))
9658 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9659
9660 /* check subclass */
9661 lua_pushstring(hlua->T, "check");
9662 lua_newtable(hlua->T);
9663
9664 /* check result snapshot */
9665 hlua_event_hdl_cb_push_event_checkres(hlua->T, &check->safe.res);
9666
9667 lua_settable(hlua->T, -3); /* check table */
9668 }
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009669
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009670 /* attempt to provide reference server object
9671 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9672 */
Aurelien DARRAGON3d9bf4e2023-03-22 17:46:12 +01009673 px = proxy_find_by_id(e_server->safe.proxy_uuid, PR_CAP_BE, 0);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009674 BUG_ON(!px);
9675 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9676 if (server) {
9677 lua_pushstring(hlua->T, "reference");
9678 hlua_fcn_new_server(hlua->T, server);
9679 lua_settable(hlua->T, -3);
9680 }
9681 }
9682 /* sub mgmt */
9683 hlua->nargs += 1;
9684 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
Aurelien DARRAGON096b3832023-04-20 11:32:46 +02009685
9686 /* when? */
9687 hlua->nargs += 1;
9688 lua_pushinteger(hlua->T, e->when.tv_sec);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009689}
9690
9691/* events runner: if there's an ongoing hlua event handling process, finish it
9692 * then, check if there are new events waiting to be processed
9693 * (events are processed sequentially)
9694 *
9695 * We have a safety measure to warn/guard if the event queue is growing up
9696 * too much due to many events being generated and lua handler is unable to
9697 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9698 * TODO: make it tunable
9699 */
9700static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9701{
9702 struct hlua_event_sub *hlua_sub = context;
9703 struct event_hdl_async_event *event;
9704 const char *error = NULL;
9705
9706 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009707 const char *trace = NULL;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009708
9709 /* We reached the limit of pending events in the queue: we should
9710 * warn the user, and temporarily pause the subscription to give a chance
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009711 * to the handler to catch up? (it also prevents resource shortage since
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009712 * the queue could grow indefinitely otherwise)
9713 * TODO: find a way to inform the handler that it missed some events
9714 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9715 *
9716 * Nonetheless, reaching this limit means that the handler is not fast enough
9717 * and/or that it subscribed to events that happen too frequently and did not
9718 * expect it. This could come from an inadequate design in the user's script.
9719 */
9720 event_hdl_pause(hlua_sub->sub);
9721 hlua_sub->paused = 1;
9722
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009723 if (SET_SAFE_LJMP(hlua_sub->hlua)) {
9724 /* The following Lua call may fail. */
9725 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9726 /* At this point the execution is safe. */
9727 RESET_SAFE_LJMP(hlua_sub->hlua);
9728 } else {
9729 /* Lua error was raised while fetching lua trace from current ctx */
9730 SEND_ERR(NULL, "Lua event_hdl: unexpected error (memory failure?).\n");
9731 }
9732 ha_warning("Lua event_hdl: pausing the subscription because the handler fails "
9733 "to keep up the pace (%u unconsumed events) from %s.\n",
9734 event_hdl_async_equeue_size(&hlua_sub->equeue),
9735 (trace) ? trace : "[unknown]");
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009736 }
9737
9738 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9739 /* ongoing hlua event handler, resume it */
9740 hlua_event_handler(hlua_sub->hlua);
9741 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9742 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9743 /* ending event: no more events to come */
9744 event_hdl_async_free_event(event);
9745 task_destroy(task);
9746 hlua_event_subscription_destroy(hlua_sub);
9747 return NULL;
9748 }
9749 /* new event: start processing it */
9750
9751 /* The following Lua calls can fail. */
9752 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +01009753 hlua_lock(hlua_sub->hlua);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009754 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009755 error = hlua_tostring_safe(hlua_sub->hlua->T, -1);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009756 else
9757 error = "critical error";
9758 ha_alert("Lua event_hdl: %s.\n", error);
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +01009759 hlua_unlock(hlua_sub->hlua);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009760 goto skip_event;
9761 }
9762
9763 /* Check stack available size. */
9764 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9765 ha_alert("Lua event_hdl: full stack.\n");
9766 RESET_SAFE_LJMP(hlua_sub->hlua);
9767 goto skip_event;
9768 }
9769
9770 /* Restore the function in the stack. */
9771 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9772
9773 /* push args */
9774 hlua_sub->hlua->nargs = 0;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009775 MAY_LJMP(hlua_event_hdl_cb_push_args(hlua_sub, event));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009776
9777 /* At this point the execution is safe. */
9778 RESET_SAFE_LJMP(hlua_sub->hlua);
9779
9780 /* At this point the event was successfully translated into hlua ctx,
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009781 * or hlua error occurred, so we can safely discard it
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009782 */
9783 event_hdl_async_free_event(event);
9784 event = NULL;
9785
9786 hlua_event_handler(hlua_sub->hlua);
9787 skip_event:
9788 if (event)
9789 event_hdl_async_free_event(event);
9790
9791 }
9792
9793 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9794 /* we just finished the processing of one event..
9795 * check for new events before becoming idle
9796 */
9797 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9798 /* more events to process, make sure the task
9799 * will be resumed ASAP to process pending events
9800 */
9801 task_wakeup(task, TASK_WOKEN_OTHER);
9802 }
9803 else if (hlua_sub->paused) {
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009804 /* empty queue, the handler caught up: resume the subscription */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009805 event_hdl_resume(hlua_sub->sub);
9806 hlua_sub->paused = 0;
9807 }
9808 }
9809
9810 return task;
9811}
9812
9813/* Must be called directly under lua protected/safe environment
9814 * (not from external callback)
9815 * <fcn_ref> should NOT be dropped after the function successfully returns:
9816 * it will be done automatically in hlua_event_subscription_destroy() when the
9817 * subscription ends.
9818 *
9819 * Returns the new subscription on success and NULL on failure (memory error)
9820 */
9821static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9822 int state_id, int fcn_ref)
9823{
9824 struct hlua_event_sub *hlua_sub;
9825 struct task *task = NULL;
9826
9827 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9828 if (!hlua_sub)
9829 goto mem_error;
9830 hlua_sub->task = NULL;
9831 hlua_sub->hlua = NULL;
9832 hlua_sub->paused = 0;
Aurelien DARRAGON98497cd2024-03-04 16:31:23 +01009833 if ((task = task_new_here()) == NULL)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009834 goto mem_error;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009835 task->process = hlua_event_runner;
9836 task->context = hlua_sub;
9837 event_hdl_async_equeue_init(&hlua_sub->equeue);
9838 hlua_sub->task = task;
9839 hlua_sub->fcn_ref = fcn_ref;
9840 hlua_sub->state_id = state_id;
9841 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9842 if (!hlua_sub->hlua)
9843 goto mem_error;
9844 HLUA_INIT(hlua_sub->hlua);
9845 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9846 goto mem_error;
9847
9848 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9849 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9850 task,
9851 hlua_sub,
9852 NULL));
9853 if (!hlua_sub->sub)
9854 goto mem_error;
9855
9856 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9857
9858 mem_error:
9859 if (hlua_sub) {
Tim Duesterhusfe83f582023-04-22 17:47:34 +02009860 task_destroy(hlua_sub->task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009861 if (hlua_sub->hlua)
9862 hlua_ctx_destroy(hlua_sub->hlua);
9863 pool_free(pool_head_hlua_event_sub, hlua_sub);
9864 }
9865
9866 return NULL;
9867}
9868
9869/* looks for an array of strings referring to a composition of event_hdl subscription
9870 * types at <index> in <L> stack
9871 */
9872__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9873{
9874 struct event_hdl_sub_type subscriptions;
9875 const char *msg;
9876
9877 if (lua_type(L, index) != LUA_TTABLE) {
9878 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9879 luaL_argerror(L, index, msg);
9880 }
9881
9882 subscriptions = EVENT_HDL_SUB_NONE;
9883
9884 /* browse the argument as an array. */
9885 lua_pushnil(L);
9886 while (lua_next(L, index) != 0) {
9887 if (lua_type(L, -1) != LUA_TSTRING) {
9888 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9889 luaL_argerror(L, index, msg);
9890 }
9891
9892 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9893 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9894 luaL_argerror(L, index, msg);
9895 }
9896
9897 /* perform subscriptions |= current sub */
9898 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9899
9900 /* pop the current value. */
9901 lua_pop(L, 1);
9902 }
9903
9904 return subscriptions;
9905}
9906
9907/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9908 * the function to prevent LJMP
9909 *
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009910 * If no error occurred, the function returns 1, else it returns 0 and
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009911 * the error message is pushed at the top of the stack
9912 */
9913__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9914{
9915 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9916
9917 /* this function may raise errors */
9918 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9919}
9920static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9921{
9922 if (!lua_checkstack(L, 2))
9923 return 0;
9924 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9925 lua_pushlightuserdata(L, sub);
9926 switch (lua_pcall(L, 1, 1, 0)) {
9927 case LUA_OK:
9928 return 1;
9929 default:
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009930 /* error was caught */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009931 return 0;
9932 }
9933}
9934
9935/* This function is a LUA helper used for registering lua event callbacks.
9936 * It expects an event subscription array and the function to be executed
9937 * when subscribed events occur (stack arguments).
9938 * It can be called from the "init" section, "post init" or during the runtime.
9939 *
9940 * <sub_list> is the subscription list where the subscription will be attempted
9941 *
9942 * Pushes the newly allocated subscription on the stack on success
9943 */
9944__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9945{
9946 struct hlua *hlua;
9947 struct event_hdl_sub *sub;
9948 struct event_hdl_sub_type subscriptions;
9949 int fcn_ref;
9950 int state_id;
9951
9952 MAY_LJMP(check_args(L, 2, "event_sub"));
9953
9954 /* Get the reference state */
9955 hlua = hlua_gethlua(L);
9956 if (hlua)
9957 /* we are in runtime processing, any thread may subscribe to events:
9958 * subscription events will be handled by the thread who performed
9959 * the registration.
9960 */
9961 state_id = hlua->state_id;
9962 else {
9963 /* we are in initialization mode, only thread 0 (actual calling thread)
9964 * may subscribe to events to prevent the same handler (from different lua
9965 * stacks) from being registered multiple times
9966 *
9967 * hlua_state_id == 0: monostack (lua-load)
9968 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9969 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9970 */
9971 if (hlua_state_id > 1)
9972 return 0; /* skip registration */
9973 state_id = hlua_state_id;
9974 }
9975
9976 /* First argument : event subscriptions. */
9977 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9978
9979 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9980 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9981 return 0; /* Never reached */
9982 }
9983
9984 /* Second argument : lua function. */
9985 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9986
9987 /* try to subscribe */
9988 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9989 if (!sub) {
9990 hlua_unref(L, fcn_ref);
9991 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9992 return 0; /* Never reached */
9993 }
9994
9995 /* push the subscription to the stack
9996 *
9997 * Here we use the safe function so that lua errors will be
9998 * handled explicitly to prevent 'sub' from being lost
9999 */
10000 if (!hlua_new_event_sub_safe(L, sub)) {
10001 /* Some events could already be pending in the handler's queue.
10002 * However it is wiser to cancel the subscription since we are unable to
10003 * provide a valid reference to it.
10004 * Pending events will be delivered (unless lua keeps raising errors).
10005 */
10006 event_hdl_unsubscribe(sub); /* cancel the subscription */
10007 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
10008 return 0; /* Never reached */
10009 }
10010 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
10011
10012 return 1;
10013}
10014
10015/* This function is a LUA wrapper used for registering global lua event callbacks
10016 * The new subscription is pushed onto the stack on success
10017 * Returns the number of arguments pushed to the stack (1 for success)
10018 */
10019__LJMP static int hlua_event_global_sub(lua_State *L)
10020{
10021 /* NULL <sub_list> = global subscription list */
10022 return MAY_LJMP(hlua_event_sub(L, NULL));
10023}
10024
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010025/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
10026 * doesn't allow "yield" functions because the HAProxy engine cannot
10027 * resume converters.
10028 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +020010029static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010030{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010031 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +020010032 struct stream *stream = smp->strm;
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010033 struct hlua *hlua = NULL;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010034 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010035
Willy Tarreaube508f12016-03-10 11:47:01 +010010036 if (!stream)
10037 return 0;
10038
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010039 if (!(hlua = hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn)))) {
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020010040 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
10041 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010042 }
10043
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010044 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010045 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010046
10047 /* The following Lua calls can fail. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010048 if (!SET_SAFE_LJMP(hlua)) {
10049 hlua_lock(hlua);
10050 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10051 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010052 else
10053 error = "critical error";
10054 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010055 hlua_unlock(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010056 return 0;
10057 }
10058
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010059 /* Check stack available size. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010060 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010061 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010062 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010063 return 0;
10064 }
10065
10066 /* Restore the function in the stack. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010067 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010068
10069 /* convert input sample and pust-it in the stack. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010070 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010071 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010072 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010073 return 0;
10074 }
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010075 MAY_LJMP(hlua_smp2lua(hlua->T, smp));
10076 hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010077
10078 /* push keywords in the stack. */
10079 if (arg_p) {
10080 for (; arg_p->type != ARGT_STOP; arg_p++) {
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010081 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010082 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010083 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010084 return 0;
10085 }
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010086 MAY_LJMP(hlua_arg2lua(hlua->T, arg_p));
10087 hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010088 }
10089 }
10090
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010091 /* We must initialize the execution timeouts. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010092 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010093
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010094 /* At this point the execution is safe. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010095 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010096 }
10097
10098 /* Execute the function. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010099 switch (hlua_ctx_resume(hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010100 /* finished. */
10101 case HLUA_E_OK:
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010102 hlua_lock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +020010103 /* If the stack is empty, the function fails. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010104 if (lua_gettop(hlua->T) <= 0) {
10105 hlua_unlock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +020010106 return 0;
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010010107 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +020010108
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010109 /* Convert the returned value in sample. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010110 hlua_lua2smp(hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +020010111 /* dup the smp before popping the related lua value and
10112 * returning it to haproxy
10113 */
10114 smp_dup(smp);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010115 lua_pop(hlua->T, 1);
10116 hlua_unlock(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010117 return 1;
10118
10119 /* yield. */
10120 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010121 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010122 return 0;
10123
10124 /* finished with error. */
10125 case HLUA_E_ERRMSG:
10126 /* Display log. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010127 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010128 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010129 fcn->name, hlua_tostring_safe(hlua->T, -1));
10130 lua_pop(hlua->T, 1);
10131 hlua_unlock(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010132 return 0;
10133
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010134 case HLUA_E_ETMOUT:
10135 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
10136 return 0;
10137
10138 case HLUA_E_NOMEM:
10139 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
10140 return 0;
10141
10142 case HLUA_E_YIELD:
10143 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
10144 return 0;
10145
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010146 case HLUA_E_ERR:
10147 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010148 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +010010149 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010150
10151 default:
10152 return 0;
10153 }
10154}
10155
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010156/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
10157 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +010010158 * resume sample-fetches. This function will be called by the sample
10159 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010160 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +020010161static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
10162 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010163{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010164 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +020010165 struct stream *stream = smp->strm;
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010166 struct hlua *hlua = NULL;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010167 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010168 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010169
Willy Tarreaube508f12016-03-10 11:47:01 +010010170 if (!stream)
10171 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +010010172
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010173 if (!(hlua = hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn)))) {
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020010174 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
10175 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010176 }
10177
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010178 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010179 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010180
10181 /* The following Lua calls can fail. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010182 if (!SET_SAFE_LJMP(hlua)) {
10183 hlua_lock(hlua);
10184 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10185 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010186 else
10187 error = "critical error";
10188 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010189 hlua_unlock(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010190 return 0;
10191 }
10192
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010193 /* Check stack available size. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010194 if (!lua_checkstack(hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010195 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010196 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010197 return 0;
10198 }
10199
10200 /* Restore the function in the stack. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010201 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010202
10203 /* push arguments in the stack. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010204 if (!hlua_txn_new(hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010205 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010206 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010207 return 0;
10208 }
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010209 hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010210
10211 /* push keywords in the stack. */
10212 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
10213 /* Check stack available size. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010214 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010215 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010216 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010217 return 0;
10218 }
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010219 MAY_LJMP(hlua_arg2lua(hlua->T, arg_p));
10220 hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010221 }
10222
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010223 /* We must initialize the execution timeouts. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010224 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010225
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010226 /* At this point the execution is safe. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010227 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010228 }
10229
10230 /* Execute the function. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010231 switch (hlua_ctx_resume(hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010232 /* finished. */
10233 case HLUA_E_OK:
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010234 hlua_lock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +020010235 /* If the stack is empty, the function fails. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010236 if (lua_gettop(hlua->T) <= 0) {
10237 hlua_unlock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +020010238 return 0;
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010010239 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +020010240
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010241 /* Convert the returned value in sample. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010242 hlua_lua2smp(hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +020010243 /* dup the smp before popping the related lua value and
10244 * returning it to haproxy
10245 */
10246 smp_dup(smp);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010247 lua_pop(hlua->T, 1);
10248 hlua_unlock(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010249
10250 /* Set the end of execution flag. */
10251 smp->flags &= ~SMP_F_MAY_CHANGE;
10252 return 1;
10253
10254 /* yield. */
10255 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010256 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010257 return 0;
10258
10259 /* finished with error. */
10260 case HLUA_E_ERRMSG:
10261 /* Display log. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010262 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010263 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010264 fcn->name, hlua_tostring_safe(hlua->T, -1));
10265 lua_pop(hlua->T, 1);
10266 hlua_unlock(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010267 return 0;
10268
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010269 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010270 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
10271 return 0;
10272
10273 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010274 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
10275 return 0;
10276
10277 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010278 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
10279 return 0;
10280
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010281 case HLUA_E_ERR:
10282 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010283 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +010010284 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010285
10286 default:
10287 return 0;
10288 }
10289}
10290
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010291/* This function is an LUA binding used for registering
10292 * "sample-conv" functions. It expects a converter name used
10293 * in the haproxy configuration file, and an LUA function.
10294 */
10295__LJMP static int hlua_register_converters(lua_State *L)
10296{
10297 struct sample_conv_kw_list *sck;
10298 const char *name;
10299 int ref;
10300 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +020010301 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010302 struct sample_conv *sc;
10303 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010304
10305 MAY_LJMP(check_args(L, 2, "register_converters"));
10306
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010307 if (hlua_gethlua(L)) {
10308 /* runtime processing */
10309 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
10310 }
10311
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010312 /* First argument : converter name. */
10313 name = MAY_LJMP(luaL_checkstring(L, 1));
10314
10315 /* Second argument : lua function. */
10316 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10317
Thierry Fournierf67442e2020-11-28 20:41:07 +010010318 /* Check if the converter is already registered */
10319 trash = get_trash_chunk();
10320 chunk_printf(trash, "lua.%s", name);
10321 sc = find_sample_conv(trash->area, trash->data);
10322 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010323 fcn = sc->private;
10324 if (fcn->function_ref[hlua_state_id] != -1) {
10325 ha_warning("Trying to register converter 'lua.%s' more than once. "
10326 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010327 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010328 }
10329 fcn->function_ref[hlua_state_id] = ref;
10330 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010331 }
10332
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010333 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010334 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010335 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +020010336 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010337 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010338 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +020010339 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010340
10341 /* Fill fcn. */
10342 fcn->name = strdup(name);
10343 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +020010344 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010345 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010346
10347 /* List head */
10348 sck->list.n = sck->list.p = NULL;
10349
10350 /* converter keyword. */
10351 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010352 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010353 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +020010354 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010355
10356 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
10357 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010358 sck->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010359 sck->kw[0].val_args = NULL;
10360 sck->kw[0].in_type = SMP_T_STR;
10361 sck->kw[0].out_type = SMP_T_STR;
10362 sck->kw[0].private = fcn;
10363
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010364 /* Register this new converter */
10365 sample_register_convs(sck);
10366
10367 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +020010368
10369 alloc_error:
10370 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010371 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +020010372 ha_free(&sck);
10373 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10374 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010375}
10376
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010377/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010378 * "sample-fetch" functions. It expects a converter name used
10379 * in the haproxy configuration file, and an LUA function.
10380 */
10381__LJMP static int hlua_register_fetches(lua_State *L)
10382{
10383 const char *name;
10384 int ref;
10385 int len;
10386 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +020010387 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010388 struct sample_fetch *sf;
10389 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010390
10391 MAY_LJMP(check_args(L, 2, "register_fetches"));
10392
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010393 if (hlua_gethlua(L)) {
10394 /* runtime processing */
10395 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
10396 }
10397
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010398 /* First argument : sample-fetch name. */
10399 name = MAY_LJMP(luaL_checkstring(L, 1));
10400
10401 /* Second argument : lua function. */
10402 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10403
Thierry Fournierf67442e2020-11-28 20:41:07 +010010404 /* Check if the sample-fetch is already registered */
10405 trash = get_trash_chunk();
10406 chunk_printf(trash, "lua.%s", name);
10407 sf = find_sample_fetch(trash->area, trash->data);
10408 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010409 fcn = sf->private;
10410 if (fcn->function_ref[hlua_state_id] != -1) {
10411 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
10412 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010413 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010414 }
10415 fcn->function_ref[hlua_state_id] = ref;
10416 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010417 }
10418
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010419 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010420 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010421 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +020010422 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010423 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010424 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +020010425 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010426
10427 /* Fill fcn. */
10428 fcn->name = strdup(name);
10429 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +020010430 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010431 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010432
10433 /* List head */
10434 sfk->list.n = sfk->list.p = NULL;
10435
10436 /* sample-fetch keyword. */
10437 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010438 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010439 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +020010440 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010441
10442 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
10443 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010444 sfk->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010445 sfk->kw[0].val_args = NULL;
10446 sfk->kw[0].out_type = SMP_T_STR;
10447 sfk->kw[0].use = SMP_USE_HTTP_ANY;
10448 sfk->kw[0].val = 0;
10449 sfk->kw[0].private = fcn;
10450
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010451 /* Register this new fetch. */
10452 sample_register_fetches(sfk);
10453
10454 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +020010455
10456 alloc_error:
10457 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010458 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +020010459 ha_free(&sfk);
10460 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10461 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010462}
10463
Christopher Faulet501465d2020-02-26 14:54:16 +010010464/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010465 */
Christopher Faulet501465d2020-02-26 14:54:16 +010010466__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010467{
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010468 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010469 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +020010470 int wakeup_ms; // tick value
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010471
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010472 /* Get hlua struct, or NULL if we execute from main lua state */
10473 hlua = hlua_gethlua(L);
10474 if (!hlua) {
10475 return 0;
10476 }
10477
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010478 MAY_LJMP(check_args(L, 1, "wake_time"));
10479
10480 delay = MAY_LJMP(luaL_checkinteger(L, 1));
10481 wakeup_ms = tick_add(now_ms, delay);
10482 hlua->wake_time = wakeup_ms;
10483 return 0;
10484}
10485
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010486/* This function is a wrapper to execute each LUA function declared as an action
10487 * wrapper during the initialisation period. This function may return any
10488 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
10489 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
10490 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010491 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010492static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +020010493 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010494{
10495 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010496 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010497 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010498 const char *error;
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010499 struct hlua *hlua = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010500
10501 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +010010502 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
10503 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
10504 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
10505 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010506 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010507 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010508 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010509 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010510
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010511 if (!(hlua = hlua_stream_ctx_prepare(s, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn)))) {
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020010512 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
10513 rule->arg.hlua_rule->fcn->name);
10514 goto end;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010515 }
10516
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010517 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010518 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010519
10520 /* The following Lua calls can fail. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010521 if (!SET_SAFE_LJMP(hlua)) {
10522 hlua_lock(hlua);
10523 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10524 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010525 else
10526 error = "critical error";
10527 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010528 rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010529 hlua_unlock(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010530 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010531 }
10532
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010533 /* Check stack available size. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010534 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010535 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010536 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010537 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010538 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010539 }
10540
10541 /* Restore the function in the stack. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010542 hlua_pushref(hlua->T, rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010543
Willy Tarreau87b09662015-04-03 00:22:06 +020010544 /* Create and and push object stream in the stack. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010545 if (!hlua_txn_new(hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010546 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010547 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010548 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010549 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010550 }
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010551 hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010552
10553 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010554 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010555 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010556 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010557 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010558 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010559 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010560 }
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010561 lua_pushstring(hlua->T, *arg);
10562 hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010563 }
10564
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010565 /* Now the execution is safe. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010566 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010567
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010568 /* We must initialize the execution timeouts. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010569 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010570 }
10571
10572 /* Execute the function. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010573 switch (hlua_ctx_resume(hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010574 /* finished. */
10575 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010576 /* Catch the return value */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010577 hlua_lock(hlua);
10578 if (lua_gettop(hlua->T) > 0)
10579 act_ret = lua_tointeger(hlua->T, -1);
10580 hlua_unlock(hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010581
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010582 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +020010583 if (act_ret == ACT_RET_YIELD) {
10584 if (flags & ACT_OPT_FINAL)
10585 goto err_yield;
10586
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010587 if (dir == SMP_OPT_DIR_REQ)
10588 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010589 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010590 else
10591 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010592 hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010593 }
10594 goto end;
10595
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010596 /* yield. */
10597 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +010010598 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010599 if (dir == SMP_OPT_DIR_REQ)
10600 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010601 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010602 else
10603 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010604 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010605
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010606 /* Some actions can be wake up when a "write" event
10607 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010608 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010609 */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010610 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010611 s->res.flags |= CF_WAKE_WRITE;
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010612 if (HLUA_IS_WAKEREQWR(hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010613 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010614 act_ret = ACT_RET_YIELD;
10615 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010616
10617 /* finished with error. */
10618 case HLUA_E_ERRMSG:
10619 /* Display log. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010620 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010621 SEND_ERR(px, "Lua function '%s': %s.\n",
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010622 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
10623 lua_pop(hlua->T, 1);
10624 hlua_unlock(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010625 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010626
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010627 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010628 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010629 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010630
10631 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010632 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010633 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010634
10635 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +020010636 err_yield:
10637 act_ret = ACT_RET_CONT;
Aurelien DARRAGONcf5b75e2023-08-31 21:45:21 +020010638 SEND_ERR(px, "Lua function '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010639 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010640 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010641
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010642 case HLUA_E_ERR:
10643 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010644 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010645 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010646
10647 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010648 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010649 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010650
10651 end:
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010010652 if (act_ret != ACT_RET_YIELD && hlua)
10653 hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010654 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010655}
10656
Willy Tarreau144f84a2021-03-02 16:09:26 +010010657struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010658{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010659 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010660
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010661 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010662 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010663 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010664}
10665
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010666static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010667{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010668 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010669 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010670 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010671 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010672 struct task *task;
10673 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010674 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010675
Willy Tarreaubafbe012017-11-24 17:34:44 +010010676 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010677 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010678 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010679 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010680 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010681 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010682 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010683 tcp_ctx->hlua = hlua;
10684 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010685
10686 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010687 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010688 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010689 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010690 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010691 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010692 }
10693 task->nice = 0;
10694 task->context = ctx;
10695 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010696 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010697
10698 /* In the execution wrappers linked with a stream, the
10699 * Lua context can be not initialized. This behavior
10700 * permits to save performances because a systematic
10701 * Lua initialization cause 5% performances loss.
10702 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010703 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010704 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010705 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010706 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010707 }
10708
10709 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010710 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010711
10712 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010713 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010010714 hlua_lock(hlua);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010715 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010716 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010717 else
10718 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010719 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010720 ctx->rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010010721 hlua_unlock(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010722 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010723 }
10724
10725 /* Check stack available size. */
10726 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010727 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010728 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010729 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010730 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010731 }
10732
10733 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010734 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010735
10736 /* Create and and push object stream in the stack. */
10737 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010738 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010739 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010740 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010741 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010742 }
10743 hlua->nargs = 1;
10744
10745 /* push keywords in the stack. */
10746 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10747 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010748 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010749 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010750 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010751 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010752 }
10753 lua_pushstring(hlua->T, *arg);
10754 hlua->nargs++;
10755 }
10756
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010757 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010758
10759 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010760 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010761 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010762
Christopher Fauletc9929382022-05-12 11:52:27 +020010763 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010764}
10765
Willy Tarreau60409db2019-08-21 14:14:50 +020010766void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010767{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010768 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010769 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010770 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010771 struct act_rule *rule = ctx->rule;
10772 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010773 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010774
Christopher Faulet31572222023-03-31 11:13:48 +020010775 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10776 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010777
Christopher Faulet31572222023-03-31 11:13:48 +020010778 /* The applet execution is already done. */
10779 if (tcp_ctx->flags & APPLET_DONE)
10780 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010781
10782 /* Execute the function. */
10783 switch (hlua_ctx_resume(hlua, 1)) {
10784 /* finished. */
10785 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010786 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010787 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10788 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010789
10790 /* yield. */
10791 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010792 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010793 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010794 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010795
10796 /* finished with error. */
10797 case HLUA_E_ERRMSG:
10798 /* Display log. */
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010010799 hlua_lock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010800 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010801 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010802 lua_pop(hlua->T, 1);
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010010803 hlua_unlock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010804 goto error;
10805
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010806 case HLUA_E_ETMOUT:
10807 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010808 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010809 goto error;
10810
10811 case HLUA_E_NOMEM:
10812 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010813 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010814 goto error;
10815
10816 case HLUA_E_YIELD: /* unexpected */
10817 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010818 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010819 goto error;
10820
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010821 case HLUA_E_ERR:
10822 /* Display log. */
10823 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010824 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010825 goto error;
10826
10827 default:
10828 goto error;
10829 }
10830
Christopher Faulet31572222023-03-31 11:13:48 +020010831out:
10832 /* eat the whole request */
10833 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10834 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010835
Christopher Faulet31572222023-03-31 11:13:48 +020010836error:
10837 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010838 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010839 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010840}
10841
10842static void hlua_applet_tcp_release(struct appctx *ctx)
10843{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010844 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10845
10846 task_destroy(tcp_ctx->task);
10847 tcp_ctx->task = NULL;
10848 hlua_ctx_destroy(tcp_ctx->hlua);
10849 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010850}
10851
Christopher Fauletc9929382022-05-12 11:52:27 +020010852/* The function returns 0 if the initialisation is complete or -1 if
10853 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010854 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010855static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010856{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010857 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010858 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010859 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010860 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010861 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010862 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010863 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010864 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010865
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010866 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010867 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010868 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010869 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010870 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010871 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010872 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010873 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010874 http_ctx->hlua = hlua;
10875 http_ctx->left_bytes = -1;
10876 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010877
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010878 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010879 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010880
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010881 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010882 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010883 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010884 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010885 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010886 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010887 }
10888 task->nice = 0;
10889 task->context = ctx;
10890 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010891 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010892
10893 /* In the execution wrappers linked with a stream, the
10894 * Lua context can be not initialized. This behavior
10895 * permits to save performances because a systematic
10896 * Lua initialization cause 5% performances loss.
10897 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010898 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010899 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010900 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010901 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010902 }
10903
10904 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010905 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010906
10907 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010908 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010010909 hlua_lock(hlua);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010910 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010911 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010912 else
10913 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010914 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010915 ctx->rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010010916 hlua_unlock(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010917 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010918 }
10919
10920 /* Check stack available size. */
10921 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010922 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010923 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010924 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010925 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010926 }
10927
10928 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010929 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010930
10931 /* Create and and push object stream in the stack. */
10932 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010933 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010934 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010935 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010936 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010937 }
10938 hlua->nargs = 1;
10939
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010940 /* push keywords in the stack. */
10941 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10942 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010943 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010944 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010945 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010946 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010947 }
10948 lua_pushstring(hlua->T, *arg);
10949 hlua->nargs++;
10950 }
10951
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010952 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010953
10954 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010955 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010956
Christopher Fauletc9929382022-05-12 11:52:27 +020010957 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010958}
10959
Willy Tarreau60409db2019-08-21 14:14:50 +020010960void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010961{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010962 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010963 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010964 struct stream *strm = __sc_strm(sc);
10965 struct channel *req = sc_oc(sc);
10966 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010967 struct act_rule *rule = ctx->rule;
10968 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010969 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010970 struct htx *req_htx, *res_htx;
10971
10972 res_htx = htx_from_buf(&res->buf);
10973
Christopher Faulet31572222023-03-31 11:13:48 +020010974 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10975 goto out;
10976
10977 /* The applet execution is already done. */
10978 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010979 goto out;
10980
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010981 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010982 if (!b_size(&res->buf)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010983 sc_need_room(sc, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010984 goto out;
10985 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010986
10987 /* Set the currently running flag. */
10988 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010989 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010990 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010991 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010992 goto out;
10993 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010994 }
10995
Christopher Faulet31572222023-03-31 11:13:48 +020010996 /* Execute the function. */
10997 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010998 /* finished. */
10999 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011000 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011001 break;
11002
11003 /* yield. */
11004 case HLUA_E_AGAIN:
11005 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011006 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010011007 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011008
11009 /* finished with error. */
11010 case HLUA_E_ERRMSG:
11011 /* Display log. */
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010011012 hlua_lock(hlua);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011013 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011014 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011015 lua_pop(hlua->T, 1);
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010011016 hlua_unlock(hlua);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011017 goto error;
11018
11019 case HLUA_E_ETMOUT:
11020 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020011021 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011022 goto error;
11023
11024 case HLUA_E_NOMEM:
11025 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020011026 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011027 goto error;
11028
11029 case HLUA_E_YIELD: /* unexpected */
11030 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020011031 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011032 goto error;
11033
11034 case HLUA_E_ERR:
11035 /* Display log. */
11036 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020011037 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011038 goto error;
11039
11040 default:
11041 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011042 }
11043
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011044 if (http_ctx->flags & APPLET_DONE) {
11045 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020011046 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010011047
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011048 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011049 goto error;
11050
Christopher Fauletf89af9c2022-04-07 10:07:18 +020011051 /* no more data are expected. If the response buffer is empty
11052 * for a chunked message, be sure to add something (EOT block in
11053 * this case) to have something to send. It is important to be
11054 * sure the EOM flags will be handled by the endpoint.
11055 */
11056 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
11057 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020011058 sc_need_room(sc, sizeof(struct htx_blk)+1);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020011059 goto out;
11060 }
11061 channel_add_input(res, 1);
11062 }
11063
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010011064 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020011065 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011066 strm->txn->status = http_ctx->status;
11067 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011068 }
11069
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011070 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011071 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020011072 /* eat the whole request */
11073 if (co_data(req)) {
11074 req_htx = htx_from_buf(&req->buf);
11075 co_htx_skip(req, req_htx, co_data(req));
11076 htx_to_buf(req_htx, &req->buf);
11077 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011078 return;
11079
11080 error:
11081
11082 /* If we are in HTTP mode, and we are not send any
11083 * data, return a 500 server error in best effort:
11084 * if there is no room available in the buffer,
11085 * just close the connection.
11086 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011087 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020011088 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011089
11090 channel_erase(res);
11091 res->buf.data = b_data(err);
11092 memcpy(res->buf.area, b_head(err), b_data(err));
11093 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010011094 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020011095 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011096 }
Christopher Faulet31572222023-03-31 11:13:48 +020011097 else
11098 se_fl_set(ctx->sedesc, SE_FL_ERROR);
11099
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011100 if (!(strm->flags & SF_ERR_MASK))
11101 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011102 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020011103 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010011104}
11105
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011106static void hlua_applet_http_release(struct appctx *ctx)
11107{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020011108 struct hlua_http_ctx *http_ctx = ctx->svcctx;
11109
11110 task_destroy(http_ctx->task);
11111 http_ctx->task = NULL;
11112 hlua_ctx_destroy(http_ctx->hlua);
11113 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011114}
11115
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011116/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011117 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011118 *
11119 * This function can fail with an abort() due to an Lua critical error.
11120 * We are in the configuration parsing process of HAProxy, this abort() is
11121 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010011122 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011123static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
11124 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010011125{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020011126 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011127 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011128
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011129 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020011130 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011131 if (!rule->arg.hlua_rule) {
11132 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020011133 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011134 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010011135
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011136 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020011137 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
11138 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011139 if (!rule->arg.hlua_rule->args) {
11140 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020011141 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011142 }
11143
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011144 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011145 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011146
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011147 /* Expect some arguments */
11148 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010011149 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011150 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020011151 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011152 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010011153 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011154 if (!rule->arg.hlua_rule->args[i]) {
11155 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020011156 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011157 }
11158 (*cur_arg)++;
11159 }
11160 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011161
Thierry FOURNIER42148732015-09-02 17:17:33 +020011162 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011163 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020011164 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020011165
11166 error:
11167 if (rule->arg.hlua_rule) {
11168 if (rule->arg.hlua_rule->args) {
11169 for (i = 0; i < fcn->nargs; i++)
11170 ha_free(&rule->arg.hlua_rule->args[i]);
11171 ha_free(&rule->arg.hlua_rule->args);
11172 }
11173 ha_free(&rule->arg.hlua_rule);
11174 }
11175 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010011176}
11177
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011178static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
11179 struct act_rule *rule, char **err)
11180{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020011181 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011182
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010011183 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011184 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010011185 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011186 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010011187 * the call of this analyzer.
11188 */
11189 if (rule->from != ACT_F_HTTP_REQ) {
11190 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
11191 return ACT_RET_PRS_ERR;
11192 }
11193
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011194 /* Memory for the rule. */
11195 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11196 if (!rule->arg.hlua_rule) {
11197 memprintf(err, "out of memory error");
11198 return ACT_RET_PRS_ERR;
11199 }
11200
11201 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011202 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011203
11204 /* TODO: later accept arguments. */
11205 rule->arg.hlua_rule->args = NULL;
11206
11207 /* Add applet pointer in the rule. */
11208 rule->applet.obj_type = OBJ_TYPE_APPLET;
11209 rule->applet.name = fcn->name;
11210 rule->applet.init = hlua_applet_http_init;
11211 rule->applet.fct = hlua_applet_http_fct;
11212 rule->applet.release = hlua_applet_http_release;
11213 rule->applet.timeout = hlua_timeout_applet;
11214
11215 return ACT_RET_PRS_OK;
11216}
11217
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011218/* This function is an LUA binding used for registering
11219 * "sample-conv" functions. It expects a converter name used
11220 * in the haproxy configuration file, and an LUA function.
11221 */
11222__LJMP static int hlua_register_action(lua_State *L)
11223{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011224 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011225 const char *name;
11226 int ref;
11227 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011228 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011229 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011230 struct buffer *trash;
11231 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011232
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011233 /* Initialise the number of expected arguments at 0. */
11234 nargs = 0;
11235
11236 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
11237 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011238
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011239 if (hlua_gethlua(L)) {
11240 /* runtime processing */
11241 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
11242 }
11243
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011244 /* First argument : converter name. */
11245 name = MAY_LJMP(luaL_checkstring(L, 1));
11246
11247 /* Second argument : environment. */
11248 if (lua_type(L, 2) != LUA_TTABLE)
11249 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
11250
11251 /* Third argument : lua function. */
11252 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11253
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011254 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011255 if (lua_gettop(L) >= 4)
11256 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
11257
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011258 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011259 lua_pushnil(L);
11260 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011261 if (lua_type(L, -1) != LUA_TSTRING) {
11262 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011263 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011264 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011265
Thierry Fournierf67442e2020-11-28 20:41:07 +010011266 /* Check if action exists */
11267 trash = get_trash_chunk();
11268 chunk_printf(trash, "lua.%s", name);
11269 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
11270 akw = tcp_req_cont_action(trash->area);
11271 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
11272 akw = tcp_res_cont_action(trash->area);
11273 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
11274 akw = action_http_req_custom(trash->area);
11275 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
11276 akw = action_http_res_custom(trash->area);
11277 } else {
11278 akw = NULL;
11279 }
11280 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011281 fcn = akw->private;
11282 if (fcn->function_ref[hlua_state_id] != -1) {
11283 ha_warning("Trying to register action 'lua.%s' more than once. "
11284 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011285 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011286 }
11287 fcn->function_ref[hlua_state_id] = ref;
11288
11289 /* pop the environment string. */
11290 lua_pop(L, 1);
11291 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011292 }
11293
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011294 /* Check required environment. Only accepted "http" or "tcp". */
11295 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020011296 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011297 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011298 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011299 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011300 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011301 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011302
11303 /* Fill fcn. */
11304 fcn->name = strdup(name);
11305 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011306 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010011307 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011308
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011309 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011310 fcn->nargs = nargs;
11311
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011312 /* List head */
11313 akl->list.n = akl->list.p = NULL;
11314
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011315 /* action keyword. */
11316 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020011317 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011318 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011319 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011320
11321 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11322
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011323 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011324 akl->kw[0].private = fcn;
11325 akl->kw[0].parse = action_register_lua;
11326
11327 /* select the action registering point. */
11328 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
11329 tcp_req_cont_keywords_register(akl);
11330 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
11331 tcp_res_cont_keywords_register(akl);
11332 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
11333 http_req_keywords_register(akl);
11334 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
11335 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011336 else {
11337 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011338 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011339 if (akl)
11340 ha_free((char **)&(akl->kw[0].kw));
11341 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011342 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011343 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
11344 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011345 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011346
11347 /* pop the environment string. */
11348 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011349
11350 /* reset for next loop */
11351 akl = NULL;
11352 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011353 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011354 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011355
11356 alloc_error:
11357 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011358 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011359 ha_free(&akl);
11360 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11361 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011362}
11363
11364static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
11365 struct act_rule *rule, char **err)
11366{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020011367 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011368
Christopher Faulet280f85b2019-07-15 15:02:04 +020011369 if (px->mode == PR_MODE_HTTP) {
11370 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010011371 return ACT_RET_PRS_ERR;
11372 }
11373
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011374 /* Memory for the rule. */
11375 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11376 if (!rule->arg.hlua_rule) {
11377 memprintf(err, "out of memory error");
11378 return ACT_RET_PRS_ERR;
11379 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011380
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011381 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011382 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011383
11384 /* TODO: later accept arguments. */
11385 rule->arg.hlua_rule->args = NULL;
11386
11387 /* Add applet pointer in the rule. */
11388 rule->applet.obj_type = OBJ_TYPE_APPLET;
11389 rule->applet.name = fcn->name;
11390 rule->applet.init = hlua_applet_tcp_init;
11391 rule->applet.fct = hlua_applet_tcp_fct;
11392 rule->applet.release = hlua_applet_tcp_release;
11393 rule->applet.timeout = hlua_timeout_applet;
11394
11395 return 0;
11396}
11397
11398/* This function is an LUA binding used for registering
11399 * "sample-conv" functions. It expects a converter name used
11400 * in the haproxy configuration file, and an LUA function.
11401 */
11402__LJMP static int hlua_register_service(lua_State *L)
11403{
11404 struct action_kw_list *akl;
11405 const char *name;
11406 const char *env;
11407 int ref;
11408 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011409 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011410 struct buffer *trash;
11411 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011412
11413 MAY_LJMP(check_args(L, 3, "register_service"));
11414
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011415 if (hlua_gethlua(L)) {
11416 /* runtime processing */
11417 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
11418 }
11419
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011420 /* First argument : converter name. */
11421 name = MAY_LJMP(luaL_checkstring(L, 1));
11422
11423 /* Second argument : environment. */
11424 env = MAY_LJMP(luaL_checkstring(L, 2));
11425
11426 /* Third argument : lua function. */
11427 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11428
Thierry Fournierf67442e2020-11-28 20:41:07 +010011429 /* Check for service already registered */
11430 trash = get_trash_chunk();
11431 chunk_printf(trash, "lua.%s", name);
11432 akw = service_find(trash->area);
11433 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011434 fcn = akw->private;
11435 if (fcn->function_ref[hlua_state_id] != -1) {
11436 ha_warning("Trying to register service 'lua.%s' more than once. "
11437 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011438 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011439 }
11440 fcn->function_ref[hlua_state_id] = ref;
11441 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011442 }
11443
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011444 /* Allocate and fill the sample fetch keyword struct. */
11445 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
11446 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011447 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011448 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011449 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011450 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011451
11452 /* Fill fcn. */
11453 len = strlen("<lua.>") + strlen(name) + 1;
11454 fcn->name = calloc(1, len);
11455 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011456 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011457 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010011458 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011459
11460 /* List head */
11461 akl->list.n = akl->list.p = NULL;
11462
11463 /* converter keyword. */
11464 len = strlen("lua.") + strlen(name) + 1;
11465 akl->kw[0].kw = calloc(1, len);
11466 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011467 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011468
11469 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11470
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010011471 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011472 if (strcmp(env, "tcp") == 0)
11473 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011474 else if (strcmp(env, "http") == 0)
11475 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011476 else {
11477 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011478 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011479 if (akl)
11480 ha_free((char **)&(akl->kw[0].kw));
11481 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011482 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010011483 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020011484 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011485
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011486 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011487 akl->kw[0].private = fcn;
11488
11489 /* End of array. */
11490 memset(&akl->kw[1], 0, sizeof(*akl->kw));
11491
11492 /* Register this new converter */
11493 service_keywords_register(akl);
11494
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011495 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011496
11497 alloc_error:
11498 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011499 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011500 ha_free(&akl);
11501 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11502 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011503}
11504
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011505/* This function initialises Lua cli handler. It copies the
11506 * arguments in the Lua stack and create channel IO objects.
11507 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020011508static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011509{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011510 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011511 struct hlua *hlua;
11512 struct hlua_function *fcn;
11513 int i;
11514 const char *error;
11515
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011516 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011517 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011518
Willy Tarreaubafbe012017-11-24 17:34:44 +010011519 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011520 if (!hlua) {
11521 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011522 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011523 }
11524 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011525 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011526
11527 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050011528 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011529 * applet_http. It is absolutely compatible.
11530 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011531 ctx->task = task_new_here();
11532 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010011533 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011534 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011535 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011536 ctx->task->nice = 0;
11537 ctx->task->context = appctx;
11538 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011539
11540 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011541 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011542 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011543 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011544 }
11545
11546 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011547 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010011548 hlua_lock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011549 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011550 error = hlua_tostring_safe(hlua->T, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011551 else
11552 error = "critical error";
11553 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010011554 hlua_unlock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011555 goto error;
11556 }
11557
11558 /* Check stack available size. */
11559 if (!lua_checkstack(hlua->T, 2)) {
11560 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11561 goto error;
11562 }
11563
11564 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011565 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011566
11567 /* Once the arguments parsed, the CLI is like an AppletTCP,
11568 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011569 */
11570 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
11571 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11572 goto error;
11573 }
11574 hlua->nargs = 1;
11575
11576 /* push keywords in the stack. */
11577 for (i = 0; *args[i]; i++) {
11578 /* Check stack available size. */
11579 if (!lua_checkstack(hlua->T, 1)) {
11580 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11581 goto error;
11582 }
11583 lua_pushstring(hlua->T, args[i]);
11584 hlua->nargs++;
11585 }
11586
11587 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011588 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011589
11590 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011591 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011592
11593 /* It's ok */
11594 return 0;
11595
11596 /* It's not ok. */
11597error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011598 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011599 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011600 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011601 return 1;
11602}
11603
11604static int hlua_cli_io_handler_fct(struct appctx *appctx)
11605{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011606 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011607 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020011608 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011609 struct hlua_function *fcn;
11610
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011611 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020011612 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011613 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011614
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011615 /* Execute the function. */
11616 switch (hlua_ctx_resume(hlua, 1)) {
11617
11618 /* finished. */
11619 case HLUA_E_OK:
11620 return 1;
11621
11622 /* yield. */
11623 case HLUA_E_AGAIN:
11624 /* We want write. */
11625 if (HLUA_IS_WAKERESWR(hlua))
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020011626 sc_need_room(sc, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011627 /* Set the timeout. */
11628 if (hlua->wake_time != TICK_ETERNITY)
11629 task_schedule(hlua->task, hlua->wake_time);
11630 return 0;
11631
11632 /* finished with error. */
11633 case HLUA_E_ERRMSG:
11634 /* Display log. */
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010011635 hlua_lock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011636 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011637 fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011638 lua_pop(hlua->T, 1);
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010011639 hlua_unlock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011640 return 1;
11641
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011642 case HLUA_E_ETMOUT:
Aurelien DARRAGONc2986812024-06-21 19:12:37 +020011643 SEND_ERR(NULL, "Lua cli '%s': execution timeout.\n",
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011644 fcn->name);
11645 return 1;
11646
11647 case HLUA_E_NOMEM:
Aurelien DARRAGONc2986812024-06-21 19:12:37 +020011648 SEND_ERR(NULL, "Lua cli '%s': out of memory error.\n",
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011649 fcn->name);
11650 return 1;
11651
11652 case HLUA_E_YIELD: /* unexpected */
Aurelien DARRAGONc2986812024-06-21 19:12:37 +020011653 SEND_ERR(NULL, "Lua cli '%s': yield not allowed.\n",
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011654 fcn->name);
11655 return 1;
11656
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011657 case HLUA_E_ERR:
11658 /* Display log. */
11659 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11660 fcn->name);
11661 return 1;
11662
11663 default:
11664 return 1;
11665 }
11666
11667 return 1;
11668}
11669
11670static void hlua_cli_io_release_fct(struct appctx *appctx)
11671{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011672 struct hlua_cli_ctx *ctx = appctx->svcctx;
11673
11674 hlua_ctx_destroy(ctx->hlua);
11675 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011676}
11677
11678/* This function is an LUA binding used for registering
11679 * new keywords in the cli. It expects a list of keywords
11680 * which are the "path". It is limited to 5 keywords. A
11681 * description of the command, a function to be executed
11682 * for the parsing and a function for io handlers.
11683 */
11684__LJMP static int hlua_register_cli(lua_State *L)
11685{
11686 struct cli_kw_list *cli_kws;
11687 const char *message;
11688 int ref_io;
11689 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011690 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011691 int index;
11692 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011693 struct buffer *trash;
11694 const char *kw[5];
11695 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011696 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011697 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011698
11699 MAY_LJMP(check_args(L, 3, "register_cli"));
11700
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011701 if (hlua_gethlua(L)) {
11702 /* runtime processing */
11703 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11704 }
11705
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011706 /* First argument : an array of maximum 5 keywords. */
11707 if (!lua_istable(L, 1))
11708 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11709
11710 /* Second argument : string with contextual message. */
11711 message = MAY_LJMP(luaL_checkstring(L, 2));
11712
11713 /* Third and fourth argument : lua function. */
11714 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11715
Thierry Fournierf67442e2020-11-28 20:41:07 +010011716 /* Check for CLI service already registered */
11717 trash = get_trash_chunk();
11718 index = 0;
11719 lua_pushnil(L);
11720 memset(kw, 0, sizeof(kw));
11721 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011722 if (index >= CLI_PREFIX_KW_NB) {
11723 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011724 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011725 }
11726 if (lua_type(L, -1) != LUA_TSTRING) {
11727 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011728 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011729 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011730 kw[index] = lua_tostring(L, -1);
11731 if (index == 0)
11732 chunk_printf(trash, "%s", kw[index]);
11733 else
11734 chunk_appendf(trash, " %s", kw[index]);
11735 index++;
11736 lua_pop(L, 1);
11737 }
11738 cli_kw = cli_find_kw_exact((char **)kw);
11739 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011740 fcn = cli_kw->private;
11741 if (fcn->function_ref[hlua_state_id] != -1) {
11742 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11743 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011744 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011745 }
11746 fcn->function_ref[hlua_state_id] = ref_io;
11747 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011748 }
11749
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011750 /* Allocate and fill the sample fetch keyword struct. */
11751 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011752 if (!cli_kws) {
11753 errmsg = "Lua out of memory error.";
11754 goto error;
11755 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011756 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011757 if (!fcn) {
11758 errmsg = "Lua out of memory error.";
11759 goto error;
11760 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011761
11762 /* Fill path. */
11763 index = 0;
11764 lua_pushnil(L);
11765 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011766 if (index >= 5) {
11767 errmsg = "1st argument must be a table with a maximum of 5 entries";
11768 goto error;
11769 }
11770 if (lua_type(L, -1) != LUA_TSTRING) {
11771 errmsg = "1st argument must be a table filled with strings";
11772 goto error;
11773 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011774 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011775 if (!cli_kws->kw[0].str_kw[index]) {
11776 errmsg = "Lua out of memory error.";
11777 goto error;
11778 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011779 index++;
11780 lua_pop(L, 1);
11781 }
11782
11783 /* Copy help message. */
11784 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011785 if (!cli_kws->kw[0].usage) {
11786 errmsg = "Lua out of memory error.";
11787 goto error;
11788 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011789
11790 /* Fill fcn io handler. */
11791 len = strlen("<lua.cli>") + 1;
11792 for (i = 0; i < index; i++)
11793 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11794 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011795 if (!fcn->name) {
11796 errmsg = "Lua out of memory error.";
11797 goto error;
11798 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011799
11800 end = fcn->name;
11801 len = 8;
11802 memcpy(end, "<lua.cli", len);
11803 end += len;
11804
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011805 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011806 *(end++) = '.';
11807 len = strlen(cli_kws->kw[0].str_kw[i]);
11808 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11809 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011810 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011811 *(end++) = '>';
11812 *(end++) = 0;
11813
Thierry Fournierc7492592020-11-28 23:57:24 +010011814 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011815
11816 /* Fill last entries. */
11817 cli_kws->kw[0].private = fcn;
11818 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11819 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11820 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11821
11822 /* Register this new converter */
11823 cli_register_kw(cli_kws);
11824
11825 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011826
11827 error:
11828 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011829 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011830 if (cli_kws) {
11831 for (i = 0; i < index; i++)
11832 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11833 ha_free((char **)&(cli_kws->kw[0].usage));
11834 }
11835 ha_free(&cli_kws);
11836 WILL_LJMP(luaL_error(L, errmsg));
11837 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011838}
11839
Christopher Faulet69c581a2021-05-31 08:54:04 +020011840static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11841{
11842 struct hlua_flt_config *conf = fconf->conf;
11843 lua_State *L;
11844 int error, pos, state_id, flt_ref;
11845
11846 state_id = reg_flt_to_stack_id(conf->reg);
11847 L = hlua_states[state_id];
11848 pos = lua_gettop(L);
11849
11850 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011851 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011852
11853 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011854 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011855
11856 /* Duplicate the filter class so each filter will have its own copy */
11857 lua_newtable(L);
11858 lua_pushnil(L);
11859
11860 while (lua_next(L, pos+2)) {
11861 lua_pushvalue(L, -2);
11862 lua_insert(L, -2);
11863 lua_settable(L, -4);
11864 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011865 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011866
11867 /* Remove the original lua filter class from the stack */
11868 lua_pop(L, 1);
11869
11870 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011871 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011872
11873 /* extra args are pushed in a table */
11874 lua_newtable(L);
11875 for (pos = 0; conf->args[pos]; pos++) {
11876 /* Check stack available size. */
11877 if (!lua_checkstack(L, 1)) {
11878 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11879 goto error;
11880 }
11881 lua_pushstring(L, conf->args[pos]);
11882 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11883 }
11884
11885 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11886 switch (error) {
11887 case LUA_OK:
11888 /* replace the filter ref */
11889 conf->ref[state_id] = flt_ref;
11890 break;
11891 case LUA_ERRRUN:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011892 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011893 goto error;
11894 case LUA_ERRMEM:
11895 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11896 goto error;
11897 case LUA_ERRERR:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011898 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011899 goto error;
11900#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11901 case LUA_ERRGCMM:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011902 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011903 goto error;
11904#endif
11905 default:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011906 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011907 goto error;
11908 }
11909
11910 lua_settop(L, 0);
11911 return 0;
11912
11913 error:
11914 lua_settop(L, 0);
11915 return -1;
11916}
11917
11918static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11919{
11920 struct hlua_flt_config *conf = fconf->conf;
11921 lua_State *L;
11922 int state_id;
11923
11924 if (!conf)
11925 return;
11926
11927 state_id = reg_flt_to_stack_id(conf->reg);
11928 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011929 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011930}
11931
11932static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11933{
11934 struct hlua_flt_config *conf = fconf->conf;
11935 int state_id = reg_flt_to_stack_id(conf->reg);
11936
11937 /* Rely on per-thread init for global scripts */
11938 if (!state_id)
11939 return hlua_filter_init_per_thread(px, fconf);
11940 return 0;
11941}
11942
11943static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11944{
11945
11946 if (fconf->conf) {
11947 struct hlua_flt_config *conf = fconf->conf;
11948 int state_id = reg_flt_to_stack_id(conf->reg);
11949 int pos;
11950
11951 /* Rely on per-thread deinit for global scripts */
11952 if (!state_id)
11953 hlua_filter_deinit_per_thread(px, fconf);
11954
11955 for (pos = 0; conf->args[pos]; pos++)
11956 free(conf->args[pos]);
11957 free(conf->args);
11958 }
11959 ha_free(&fconf->conf);
11960 ha_free((char **)&fconf->id);
11961 ha_free(&fconf->ops);
11962}
11963
11964static int hlua_filter_new(struct stream *s, struct filter *filter)
11965{
11966 struct hlua_flt_config *conf = FLT_CONF(filter);
11967 struct hlua_flt_ctx *flt_ctx = NULL;
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010011968 struct hlua *hlua = NULL;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011969 int ret = 1;
11970
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010011971 if (!(hlua = hlua_stream_ctx_prepare(s, reg_flt_to_stack_id(conf->reg)))) {
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020011972 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11973 conf->reg->name);
11974 ret = 0;
11975 goto end;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011976 }
11977
11978 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11979 if (!flt_ctx) {
11980 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11981 conf->reg->name);
11982 ret = 0;
11983 goto end;
11984 }
Aurelien DARRAGON205f1ac2024-03-04 09:39:58 +010011985
11986 if ((flt_ctx->hlua[0] = pool_alloc(pool_head_hlua)))
11987 HLUA_INIT(flt_ctx->hlua[0]);
11988 if ((flt_ctx->hlua[1] = pool_alloc(pool_head_hlua)))
11989 HLUA_INIT(flt_ctx->hlua[1]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011990 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11991 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11992 conf->reg->name);
11993 ret = 0;
11994 goto end;
11995 }
Aurelien DARRAGON205f1ac2024-03-04 09:39:58 +010011996
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011997 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11998 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011999 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
12000 conf->reg->name);
12001 ret = 0;
12002 goto end;
12003 }
12004
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012005 if (!HLUA_IS_RUNNING(hlua)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012006 /* The following Lua calls can fail. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012007 if (!SET_SAFE_LJMP(hlua)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012008 const char *error;
12009
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012010 hlua_lock(hlua);
12011 if (lua_type(hlua->T, -1) == LUA_TSTRING)
12012 error = hlua_tostring_safe(hlua->T, -1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012013 else
12014 error = "critical error";
12015 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012016 hlua_unlock(hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012017 ret = 0;
12018 goto end;
12019 }
12020
12021 /* Check stack size. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012022 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012023 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012024 RESET_SAFE_LJMP(hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012025 ret = 0;
12026 goto end;
12027 }
12028
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012029 hlua_pushref(hlua->T, conf->ref[hlua->state_id]);
12030 if (lua_getfield(hlua->T, -1, "new") != LUA_TFUNCTION) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012031 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
12032 conf->reg->name);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012033 RESET_SAFE_LJMP(hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012034 ret = 0;
12035 goto end;
12036 }
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012037 lua_insert(hlua->T, -2);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012038
12039 /* Push the copy on the stack */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012040 hlua->nargs = 1;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012041
12042 /* We must initialize the execution timeouts. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012043 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012044
12045 /* At this point the execution is safe. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012046 RESET_SAFE_LJMP(hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012047 }
12048
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012049 switch (hlua_ctx_resume(hlua, 0)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012050 case HLUA_E_OK:
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012051 /* The following Lua calls can fail. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012052 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012053 const char *error;
12054
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012055 hlua_lock(hlua);
12056 if (lua_type(hlua->T, -1) == LUA_TSTRING)
12057 error = hlua_tostring_safe(hlua->T, -1);
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012058 else
12059 error = "critical error";
12060 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012061 hlua_unlock(hlua);
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012062 ret = 0;
12063 goto end;
12064 }
12065
Christopher Faulet69c581a2021-05-31 08:54:04 +020012066 /* Nothing returned or not a table, ignore the filter for current stream */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012067 if (!lua_gettop(hlua->T) || !lua_istable(hlua->T, 1)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012068 ret = 0;
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012069 RESET_SAFE_LJMP(hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012070 goto end;
12071 }
12072
12073 /* Attached the filter pointer to the ctx */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012074 lua_pushstring(hlua->T, "__filter");
12075 lua_pushlightuserdata(hlua->T, filter);
12076 lua_settable(hlua->T, -3);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012077
12078 /* Save a ref on the filter ctx */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012079 lua_pushvalue(hlua->T, 1);
12080 flt_ctx->ref = hlua_ref(hlua->T);
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012081
12082 /* At this point the execution is safe. */
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012083 RESET_SAFE_LJMP(hlua);
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012084
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +010012085 /* save main hlua ctx (from the stream) */
12086 flt_ctx->_hlua = hlua;
12087
Christopher Faulet69c581a2021-05-31 08:54:04 +020012088 filter->ctx = flt_ctx;
12089 break;
12090 case HLUA_E_ERRMSG:
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012091 hlua_lock(hlua);
12092 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, hlua_tostring_safe(hlua->T, -1));
12093 hlua_unlock(hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012094 ret = -1;
12095 goto end;
12096 case HLUA_E_ETMOUT:
12097 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
12098 ret = 0;
12099 goto end;
12100 case HLUA_E_NOMEM:
12101 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
12102 ret = 0;
12103 goto end;
12104 case HLUA_E_AGAIN:
12105 case HLUA_E_YIELD:
12106 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
12107 " are not allowed from 'new' function.\n", conf->reg->name);
12108 ret = 0;
12109 goto end;
12110 case HLUA_E_ERR:
12111 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
12112 ret = 0;
12113 goto end;
12114 default:
12115 ret = 0;
12116 goto end;
12117 }
12118
12119 end:
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012120 if (hlua) {
12121 hlua_lock(hlua);
12122 lua_settop(hlua->T, 0);
12123 hlua_unlock(hlua);
Aurelien DARRAGON01d1b732024-03-04 11:25:47 +010012124 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012125 if (ret <= 0) {
12126 if (flt_ctx) {
12127 hlua_ctx_destroy(flt_ctx->hlua[0]);
12128 hlua_ctx_destroy(flt_ctx->hlua[1]);
12129 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
12130 }
12131 }
12132 return ret;
12133}
12134
12135static void hlua_filter_delete(struct stream *s, struct filter *filter)
12136{
12137 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Aurelien DARRAGON1a3ac402024-03-12 17:05:54 +010012138 struct hlua *hlua = hlua_stream_ctx_get(s, flt_ctx->_hlua->state_id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012139
Aurelien DARRAGON188adfd2024-03-12 17:00:25 +010012140 hlua_lock(hlua);
12141 hlua_unref(hlua->T, flt_ctx->ref);
12142 hlua_unlock(hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012143 hlua_ctx_destroy(flt_ctx->hlua[0]);
12144 hlua_ctx_destroy(flt_ctx->hlua[1]);
12145 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
12146 filter->ctx = NULL;
12147}
12148
Christopher Faulet9f55a502020-02-25 15:21:02 +010012149static int hlua_filter_from_payload(struct filter *filter)
12150{
12151 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12152
12153 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
12154}
12155
Christopher Fauletc404f112020-02-26 15:03:09 +010012156static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
12157 int dir, unsigned int flags)
12158{
12159 struct hlua *flt_hlua;
12160 struct hlua_flt_config *conf = FLT_CONF(filter);
12161 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12162 unsigned int hflags = HLUA_TXN_FLT_CTX;
12163 int ret = 1;
12164
12165 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
12166 if (!flt_hlua)
12167 goto end;
12168
12169 if (!HLUA_IS_RUNNING(flt_hlua)) {
Aurelien DARRAGONf8b137b2024-03-04 11:06:24 +010012170 int extra_idx;
Christopher Fauletc404f112020-02-26 15:03:09 +010012171
12172 /* The following Lua calls can fail. */
12173 if (!SET_SAFE_LJMP(flt_hlua)) {
12174 const char *error;
12175
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010012176 hlua_lock(flt_hlua);
Christopher Fauletc404f112020-02-26 15:03:09 +010012177 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012178 error = hlua_tostring_safe(flt_hlua->T, -1);
Christopher Fauletc404f112020-02-26 15:03:09 +010012179 else
12180 error = "critical error";
12181 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
Aurelien DARRAGONcddf6222024-03-04 11:17:58 +010012182 hlua_unlock(flt_hlua);
Christopher Fauletc404f112020-02-26 15:03:09 +010012183 goto end;
12184 }
12185
Aurelien DARRAGONf8b137b2024-03-04 11:06:24 +010012186 extra_idx = lua_gettop(flt_hlua->T);
12187
Christopher Fauletc404f112020-02-26 15:03:09 +010012188 /* Check stack size. */
12189 if (!lua_checkstack(flt_hlua->T, 3)) {
12190 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
12191 RESET_SAFE_LJMP(flt_hlua);
12192 goto end;
12193 }
12194
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012195 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010012196 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
12197 RESET_SAFE_LJMP(flt_hlua);
12198 goto end;
12199 }
12200 lua_insert(flt_hlua->T, -2);
12201
12202 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
12203 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
12204 RESET_SAFE_LJMP(flt_hlua);
12205 goto end;
12206 }
12207 flt_hlua->nargs = 2;
12208
12209 if (flags & HLUA_FLT_CB_ARG_CHN) {
12210 if (dir == SMP_OPT_DIR_REQ)
12211 lua_getfield(flt_hlua->T, -1, "req");
12212 else
12213 lua_getfield(flt_hlua->T, -1, "res");
12214 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
12215 lua_pushstring(flt_hlua->T, "__filter");
12216 lua_pushlightuserdata(flt_hlua->T, filter);
12217 lua_settable(flt_hlua->T, -3);
12218 }
12219 flt_hlua->nargs++;
12220 }
12221 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012222 if (dir == SMP_OPT_DIR_REQ)
12223 lua_getfield(flt_hlua->T, -1, "http_req");
12224 else
12225 lua_getfield(flt_hlua->T, -1, "http_res");
12226 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
12227 lua_pushstring(flt_hlua->T, "__filter");
12228 lua_pushlightuserdata(flt_hlua->T, filter);
12229 lua_settable(flt_hlua->T, -3);
12230 }
12231 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010012232 }
12233
12234 /* Check stack size. */
12235 if (!lua_checkstack(flt_hlua->T, 1)) {
12236 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
12237 RESET_SAFE_LJMP(flt_hlua);
12238 goto end;
12239 }
12240
12241 while (extra_idx--) {
12242 lua_pushvalue(flt_hlua->T, 1);
12243 lua_remove(flt_hlua->T, 1);
12244 flt_hlua->nargs++;
12245 }
12246
12247 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010012248 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010012249
12250 /* At this point the execution is safe. */
12251 RESET_SAFE_LJMP(flt_hlua);
12252 }
12253
12254 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
12255 case HLUA_E_OK:
12256 /* Catch the return value if it required */
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012257 hlua_lock(flt_hlua);
Christopher Fauletc404f112020-02-26 15:03:09 +010012258 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
12259 ret = lua_tointeger(flt_hlua->T, -1);
12260 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12261 }
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012262 hlua_unlock(flt_hlua);
Christopher Fauletc404f112020-02-26 15:03:09 +010012263
12264 /* Set timeout in the required channel. */
12265 if (flt_hlua->wake_time != TICK_ETERNITY) {
12266 if (dir == SMP_OPT_DIR_REQ)
12267 s->req.analyse_exp = flt_hlua->wake_time;
12268 else
12269 s->res.analyse_exp = flt_hlua->wake_time;
12270 }
12271 break;
12272 case HLUA_E_AGAIN:
12273 /* Set timeout in the required channel. */
12274 if (flt_hlua->wake_time != TICK_ETERNITY) {
12275 if (dir == SMP_OPT_DIR_REQ)
12276 s->req.analyse_exp = flt_hlua->wake_time;
12277 else
12278 s->res.analyse_exp = flt_hlua->wake_time;
12279 }
12280 /* Some actions can be wake up when a "write" event
12281 * is detected on a response channel. This is useful
12282 * only for actions targeted on the requests.
12283 */
12284 if (HLUA_IS_WAKERESWR(flt_hlua))
12285 s->res.flags |= CF_WAKE_WRITE;
12286 if (HLUA_IS_WAKEREQWR(flt_hlua))
12287 s->req.flags |= CF_WAKE_WRITE;
12288 ret = 0;
12289 goto end;
12290 case HLUA_E_ERRMSG:
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012291 hlua_lock(flt_hlua);
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012292 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, hlua_tostring_safe(flt_hlua->T, -1));
Aurelien DARRAGON258fc3f2024-03-01 21:17:51 +010012293 hlua_unlock(flt_hlua);
Christopher Fauletc404f112020-02-26 15:03:09 +010012294 ret = -1;
12295 goto end;
12296 case HLUA_E_ETMOUT:
12297 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
12298 goto end;
12299 case HLUA_E_NOMEM:
12300 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
12301 goto end;
12302 case HLUA_E_YIELD:
12303 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
12304 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
12305 goto end;
12306 case HLUA_E_ERR:
12307 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
12308 goto end;
12309 default:
12310 goto end;
12311 }
12312
12313
12314 end:
12315 return ret;
12316}
12317
12318static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
12319{
12320 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12321
12322 flt_ctx->flags = 0;
12323 return hlua_filter_callback(s, filter, "start_analyze",
12324 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12325 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
12326}
12327
12328static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
12329{
12330 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12331
12332 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12333 return hlua_filter_callback(s, filter, "end_analyze",
12334 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12335 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
12336}
12337
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012338static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
12339{
12340 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12341
12342 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12343 return hlua_filter_callback(s, filter, "http_headers",
12344 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12345 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12346}
12347
12348static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
12349 unsigned int offset, unsigned int len)
12350{
12351 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12352 struct hlua *flt_hlua;
12353 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12354 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12355 int ret;
12356
12357 flt_hlua = flt_ctx->hlua[idx];
12358 flt_ctx->cur_off[idx] = offset;
12359 flt_ctx->cur_len[idx] = len;
12360 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12361 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12362 if (ret != -1) {
12363 ret = flt_ctx->cur_len[idx];
12364 if (lua_gettop(flt_hlua->T) > 0) {
12365 ret = lua_tointeger(flt_hlua->T, -1);
12366 if (ret > flt_ctx->cur_len[idx])
12367 ret = flt_ctx->cur_len[idx];
12368 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12369 }
12370 }
12371 return ret;
12372}
12373
12374static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
12375{
12376 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12377
12378 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12379 return hlua_filter_callback(s, filter, "http_end",
12380 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12381 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12382}
12383
Christopher Fauletc404f112020-02-26 15:03:09 +010012384static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
12385 unsigned int offset, unsigned int len)
12386{
12387 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12388 struct hlua *flt_hlua;
12389 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12390 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12391 int ret;
12392
12393 flt_hlua = flt_ctx->hlua[idx];
12394 flt_ctx->cur_off[idx] = offset;
12395 flt_ctx->cur_len[idx] = len;
12396 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12397 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
12398 if (ret != -1) {
12399 ret = flt_ctx->cur_len[idx];
12400 if (lua_gettop(flt_hlua->T) > 0) {
12401 ret = lua_tointeger(flt_hlua->T, -1);
12402 if (ret > flt_ctx->cur_len[idx])
12403 ret = flt_ctx->cur_len[idx];
12404 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12405 }
12406 }
12407 return ret;
12408}
12409
Christopher Faulet69c581a2021-05-31 08:54:04 +020012410static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
12411 struct flt_conf *fconf, char **err, void *private)
12412{
12413 struct hlua_reg_filter *reg_flt = private;
12414 lua_State *L;
12415 struct hlua_flt_config *conf = NULL;
12416 const char *flt_id = NULL;
12417 int state_id, pos, flt_flags = 0;
12418 struct flt_ops *hlua_flt_ops = NULL;
12419
12420 state_id = reg_flt_to_stack_id(reg_flt);
12421 L = hlua_states[state_id];
12422
12423 /* Initialize the filter ops with default callbacks */
12424 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012425 if (!hlua_flt_ops)
12426 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012427 hlua_flt_ops->init = hlua_filter_init;
12428 hlua_flt_ops->deinit = hlua_filter_deinit;
12429 if (state_id) {
12430 /* Set per-thread callback if script is loaded per-thread */
12431 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
12432 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
12433 }
12434 hlua_flt_ops->attach = hlua_filter_new;
12435 hlua_flt_ops->detach = hlua_filter_delete;
12436
12437 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012438 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012439
Christopher Fauletc404f112020-02-26 15:03:09 +010012440 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
12441 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
12442 lua_pop(L, 1);
12443 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
12444 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
12445 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012446 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
12447 hlua_flt_ops->http_headers = hlua_filter_http_headers;
12448 lua_pop(L, 1);
12449 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
12450 hlua_flt_ops->http_payload = hlua_filter_http_payload;
12451 lua_pop(L, 1);
12452 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
12453 hlua_flt_ops->http_end = hlua_filter_http_end;
12454 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010012455 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
12456 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
12457 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012458
12459 /* Get id and flags of the filter class */
12460 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
12461 flt_id = lua_tostring(L, -1);
12462 lua_pop(L, 1);
12463 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
12464 flt_flags = lua_tointeger(L, -1);
12465 lua_pop(L, 1);
12466
12467 /* Create the filter config */
12468 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012469 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020012470 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012471 conf->reg = reg_flt;
12472
12473 /* duplicate args */
12474 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
12475 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012476 if (!conf->args)
12477 goto error;
12478 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012479 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012480 if (!conf->args[pos])
12481 goto error;
12482 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012483 conf->args[pos] = NULL;
12484 *cur_arg += pos + 1;
12485
Christopher Fauletc86bb872021-08-13 08:33:57 +020012486 if (flt_id) {
12487 fconf->id = strdup(flt_id);
12488 if (!fconf->id)
12489 goto error;
12490 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012491 fconf->flags = flt_flags;
12492 fconf->conf = conf;
12493 fconf->ops = hlua_flt_ops;
12494
12495 lua_settop(L, 0);
12496 return 0;
12497
12498 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020012499 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012500 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012501 if (conf && conf->args) {
12502 for (pos = 0; conf->args[pos]; pos++)
12503 free(conf->args[pos]);
12504 free(conf->args);
12505 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012506 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012507 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012508 lua_settop(L, 0);
12509 return -1;
12510}
12511
Christopher Fauletc404f112020-02-26 15:03:09 +010012512__LJMP static int hlua_register_data_filter(lua_State *L)
12513{
12514 struct filter *filter;
12515 struct channel *chn;
12516
12517 MAY_LJMP(check_args(L, 2, "register_data_filter"));
12518 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12519 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12520
12521 lua_getfield(L, 1, "__filter");
12522 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12523 filter = lua_touserdata (L, -1);
12524 lua_pop(L, 1);
12525
12526 register_data_filter(chn_strm(chn), chn, filter);
12527 return 1;
12528}
12529
12530__LJMP static int hlua_unregister_data_filter(lua_State *L)
12531{
12532 struct filter *filter;
12533 struct channel *chn;
12534
12535 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
12536 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12537 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12538
12539 lua_getfield(L, 1, "__filter");
12540 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12541 filter = lua_touserdata (L, -1);
12542 lua_pop(L, 1);
12543
12544 unregister_data_filter(chn_strm(chn), chn, filter);
12545 return 1;
12546}
12547
Christopher Faulet69c581a2021-05-31 08:54:04 +020012548/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012549 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020012550 * parse configuration arguments.
12551 */
12552__LJMP static int hlua_register_filter(lua_State *L)
12553{
12554 struct buffer *trash;
12555 struct flt_kw_list *fkl;
12556 struct flt_kw *fkw;
12557 const char *name;
12558 struct hlua_reg_filter *reg_flt= NULL;
12559 int flt_ref, fun_ref;
12560 int len;
12561
12562 MAY_LJMP(check_args(L, 3, "register_filter"));
12563
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010012564 if (hlua_gethlua(L)) {
12565 /* runtime processing */
12566 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
12567 }
12568
Christopher Faulet69c581a2021-05-31 08:54:04 +020012569 /* First argument : filter name. */
12570 name = MAY_LJMP(luaL_checkstring(L, 1));
12571
12572 /* Second argument : The filter class */
12573 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
12574
12575 /* Third argument : lua function. */
12576 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
12577
12578 trash = get_trash_chunk();
12579 chunk_printf(trash, "lua.%s", name);
12580 fkw = flt_find_kw(trash->area);
12581 if (fkw != NULL) {
12582 reg_flt = fkw->private;
12583 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
12584 ha_warning("Trying to register filter 'lua.%s' more than once. "
12585 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012586 if (reg_flt->flt_ref[hlua_state_id] != -1)
12587 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
12588 if (reg_flt->fun_ref[hlua_state_id] != -1)
12589 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012590 }
12591 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12592 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12593 return 0;
12594 }
12595
12596 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
12597 if (!fkl)
12598 goto alloc_error;
12599 fkl->scope = "HLUA";
12600
12601 reg_flt = new_hlua_reg_filter(name);
12602 if (!reg_flt)
12603 goto alloc_error;
12604
12605 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12606 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12607
12608 /* The filter keyword */
12609 len = strlen("lua.") + strlen(name) + 1;
12610 fkl->kw[0].kw = calloc(1, len);
12611 if (!fkl->kw[0].kw)
12612 goto alloc_error;
12613
12614 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
12615
12616 fkl->kw[0].parse = hlua_filter_parse_fct;
12617 fkl->kw[0].private = reg_flt;
12618 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
12619
12620 /* Register this new filter */
12621 flt_register_keywords(fkl);
12622
12623 return 0;
12624
12625 alloc_error:
12626 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012627 hlua_unref(L, flt_ref);
12628 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012629 ha_free(&fkl);
12630 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
12631 return 0; /* Never reached */
12632}
12633
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012634static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012635 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012636 char **err, unsigned int *timeout)
12637{
12638 const char *error;
12639
12640 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020012641 if (error == PARSE_TIME_OVER) {
12642 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
12643 args[1], args[0]);
12644 return -1;
12645 }
12646 else if (error == PARSE_TIME_UNDER) {
12647 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
12648 args[1], args[0]);
12649 return -1;
12650 }
12651 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012652 memprintf(err, "%s: invalid timeout", args[0]);
12653 return -1;
12654 }
12655 return 0;
12656}
12657
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012658static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
12659 const struct proxy *defpx, const char *file, int line,
12660 char **err)
12661{
12662 return hlua_read_timeout(args, section_type, curpx, defpx,
12663 file, line, err, &hlua_timeout_burst);
12664}
12665
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012666static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012667 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012668 char **err)
12669{
12670 return hlua_read_timeout(args, section_type, curpx, defpx,
12671 file, line, err, &hlua_timeout_session);
12672}
12673
12674static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012675 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012676 char **err)
12677{
12678 return hlua_read_timeout(args, section_type, curpx, defpx,
12679 file, line, err, &hlua_timeout_task);
12680}
12681
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012682static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012683 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012684 char **err)
12685{
12686 return hlua_read_timeout(args, section_type, curpx, defpx,
12687 file, line, err, &hlua_timeout_applet);
12688}
12689
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012690static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012691 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012692 char **err)
12693{
12694 char *error;
12695
12696 hlua_nb_instruction = strtoll(args[1], &error, 10);
12697 if (*error != '\0') {
12698 memprintf(err, "%s: invalid number", args[0]);
12699 return -1;
12700 }
12701 return 0;
12702}
12703
Willy Tarreau32f61e22015-03-18 17:54:59 +010012704static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012705 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012706 char **err)
12707{
12708 char *error;
12709
12710 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012711 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012712 return -1;
12713 }
12714 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12715 if (*error != '\0') {
12716 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12717 return -1;
12718 }
12719 return 0;
12720}
12721
Tristan2632d042023-10-23 13:07:39 +010012722static int hlua_cfg_parse_log_loggers(char **args, int section_type, struct proxy *curpx,
12723 const struct proxy *defpx, const char *file, int line,
12724 char **err)
12725{
12726 if (too_many_args(1, args, err, NULL))
12727 return -1;
12728
12729 if (strcmp(args[1], "on") == 0)
12730 hlua_log_opts |= HLUA_LOG_LOGGERS_ON;
12731 else if (strcmp(args[1], "off") == 0)
12732 hlua_log_opts &= ~HLUA_LOG_LOGGERS_ON;
12733 else {
12734 memprintf(err, "'%s' expects either 'on' or 'off' but got '%s'.", args[0], args[1]);
12735 return -1;
12736 }
12737 return 0;
12738}
12739
12740static int hlua_cfg_parse_log_stderr(char **args, int section_type, struct proxy *curpx,
12741 const struct proxy *defpx, const char *file, int line,
12742 char **err)
12743{
12744 if (too_many_args(1, args, err, NULL))
12745 return -1;
12746
12747 if (strcmp(args[1], "on") == 0)
12748 hlua_log_opts = (hlua_log_opts & ~HLUA_LOG_STDERR_MASK) | HLUA_LOG_STDERR_ON;
12749 else if (strcmp(args[1], "auto") == 0)
12750 hlua_log_opts = (hlua_log_opts & ~HLUA_LOG_STDERR_MASK) | HLUA_LOG_STDERR_AUTO;
12751 else if (strcmp(args[1], "off") == 0)
12752 hlua_log_opts &= ~HLUA_LOG_STDERR_MASK;
12753 else {
12754 memprintf(err, "'%s' expects either 'on', 'auto', or 'off' but got '%s'.", args[0], args[1]);
12755 return -1;
12756 }
12757 return 0;
12758}
Willy Tarreau32f61e22015-03-18 17:54:59 +010012759
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012760/* This function is called by the main configuration key "lua-load". It loads and
12761 * execute an lua file during the parsing of the HAProxy configuration file. It is
12762 * the main lua entry point.
12763 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012764 * This function runs with the HAProxy keywords API. It returns -1 if an error
12765 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012766 *
12767 * In some error case, LUA set an error message in top of the stack. This function
12768 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012769 *
12770 * This function can fail with an abort() due to an Lua critical error.
12771 * We are in the configuration parsing process of HAProxy, this abort() is
12772 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012773 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012774static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012775{
12776 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012777 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012778
12779 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012780 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012781 if (error) {
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012782 memprintf(err, "error in Lua file '%s': %s", args[0], hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012783 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012784 return -1;
12785 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012786
12787 /* Push args in the Lua stack, except the first one which is the filename */
12788 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012789 /* Check stack size. */
12790 if (!lua_checkstack(L, 1)) {
12791 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12792 return -1;
12793 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012794 lua_pushstring(L, args[nargs]);
12795 }
12796 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012797
12798 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012799 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012800 switch (error) {
12801 case LUA_OK:
12802 break;
12803 case LUA_ERRRUN:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012804 memprintf(err, "Lua runtime error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012805 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012806 return -1;
12807 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012808 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012809 return -1;
12810 case LUA_ERRERR:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012811 memprintf(err, "Lua message handler error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012812 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012813 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012814#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012815 case LUA_ERRGCMM:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012816 memprintf(err, "Lua garbage collector error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012817 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012818 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012819#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012820 default:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012821 memprintf(err, "Lua unknown error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012822 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012823 return -1;
12824 }
12825
12826 return 0;
12827}
12828
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012829static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012830 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012831 char **err)
12832{
12833 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012834 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012835 return -1;
12836 }
12837
Thierry Fournier59f11be2020-11-29 00:37:41 +010012838 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012839 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012840 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012841 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012842}
12843
Thierry Fournier59f11be2020-11-29 00:37:41 +010012844static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012845 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012846 char **err)
12847{
12848 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012849 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012850
12851 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012852 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012853 return -1;
12854 }
12855
12856 if (per_thread_load == NULL) {
12857 /* allocate the first entry large enough to store the final NULL */
12858 per_thread_load = calloc(1, sizeof(*per_thread_load));
12859 if (per_thread_load == NULL) {
12860 memprintf(err, "out of memory error");
12861 return -1;
12862 }
12863 }
12864
12865 /* count used entries */
12866 for (len = 0; per_thread_load[len] != NULL; len++)
12867 ;
12868
12869 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12870 if (per_thread_load == NULL) {
12871 memprintf(err, "out of memory error");
12872 return -1;
12873 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012874 per_thread_load[len + 1] = NULL;
12875
Thierry Fournierae6b5682022-09-19 09:04:16 +020012876 /* count args excepting the first, allocate array and copy args */
12877 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012878 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012879 if (per_thread_load[len] == NULL) {
12880 memprintf(err, "out of memory error");
12881 return -1;
12882 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012883 for (i = 1; *(args[i]) != 0; i++) {
12884 per_thread_load[len][i - 1] = strdup(args[i]);
12885 if (per_thread_load[len][i - 1] == NULL) {
12886 memprintf(err, "out of memory error");
12887 return -1;
12888 }
12889 }
12890 per_thread_load[len][i - 1] = strdup("");
12891 if (per_thread_load[len][i - 1] == NULL) {
12892 memprintf(err, "out of memory error");
12893 return -1;
12894 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012895
12896 /* loading for thread 1 only */
12897 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012898 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012899 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012900}
12901
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012902/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12903 * in the given <ctx>.
12904 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012905static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012906{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012907 lua_getglobal(L, "package"); /* push package variable */
12908 lua_pushstring(L, path); /* push given path */
12909 lua_pushstring(L, ";"); /* push semicolon */
12910 lua_getfield(L, -3, type); /* push old path */
12911 lua_concat(L, 3); /* concatenate to new path */
12912 lua_setfield(L, -2, type); /* store new path */
12913 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012914
12915 return 0;
12916}
12917
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012918static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012919 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012920 char **err)
12921{
12922 char *path;
12923 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012924 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012925 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012926
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012927 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012928 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012929 }
12930
12931 if (!(*args[1])) {
12932 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012933 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012934 }
12935 path = args[1];
12936
12937 if (*args[2]) {
12938 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12939 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012940 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012941 }
12942 type = args[2];
12943 }
12944
Thierry Fournier59f11be2020-11-29 00:37:41 +010012945 p = calloc(1, sizeof(*p));
12946 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012947 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012948 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012949 }
12950 p->path = strdup(path);
12951 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012952 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012953 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012954 }
12955 p->type = strdup(type);
12956 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012957 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012958 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012959 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012960 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012961
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012962 /* Handle the global state and the per-thread state for the first
12963 * thread. The remaining threads will be initialized based on
12964 * prepend_path_list.
12965 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012966 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012967 lua_State *L = hlua_states[i];
12968 const char *error;
12969
12970 if (setjmp(safe_ljmp_env) != 0) {
12971 lua_atpanic(L, hlua_panic_safe);
12972 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012973 error = hlua_tostring_safe(L, -1);
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012974 else
12975 error = "critical error";
12976 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12977 exit(1);
12978 } else {
12979 lua_atpanic(L, hlua_panic_ljmp);
12980 }
12981
12982 hlua_prepend_path(L, type, path);
12983
12984 lua_atpanic(L, hlua_panic_safe);
12985 }
12986
Thierry Fournier59f11be2020-11-29 00:37:41 +010012987 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012988
12989err2:
12990 free(p->type);
12991 free(p->path);
12992err:
12993 free(p);
12994 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012995}
12996
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012997/* configuration keywords declaration */
12998static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012999 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010013000 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010013001 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010013002 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
13003 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020013004 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020013005 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010013006 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010013007 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Tristan2632d042023-10-23 13:07:39 +010013008 { CFG_GLOBAL, "tune.lua.log.loggers", hlua_cfg_parse_log_loggers },
13009 { CFG_GLOBAL, "tune.lua.log.stderr", hlua_cfg_parse_log_stderr },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010013010 { 0, NULL, NULL },
13011}};
13012
Willy Tarreau0108d902018-11-25 19:14:37 +010013013INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
13014
William Lallemand52139182022-03-30 15:05:42 +020013015#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010013016
William Lallemand30fcca12022-03-30 12:03:12 +020013017/*
13018 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
13019 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
13020 * difference is that the yield in lua and for the CLI is not handled the same
13021 * way.
13022 */
13023__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
13024{
13025 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
13026 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
13027 struct ckch_inst *ckchi = *lua_ckchi;
13028 struct ckch_store *old_ckchs = lua_ckchs[0];
13029 struct ckch_store *new_ckchs = lua_ckchs[1];
13030 struct hlua *hlua;
13031 char *err = NULL;
13032 int y = 1;
13033
13034 hlua = hlua_gethlua(L);
13035
13036 /* get the first ckchi to copy */
13037 if (ckchi == NULL)
13038 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
13039
13040 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
13041 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
13042 struct ckch_inst *new_inst;
13043
Aurelien DARRAGON60497352024-06-03 16:18:27 +020013044 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances
13045 * during runtime
13046 */
13047 if (hlua && (y % 10) == 0) {
William Lallemand30fcca12022-03-30 12:03:12 +020013048
13049 *lua_ckchi = ckchi;
13050
13051 task_wakeup(hlua->task, TASK_WOKEN_MSG);
13052 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
13053 }
13054
13055 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
13056 goto error;
13057
13058 /* link the new ckch_inst to the duplicate */
13059 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
13060 y++;
13061 }
13062
13063 /* The generation is finished, we can insert everything */
13064 ckch_store_replace(old_ckchs, new_ckchs);
13065
13066 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
13067
13068 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
13069
13070 return 0;
13071
13072error:
13073 ckch_store_free(new_ckchs);
13074 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
Aurelien DARRAGONf176a2a2024-06-04 15:15:29 +020013075 hlua_pushfstring_safe(L, "%s", err);
William Lallemand30fcca12022-03-30 12:03:12 +020013076 free(err);
Aurelien DARRAGONf176a2a2024-06-04 15:15:29 +020013077 WILL_LJMP(lua_error(L));
William Lallemand30fcca12022-03-30 12:03:12 +020013078
13079 return 0;
13080}
13081
13082/*
13083 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
13084 * from the table in parameter.
13085 *
13086 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
13087 * means it does not need to have a transaction since everything is done in the
13088 * same function.
13089 *
13090 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
13091 *
13092 */
13093__LJMP static int hlua_ckch_set(lua_State *L)
13094{
13095 struct hlua *hlua;
13096 struct ckch_inst **lua_ckchi;
13097 struct ckch_store **lua_ckchs;
13098 struct ckch_store *old_ckchs = NULL;
13099 struct ckch_store *new_ckchs = NULL;
13100 int errcode = 0;
13101 char *err = NULL;
13102 struct cert_exts *cert_ext = NULL;
13103 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010013104 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020013105 int ret;
13106
13107 if (lua_type(L, -1) != LUA_TTABLE)
13108 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
13109
13110 hlua = hlua_gethlua(L);
Aurelien DARRAGON60497352024-06-03 16:18:27 +020013111 if (hlua && HLUA_CANT_YIELD(hlua)) {
13112 /* using hlua_ckch_set() during runtime from a context that
13113 * doesn't allow yielding (e.g.: fetches) is not supported
13114 * as it may cause contention.
13115 */
13116 WILL_LJMP(luaL_error(L, "Cannot use CertCache.set from a "
13117 "non-yield capable runtime context"));
13118 }
William Lallemand30fcca12022-03-30 12:03:12 +020013119
13120 /* FIXME: this should not return an error but should come back later */
13121 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
13122 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
13123
13124 ret = lua_getfield(L, -1, "filename");
13125 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020013126 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020013127 errcode |= ERR_ALERT | ERR_FATAL;
13128 goto end;
13129 }
13130 filename = (char *)lua_tostring(L, -1);
13131
13132
13133 /* look for the filename in the tree */
13134 old_ckchs = ckchs_lookup(filename);
13135 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020013136 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020013137 errcode |= ERR_ALERT | ERR_FATAL;
13138 goto end;
13139 }
13140 /* TODO: handle extra_files_noext */
13141
13142 new_ckchs = ckchs_dup(old_ckchs);
13143 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020013144 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020013145 errcode |= ERR_ALERT | ERR_FATAL;
13146 goto end;
13147 }
13148
William Lallemand52ddd992022-11-22 11:51:53 +010013149 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020013150
13151 /* loop on the field in the table, which have the same name as the
13152 * possible extensions of files */
13153 lua_pushnil(L);
13154 while (lua_next(L, 1)) {
13155 int i;
13156 const char *field = lua_tostring(L, -2);
13157 char *payload = (char *)lua_tostring(L, -1);
13158
13159 if (!field || strcmp(field, "filename") == 0) {
13160 lua_pop(L, 1);
13161 continue;
13162 }
13163
13164 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
13165 if (strcmp(field, cert_exts[i].ext) == 0) {
13166 cert_ext = &cert_exts[i];
13167 break;
13168 }
13169 }
13170
13171 /* this is the default type, the field is not supported */
13172 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020013173 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020013174 errcode |= ERR_ALERT | ERR_FATAL;
13175 goto end;
13176 }
13177
Frédéric Lécaille1409dea2023-12-06 11:42:42 +010013178 /* Reset the OCSP CID */
13179 if (cert_ext->type == CERT_TYPE_PEM || cert_ext->type == CERT_TYPE_KEY ||
13180 cert_ext->type == CERT_TYPE_ISSUER) {
13181 OCSP_CERTID_free(new_ckchs->data->ocsp_cid);
13182 new_ckchs->data->ocsp_cid = NULL;
13183 }
13184
13185 /* apply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010013186 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020013187 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020013188 errcode |= ERR_ALERT | ERR_FATAL;
13189 goto end;
13190 }
13191 lua_pop(L, 1);
13192 }
13193
13194 /* store the pointers on the lua stack */
13195 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
13196 lua_ckchs[0] = old_ckchs;
13197 lua_ckchs[1] = new_ckchs;
13198 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
13199 *lua_ckchi = NULL;
13200
Aurelien DARRAGON60497352024-06-03 16:18:27 +020013201 if (hlua) {
13202 /* yield right away to let hlua_ckch_commit_yield() benefit from
13203 * a fresh task cycle on next wakeup
13204 */
13205 task_wakeup(hlua->task, TASK_WOKEN_MSG);
13206 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
13207 } else {
13208 /* body/init context: yielding not available, perform the commit as a
13209 * 1-shot operation (may be slow, but haproxy process is starting so
13210 * it is acceptable)
13211 */
13212 hlua_ckch_commit_yield(L, LUA_OK, 0);
13213 }
William Lallemand30fcca12022-03-30 12:03:12 +020013214
13215end:
13216 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
13217
13218 if (errcode & ERR_CODE) {
13219 ckch_store_free(new_ckchs);
Aurelien DARRAGONf176a2a2024-06-04 15:15:29 +020013220 hlua_pushfstring_safe(L, "%s", err);
13221 free(err);
13222 WILL_LJMP(lua_error(L));
William Lallemand30fcca12022-03-30 12:03:12 +020013223 }
13224 free(err);
13225
13226 return 0;
13227}
13228
William Lallemand52139182022-03-30 15:05:42 +020013229#else
13230
13231__LJMP static int hlua_ckch_set(lua_State *L)
13232{
13233 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
13234
13235 return 0;
13236}
13237#endif /* ! USE_OPENSSL */
13238
13239
13240
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013241/* This function can fail with an abort() due to an Lua critical error.
13242 * We are in the initialisation process of HAProxy, this abort() is
13243 * tolerated.
13244 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010013245int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013246{
13247 struct hlua_init_function *init;
13248 const char *msg;
13249 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013250 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010013251 const char *kind;
13252 const char *trace;
13253 int return_status = 1;
13254#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
13255 int nres;
13256#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013257
Willy Tarreaucdb53462020-12-02 12:12:00 +010013258 /* disable memory limit checks if limit is not set */
13259 if (!hlua_global_allocator.limit)
13260 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
13261
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050013262 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010013263 if (setjmp(safe_ljmp_env) != 0) {
13264 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010013265 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010013266 error = hlua_tostring_safe(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010013267 else
13268 error = "critical error";
13269 fprintf(stderr, "Lua post-init: %s.\n", error);
13270 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013271 } else {
13272 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010013273 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020013274
Thierry Fournierc7492592020-11-28 23:57:24 +010013275 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010013276 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010013277 /* function ref should be released right away since it was pushed
13278 * on the stack and will not be used anymore
13279 */
13280 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010013281
13282#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Aurelien DARRAGON3ddcd1b2023-09-08 19:29:08 +020013283 ret = lua_resume(L, NULL, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010013284#else
Aurelien DARRAGON3ddcd1b2023-09-08 19:29:08 +020013285 ret = lua_resume(L, NULL, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010013286#endif
13287 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013288 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010013289
13290 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010013291 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010013292 break;
Thierry Fournier670db242020-11-28 10:49:59 +010013293
13294 case LUA_ERRERR:
13295 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010013296 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010013297 case LUA_ERRRUN:
13298 if (!kind)
13299 kind = "runtime error";
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010013300 msg = hlua_tostring_safe(L, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010013301 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010013302 if (msg)
13303 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
13304 else
13305 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +010013306
13307 lua_settop(L, 0); /* Empty the stack. */
Thierry Fournier670db242020-11-28 10:49:59 +010013308 return_status = 0;
13309 break;
13310
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013311 default:
Thierry Fournier670db242020-11-28 10:49:59 +010013312 /* Unknown error */
13313 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010013314 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010013315 case LUA_YIELD:
13316 /* yield is not configured at this step, this state doesn't happen */
13317 if (!kind)
13318 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010013319 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010013320 case LUA_ERRMEM:
13321 if (!kind)
13322 kind = "out of memory error";
Aurelien DARRAGON3e81aed2023-08-09 10:11:49 +020013323 lua_settop(L, 0); /* Empty the stack. */
Christopher Fauletd09cc512021-03-24 14:48:45 +010013324 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010013325 ha_alert("Lua init: %s: %s\n", kind, trace);
13326 return_status = 0;
13327 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013328 }
Thierry Fournier670db242020-11-28 10:49:59 +010013329 if (!return_status)
13330 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013331 }
Thierry Fournier3c539322020-11-28 16:05:05 +010013332
13333 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010013334 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013335}
13336
Thierry Fournierb8cef172020-11-28 15:37:17 +010013337int hlua_post_init()
13338{
Thierry Fournier59f11be2020-11-29 00:37:41 +010013339 int ret;
13340 int i;
13341 int errors;
13342 char *err = NULL;
13343 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013344 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013345
Willy Tarreaub1310492021-08-30 09:35:18 +020013346#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010013347 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013348 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010013349 int saved_used_backed = global.ssl_used_backend;
13350 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013351 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010013352 global.ssl_used_backend = saved_used_backed;
13353 }
13354#endif
13355
Thierry Fournierc7492592020-11-28 23:57:24 +010013356 /* Perform post init of common thread */
13357 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013358 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013359 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
13360 if (ret == 0)
13361 return 0;
13362
13363 /* init remaining lua states and load files */
13364 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
13365
13366 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013367 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013368
13369 /* Init lua state */
13370 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
13371
13372 /* Load lua files */
13373 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
13374 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
13375 if (ret != 0) {
13376 ha_alert("Lua init: %s\n", err);
13377 return 0;
13378 }
13379 }
13380 }
13381
13382 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013383 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013384
13385 /* Execute post init for all states */
13386 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
13387
13388 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013389 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013390
13391 /* run post init */
13392 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
13393 if (ret == 0)
13394 return 0;
13395 }
13396
13397 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013398 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013399
13400 /* control functions registering. Each function must have:
13401 * - only the function_ref[0] set positive and all other to -1
13402 * - only the function_ref[0] set to -1 and all other positive
13403 * This ensure a same reference is not used both in shared
13404 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013405 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010013406 * complicated to found for the end user.
13407 */
13408 errors = 0;
13409 list_for_each_entry(fcn, &referenced_functions, l) {
13410 ret = 0;
13411 for (i = 1; i < global.nbthread + 1; i++) {
13412 if (fcn->function_ref[i] == -1)
13413 ret--;
13414 else
13415 ret++;
13416 }
13417 if (abs(ret) != global.nbthread) {
13418 ha_alert("Lua function '%s' is not referenced in all thread. "
13419 "Expect function in all thread or in none thread.\n", fcn->name);
13420 errors++;
13421 continue;
13422 }
13423
13424 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013425 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
13426 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010013427 "exclusive.\n", fcn->name);
13428 errors++;
13429 }
13430 }
13431
Christopher Faulet69c581a2021-05-31 08:54:04 +020013432 /* Do the same with registered filters */
13433 list_for_each_entry(reg_flt, &referenced_filters, l) {
13434 ret = 0;
13435 for (i = 1; i < global.nbthread + 1; i++) {
13436 if (reg_flt->flt_ref[i] == -1)
13437 ret--;
13438 else
13439 ret++;
13440 }
13441 if (abs(ret) != global.nbthread) {
13442 ha_alert("Lua filter '%s' is not referenced in all thread. "
13443 "Expect function in all thread or in none thread.\n", reg_flt->name);
13444 errors++;
13445 continue;
13446 }
13447
13448 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
13449 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
13450 "and per-thread Lua context (through lua-load-per-thread). these two context "
Aurelien DARRAGONf77f3282024-03-11 13:49:56 +010013451 "exclusive.\n", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020013452 errors++;
13453 }
13454 }
13455
13456
Thierry Fournier59f11be2020-11-29 00:37:41 +010013457 if (errors > 0)
13458 return 0;
13459
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013460 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010013461 * -1 in order to have probably a segfault if someone use it
13462 */
13463 hlua_state_id = -1;
13464
13465 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010013466}
13467
Willy Tarreau32f61e22015-03-18 17:54:59 +010013468/* The memory allocator used by the Lua stack. <ud> is a pointer to the
13469 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
13470 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013471 * allocation. <nsize> is the requested new size. A new allocation is
13472 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010013473 * zero. This one verifies that the limits are respected but is optimized
13474 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013475 *
13476 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
13477 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
13478 * that and will simply allocate zero as if it were the result of malloc(0),
13479 * so mapping this onto realloc() will lead to memory leaks on non-glibc
13480 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010013481 */
13482static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
13483{
13484 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010013485 size_t limit, old, new;
13486
13487 /* a limit of ~0 means unlimited and boot complete, so there's no need
13488 * for accounting anymore.
13489 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013490 if (likely(~zone->limit == 0)) {
13491 if (!nsize)
13492 ha_free(&ptr);
13493 else
13494 ptr = realloc(ptr, nsize);
13495 return ptr;
13496 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010013497
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013498 if (!ptr)
13499 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010013500
Willy Tarreaucdb53462020-12-02 12:12:00 +010013501 /* enforce strict limits across all threads */
13502 limit = zone->limit;
13503 old = _HA_ATOMIC_LOAD(&zone->allocated);
13504 do {
13505 new = old + nsize - osize;
13506 if (unlikely(nsize && limit && new > limit))
13507 return NULL;
13508 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010013509
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013510 if (!nsize)
13511 ha_free(&ptr);
13512 else
13513 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010013514
13515 if (unlikely(!ptr && nsize)) // failed
13516 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
13517
13518 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010013519 return ptr;
13520}
13521
Thierry Fournierecb83c22020-11-28 15:49:44 +010013522/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013523 * We are in the initialisation process of HAProxy, this abort() is
13524 * tolerated.
13525 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010013526lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013527{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013528 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013529 int idx;
13530 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013531 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013532 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013533 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013534 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013535 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013536 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013537
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013538 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013539 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013540
firexinghe64d7afb2023-07-13 11:03:34 +080013541 if (!L) {
13542 fprintf(stderr,
13543 "Lua init: critical error: lua_newstate() returned NULL."
13544 " This may possibly be caused by a memory allocation error.\n");
13545 exit(1);
13546 }
13547
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013548 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013549 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013550 *context = NULL;
13551
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013552 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013553 * the Lua function can fail with an abort. We are in the initialisation
13554 * process of HAProxy, this abort() is tolerated.
13555 */
13556
Thierry Fournier3c539322020-11-28 16:05:05 +010013557 /* Call post initialisation function in safe environment. */
13558 if (setjmp(safe_ljmp_env) != 0) {
13559 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013560 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010013561 error_msg = hlua_tostring_safe(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013562 else
13563 error_msg = "critical error";
13564 fprintf(stderr, "Lua init: %s.\n", error_msg);
13565 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013566 } else {
13567 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013568 }
13569
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013570 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013571 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013572#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
13573#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
13574#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013575 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013576#endif
13577#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013578 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013579#endif
13580#undef HLUA_PREPEND_PATH_TOSTRING
13581#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013582
Thierry Fournier59f11be2020-11-29 00:37:41 +010013583 /* Apply configured prepend path */
13584 list_for_each_entry(pp, &prepend_path_list, l)
13585 hlua_prepend_path(L, pp->type, pp->path);
13586
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013587 /*
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +020013588 * Override some lua functions.
13589 *
13590 */
13591
13592 /* push our "safe" coroutine.create() function */
13593 lua_getglobal(L, "coroutine");
13594 lua_pushcclosure(L, hlua_coroutine_create, 0);
13595 lua_setfield(L, -2, "create");
13596
13597 /*
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013598 *
13599 * Create "core" object.
13600 *
13601 */
13602
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010013603 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013604 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013605
Thierry Fournierecb83c22020-11-28 15:49:44 +010013606 /* set the thread id */
13607 hlua_class_const_int(L, "thread", thread_num);
13608
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013609 /* Push the loglevel constants. */
Christopher Faulet12a5ee72024-02-29 15:41:17 +010013610 hlua_class_const_int(L, "silent", -1);
Willy Tarreau80f5fae2015-02-27 16:38:20 +010013611 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013612 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013613
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013614 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013615 hlua_class_function(L, "register_init", hlua_register_init);
13616 hlua_class_function(L, "register_task", hlua_register_task);
13617 hlua_class_function(L, "register_fetches", hlua_register_fetches);
13618 hlua_class_function(L, "register_converters", hlua_register_converters);
13619 hlua_class_function(L, "register_action", hlua_register_action);
13620 hlua_class_function(L, "register_service", hlua_register_service);
13621 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020013622 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013623 hlua_class_function(L, "yield", hlua_yield);
13624 hlua_class_function(L, "set_nice", hlua_set_nice);
13625 hlua_class_function(L, "sleep", hlua_sleep);
13626 hlua_class_function(L, "msleep", hlua_msleep);
13627 hlua_class_function(L, "add_acl", hlua_add_acl);
13628 hlua_class_function(L, "del_acl", hlua_del_acl);
13629 hlua_class_function(L, "set_map", hlua_set_map);
13630 hlua_class_function(L, "del_map", hlua_del_map);
13631 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020013632 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010013633 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013634 hlua_class_function(L, "log", hlua_log);
13635 hlua_class_function(L, "Debug", hlua_log_debug);
13636 hlua_class_function(L, "Info", hlua_log_info);
13637 hlua_class_function(L, "Warning", hlua_log_warning);
13638 hlua_class_function(L, "Alert", hlua_log_alert);
13639 hlua_class_function(L, "done", hlua_done);
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020013640 hlua_class_function(L, "disable_legacy_mailers", hlua_disable_legacy_mailers);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013641 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013642
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013643 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013644
13645 /*
13646 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013647 * Create "act" object.
13648 *
13649 */
13650
13651 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013652 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013653
13654 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013655 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
13656 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
13657 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
13658 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
13659 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
13660 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
13661 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
13662 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013663
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013664 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010013665
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013666 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013667
13668 /*
13669 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020013670 * Create "Filter" object.
13671 *
13672 */
13673
13674 /* This table entry is the object "filter" base. */
13675 lua_newtable(L);
13676
13677 /* push flags and constants */
13678 hlua_class_const_int(L, "CONTINUE", 1);
13679 hlua_class_const_int(L, "WAIT", 0);
13680 hlua_class_const_int(L, "ERROR", -1);
13681
13682 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
13683
Christopher Fauletc404f112020-02-26 15:03:09 +010013684 hlua_class_function(L, "wake_time", hlua_set_wake_time);
13685 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
13686 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
13687
Christopher Faulet69c581a2021-05-31 08:54:04 +020013688 lua_setglobal(L, "filter");
13689
13690 /*
13691 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013692 * Register class Map
13693 *
13694 */
13695
13696 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013697 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013698
13699 /* register pattern types. */
13700 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013701 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013702 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013703 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013704 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013705 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013706
13707 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013708 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013709
13710 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013711 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013712
Ilya Shipitsind4259502020-04-08 01:07:56 +050013713 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013714 lua_pushstring(L, "__index");
13715 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013716
13717 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013718 hlua_class_function(L, "lookup", hlua_map_lookup);
13719 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013720
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013721 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013722
Thierry Fournier45e78d72016-02-19 18:34:46 +010013723 /* Register previous table in the registry with reference and named entry.
13724 * The function hlua_register_metatable() pops the stack, so we
13725 * previously create a copy of the table.
13726 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013727 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
13728 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013729
13730 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013731 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013732
13733 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013734 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013735
13736 /*
13737 *
William Lallemand30fcca12022-03-30 12:03:12 +020013738 * Register "CertCache" class
13739 *
13740 */
13741
13742 /* Create and fill the metatable. */
13743 lua_newtable(L);
13744 /* Register */
13745 hlua_class_function(L, "set", hlua_ckch_set);
13746 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
13747
13748 /*
13749 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013750 * Register class Channel
13751 *
13752 */
13753
13754 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013755 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013756
Ilya Shipitsind4259502020-04-08 01:07:56 +050013757 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013758 lua_pushstring(L, "__index");
13759 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013760
13761 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013762 hlua_class_function(L, "data", hlua_channel_get_data);
13763 hlua_class_function(L, "line", hlua_channel_get_line);
13764 hlua_class_function(L, "set", hlua_channel_set_data);
13765 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013766 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013767 hlua_class_function(L, "prepend", hlua_channel_prepend);
13768 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013769 hlua_class_function(L, "send", hlua_channel_send);
13770 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013771 hlua_class_function(L, "input", hlua_channel_get_in_len);
13772 hlua_class_function(L, "output", hlua_channel_get_out_len);
13773 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013774 hlua_class_function(L, "is_full", hlua_channel_is_full);
13775 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013776
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013777 /* Deprecated API */
13778 hlua_class_function(L, "get", hlua_channel_get);
13779 hlua_class_function(L, "dup", hlua_channel_dup);
13780 hlua_class_function(L, "getline", hlua_channel_getline);
13781 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13782 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13783
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013784 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013785
13786 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013787 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013788
13789 /*
13790 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013791 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013792 *
13793 */
13794
13795 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013796 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013797
Ilya Shipitsind4259502020-04-08 01:07:56 +050013798 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013799 lua_pushstring(L, "__index");
13800 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013801
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013802 /* Browse existing fetches and create the associated
13803 * object method.
13804 */
13805 sf = NULL;
13806 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013807 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13808 * by an underscore.
13809 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013810 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013811 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013812 if (*p == '.' || *p == '-' || *p == '+')
13813 *p = '_';
13814
13815 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013816 lua_pushstring(L, trash.area);
13817 lua_pushlightuserdata(L, sf);
13818 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13819 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013820 }
13821
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013822 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013823
13824 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013825 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013826
13827 /*
13828 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013829 * Register class Converters
13830 *
13831 */
13832
13833 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013834 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013835
13836 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013837 lua_pushstring(L, "__index");
13838 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013839
13840 /* Browse existing converters and create the associated
13841 * object method.
13842 */
13843 sc = NULL;
13844 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013845 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13846 * by an underscore.
13847 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013848 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013849 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013850 if (*p == '.' || *p == '-' || *p == '+')
13851 *p = '_';
13852
13853 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013854 lua_pushstring(L, trash.area);
13855 lua_pushlightuserdata(L, sc);
13856 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13857 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013858 }
13859
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013860 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013861
13862 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013863 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013864
13865 /*
13866 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013867 * Register class HTTP
13868 *
13869 */
13870
13871 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013872 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013873
Ilya Shipitsind4259502020-04-08 01:07:56 +050013874 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013875 lua_pushstring(L, "__index");
13876 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013877
13878 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013879 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13880 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13881 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13882 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13883 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13884 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13885 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13886 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13887 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13888 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013889
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013890 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13891 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13892 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13893 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13894 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13895 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13896 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013897
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013898 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013899
13900 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013901 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013902
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013903 /*
13904 *
13905 * Register class HTTPMessage
13906 *
13907 */
13908
13909 /* Create and fill the metatable. */
13910 lua_newtable(L);
13911
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013912 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013913 lua_pushstring(L, "__index");
13914 lua_newtable(L);
13915
13916 /* Register Lua functions. */
13917 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13918 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13919 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13920 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13921 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13922 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13923 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13924 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13925 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13926 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13927 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13928 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13929 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13930 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13931 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13932 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13933 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13934 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13935
13936 hlua_class_function(L, "body", hlua_http_msg_get_body);
13937 hlua_class_function(L, "set", hlua_http_msg_set_data);
13938 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13939 hlua_class_function(L, "append", hlua_http_msg_append);
13940 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13941 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13942 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13943 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13944
13945 hlua_class_function(L, "send", hlua_http_msg_send);
13946 hlua_class_function(L, "forward", hlua_http_msg_forward);
13947
13948 lua_rawset(L, -3);
13949
13950 /* Register previous table in the registry with reference and named entry. */
13951 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013952
13953 /*
13954 *
13955 * Register class HTTPClient
13956 *
13957 */
13958
13959 /* Create and fill the metatable. */
13960 lua_newtable(L);
13961 lua_pushstring(L, "__index");
13962 lua_newtable(L);
13963 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013964 hlua_class_function(L, "head", hlua_httpclient_head);
13965 hlua_class_function(L, "put", hlua_httpclient_put);
13966 hlua_class_function(L, "post", hlua_httpclient_post);
13967 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013968 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013969 /* Register the garbage collector entry. */
13970 lua_pushstring(L, "__gc");
13971 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13972 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13973
William Lallemand3956c4e2021-09-21 16:25:15 +020013974
13975
13976 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013977 /*
13978 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013979 * Register class AppletTCP
13980 *
13981 */
13982
13983 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013984 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013985
Ilya Shipitsind4259502020-04-08 01:07:56 +050013986 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013987 lua_pushstring(L, "__index");
13988 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013989
13990 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013991 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13992 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13993 hlua_class_function(L, "send", hlua_applet_tcp_send);
13994 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13995 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13996 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13997 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13998 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013999
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014000 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020014001
14002 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014003 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020014004
14005 /*
14006 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020014007 * Register class AppletHTTP
14008 *
14009 */
14010
14011 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014012 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020014013
Ilya Shipitsind4259502020-04-08 01:07:56 +050014014 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014015 lua_pushstring(L, "__index");
14016 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020014017
14018 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014019 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
14020 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
14021 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
14022 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
14023 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
14024 hlua_class_function(L, "getline", hlua_applet_http_getline);
14025 hlua_class_function(L, "receive", hlua_applet_http_recv);
14026 hlua_class_function(L, "send", hlua_applet_http_send);
14027 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
14028 hlua_class_function(L, "set_status", hlua_applet_http_status);
14029 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020014030
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014031 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020014032
14033 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014034 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020014035
14036 /*
14037 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010014038 * Register class TXN
14039 *
14040 */
14041
14042 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014043 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010014044
Ilya Shipitsind4259502020-04-08 01:07:56 +050014045 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014046 lua_pushstring(L, "__index");
14047 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010014048
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010014049 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014050 hlua_class_function(L, "set_priv", hlua_set_priv);
14051 hlua_class_function(L, "get_priv", hlua_get_priv);
14052 hlua_class_function(L, "set_var", hlua_set_var);
14053 hlua_class_function(L, "unset_var", hlua_unset_var);
14054 hlua_class_function(L, "get_var", hlua_get_var);
14055 hlua_class_function(L, "done", hlua_txn_done);
14056 hlua_class_function(L, "reply", hlua_txn_reply_new);
14057 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
14058 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
14059 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
14060 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
14061 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
14062 hlua_class_function(L, "deflog", hlua_txn_deflog);
14063 hlua_class_function(L, "log", hlua_txn_log);
14064 hlua_class_function(L, "Debug", hlua_txn_log_debug);
14065 hlua_class_function(L, "Info", hlua_txn_log_info);
14066 hlua_class_function(L, "Warning", hlua_txn_log_warning);
14067 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010014068
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014069 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010014070
14071 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014072 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014073
14074 /*
14075 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010014076 * Register class reply
14077 *
14078 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014079 lua_newtable(L);
14080 lua_pushstring(L, "__index");
14081 lua_newtable(L);
14082 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
14083 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
14084 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
14085 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
14086 lua_settable(L, -3); /* Sets the __index entry. */
14087 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010014088
14089
14090 /*
14091 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014092 * Register class Socket
14093 *
14094 */
14095
14096 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014097 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014098
Ilya Shipitsind4259502020-04-08 01:07:56 +050014099 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014100 lua_pushstring(L, "__index");
14101 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014102
Baptiste Assmann84bb4932015-03-02 21:40:06 +010014103#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014104 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010014105#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014106 hlua_class_function(L, "connect", hlua_socket_connect);
14107 hlua_class_function(L, "send", hlua_socket_send);
14108 hlua_class_function(L, "receive", hlua_socket_receive);
14109 hlua_class_function(L, "close", hlua_socket_close);
14110 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
14111 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
14112 hlua_class_function(L, "setoption", hlua_socket_setoption);
14113 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014114
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014115 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014116
14117 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014118 lua_pushstring(L, "__gc");
14119 lua_pushcclosure(L, hlua_socket_gc, 0);
14120 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014121
14122 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010014123 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014124
Thierry Fournieraafc7772020-12-04 11:47:47 +010014125 lua_atpanic(L, hlua_panic_safe);
14126
14127 return L;
14128}
14129
14130void hlua_init(void) {
14131 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010014132 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010014133#ifdef USE_OPENSSL
14134 struct srv_kw *kw;
14135 int tmp_error;
14136 char *error;
14137 char *args[] = { /* SSL client configuration. */
14138 "ssl",
14139 "verify",
14140 "none",
14141 NULL
14142 };
14143#endif
14144
14145 /* Init post init function list head */
14146 for (i = 0; i < MAX_THREADS + 1; i++)
14147 LIST_INIT(&hlua_init_functions[i]);
14148
14149 /* Init state for common/shared lua parts */
14150 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020014151 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010014152 hlua_states[0] = hlua_init_state(0);
14153
14154 /* Init state 1 for thread 0. We have at least one thread. */
14155 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020014156 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010014157 hlua_states[1] = hlua_init_state(1);
14158
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014159 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020014160 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010014161 if (!socket_proxy) {
14162 fprintf(stderr, "Lua init: %s\n", errmsg);
14163 exit(1);
14164 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014165
14166 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010014167 socket_tcp = new_server(socket_proxy);
14168 if (!socket_tcp) {
14169 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
14170 exit(1);
14171 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014172
14173#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014174 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010014175 socket_ssl = new_server(socket_proxy);
14176 if (!socket_ssl) {
14177 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
14178 exit(1);
14179 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014180
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010014181 socket_ssl->use_ssl = 1;
14182 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014183
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000014184 for (i = 0; args[i] != NULL; i++) {
14185 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014186 /*
14187 *
14188 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080014189 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014190 * features like client certificates and ssl_verify.
14191 *
14192 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010014193 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014194 if (tmp_error != 0) {
14195 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
14196 abort(); /* This must be never arrives because the command line
14197 not editable by the user. */
14198 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000014199 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014200 }
14201 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010014202#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010014203
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010014204}
Willy Tarreaubb57d942016-12-21 19:04:56 +010014205
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020014206static void hlua_deinit()
14207{
Willy Tarreau186f3762020-12-04 11:48:12 +010014208 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020014209 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
14210
14211 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
14212 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010014213
14214 for (thr = 0; thr < MAX_THREADS+1; thr++) {
14215 if (hlua_states[thr])
14216 lua_close(hlua_states[thr]);
14217 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010014218
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020014219 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010014220
Willy Tarreau0f143af2021-03-05 10:41:48 +010014221#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020014222 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010014223#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010014224
14225 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020014226}
14227
14228REGISTER_POST_DEINIT(hlua_deinit);
14229
Willy Tarreau80713382018-11-26 10:19:54 +010014230static void hlua_register_build_options(void)
14231{
Willy Tarreaubb57d942016-12-21 19:04:56 +010014232 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010014233
Willy Tarreaubb57d942016-12-21 19:04:56 +010014234 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
14235 hap_register_build_opts(ptr, 1);
14236}
Willy Tarreau80713382018-11-26 10:19:54 +010014237
14238INITCALL0(STG_REGISTER, hlua_register_build_options);