blob: 4cfb76879680b5040b01b2b70c616802e00a75fa [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
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100263#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200264 ({ \
265 int ret; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100266 hlua_lock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200267 if (setjmp(safe_ljmp_env) != 0) { \
268 lua_atpanic(__L, hlua_panic_safe); \
269 ret = 0; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100270 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200271 } else { \
272 lua_atpanic(__L, hlua_panic_ljmp); \
273 ret = 1; \
274 } \
275 ret; \
276 })
277
278/* If we are the last function catching Lua errors, we
279 * must reset the panic function.
280 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100281#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200282 do { \
283 lua_atpanic(__L, hlua_panic_safe); \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100284 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200285 } while(0)
286
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100287#define SET_SAFE_LJMP(__HLUA) \
288 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
289
290#define RESET_SAFE_LJMP(__HLUA) \
291 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
292
293#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100294 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100295
296#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100297 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100298
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200299/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200300#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100301/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200302#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200303/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100304#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100305#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200306
Thierry Fournierafc63e22020-11-28 17:06:51 +0100307/* The main Lua execution context. The 0 index is the
308 * common state shared by all threads.
309 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100310static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100311
Christopher Fauletc404f112020-02-26 15:03:09 +0100312#define HLUA_FLT_CB_FINAL 0x00000001
313#define HLUA_FLT_CB_RETVAL 0x00000002
314#define HLUA_FLT_CB_ARG_CHN 0x00000004
315#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
316
Christopher Faulet9f55a502020-02-25 15:21:02 +0100317#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
318
Christopher Faulet69c581a2021-05-31 08:54:04 +0200319struct hlua_reg_filter {
320 char *name;
321 int flt_ref[MAX_THREADS + 1];
322 int fun_ref[MAX_THREADS + 1];
323 struct list l;
324};
325
326struct hlua_flt_config {
327 struct hlua_reg_filter *reg;
328 int ref[MAX_THREADS + 1];
329 char **args;
330};
331
332struct hlua_flt_ctx {
333 int ref; /* ref to the filter lua object */
334 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
335 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
336 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
337 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
338};
339
Willy Tarreau5321da92022-05-06 11:57:34 +0200340/* appctx context used by the cosockets */
341struct hlua_csk_ctx {
342 int connected;
343 struct xref xref; /* cross reference with the Lua object owner. */
344 struct list wake_on_read;
345 struct list wake_on_write;
346 struct appctx *appctx;
Christopher Faulet26786572023-09-27 17:39:44 +0200347 struct server *srv;
Christopher Fauletcb068552023-09-27 17:34:24 +0200348 int timeout;
Willy Tarreau5321da92022-05-06 11:57:34 +0200349 int die;
350};
351
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200352/* appctx context used by TCP services */
353struct hlua_tcp_ctx {
354 struct hlua *hlua;
355 int flags;
356 struct task *task;
357};
358
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200359/* appctx context used by HTTP services */
360struct hlua_http_ctx {
361 struct hlua *hlua;
362 int left_bytes; /* The max amount of bytes that we can read. */
363 int flags;
364 int status;
365 const char *reason;
366 struct task *task;
367};
368
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200369/* used by registered CLI keywords */
370struct hlua_cli_ctx {
371 struct hlua *hlua;
372 struct task *task;
373 struct hlua_function *fcn;
374};
375
Christopher Faulet69c581a2021-05-31 08:54:04 +0200376DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
377
Christopher Faulet9f55a502020-02-25 15:21:02 +0100378static int hlua_filter_from_payload(struct filter *filter);
379
Christopher Faulet69c581a2021-05-31 08:54:04 +0200380/* This is the chained list of struct hlua_flt referenced
381 * for haproxy filters. It is used for a post-initialisation control.
382 */
383static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
384
385
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100386/* This is the memory pool containing struct lua for applets
387 * (including cli).
388 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100389DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100390
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100391/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100392static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100393static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100394#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100395static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100396#endif
397
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100398/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100399struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100400
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100401/* The following variables contains the reference of the different
402 * Lua classes. These references are useful for identify metadata
403 * associated with an object.
404 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100405static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100406static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100407static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100408static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100409static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100410static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100411static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200412static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200413static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200414static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200415static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100416static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100417
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100418/* Lua max execution timeouts. By default, stream-related
419 * lua coroutines (e.g.: actions) have a short timeout.
420 * On the other hand tasks coroutines don't have a timeout because
421 * a task may remain alive during all the haproxy execution.
422 *
423 * Timeouts are expressed in milliseconds, they are meant to be used
424 * with hlua timer's API exclusively.
425 * 0 means no timeout
426 */
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200427static uint32_t hlua_timeout_burst = 1000; /* burst timeout. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100428static uint32_t hlua_timeout_session = 4000; /* session timeout. */
429static uint32_t hlua_timeout_task = 0; /* task timeout. */
430static uint32_t hlua_timeout_applet = 4000; /* applet timeout. */
431
432/* hlua multipurpose timer:
433 * used to compute burst lua time (within a single hlua_ctx_resume())
434 * and cumulative lua time for a given coroutine, and to check
435 * the lua coroutine against the configured timeouts
436 */
437
438/* fetch per-thread cpu_time with ms precision (may wrap) */
439static inline uint32_t _hlua_time_ms()
440{
441 /* We're interested in the current cpu time in ms, which will be returned
442 * as a uint32_t to save some space.
443 * We must take the following into account:
444 *
445 * - now_cpu_time_fast() which returns the time in nanoseconds as a uint64_t
446 * will wrap every 585 years.
447 * - uint32_t may only contain 4294967295ms (~=49.7 days), so _hlua_time_ms()
448 * itself will also wrap every 49.7 days.
449 *
450 * While we can safely ignore the now_cpu_time_fast() wrap, we must
451 * take care of the uint32_t wrap by making sure to exclusively
452 * manipulate the time using uint32_t everywhere _hlua_time_ms()
453 * is involved.
454 */
455 return (uint32_t)(now_cpu_time_fast() / 1000000ULL);
456}
457
458/* computes time spent in a single lua execution (in ms) */
459static inline uint32_t _hlua_time_burst(const struct hlua_timer *timer)
460{
461 uint32_t burst_ms;
462
463 /* wrapping is expected and properly
464 * handled thanks to _hlua_time_ms() and burst_ms
465 * being of the same type
466 */
467 burst_ms = _hlua_time_ms() - timer->start;
468 return burst_ms;
469}
470
471static inline void hlua_timer_init(struct hlua_timer *timer, unsigned int max)
472{
473 timer->cumulative = 0;
474 timer->burst = 0;
475 timer->max = max;
476}
477
478/* reset the timer ctx between 2 yields */
479static inline void hlua_timer_reset(struct hlua_timer *timer)
480{
481 timer->cumulative += timer->burst;
482 timer->burst = 0;
483}
484
485/* start the timer right before a new execution */
486static inline void hlua_timer_start(struct hlua_timer *timer)
487{
488 timer->start = _hlua_time_ms();
489}
490
491/* update hlua timer when finishing an execution */
492static inline void hlua_timer_stop(struct hlua_timer *timer)
493{
494 timer->burst += _hlua_time_burst(timer);
495}
496
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200497/* check the timers for current hlua context:
498 * - first check for burst timeout (max execution time for the current
499 hlua resume, ie: time between effective yields)
500 * - then check for yield cumulative timeout
501 *
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100502 * Returns 1 if the check succeeded and 0 if it failed
503 * (ie: timeout exceeded)
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100504 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100505static inline int hlua_timer_check(const struct hlua_timer *timer)
506{
507 uint32_t pburst = _hlua_time_burst(timer); /* pending burst time in ms */
508
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200509 if (hlua_timeout_burst && (timer->burst + pburst) > hlua_timeout_burst)
510 return 0; /* burst timeout exceeded */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100511 if (timer->max && (timer->cumulative + timer->burst + pburst) > timer->max)
512 return 0; /* cumulative timeout exceeded */
513 return 1; /* ok */
514}
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100515
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100516/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
517 * it is used for preventing infinite loops.
518 *
519 * I test the scheer with an infinite loop containing one incrementation
520 * and one test. I run this loop between 10 seconds, I raise a ceil of
521 * 710M loops from one interrupt each 9000 instructions, so I fix the value
522 * to one interrupt each 10 000 instructions.
523 *
524 * configured | Number of
525 * instructions | loops executed
526 * between two | in milions
527 * forced yields |
528 * ---------------+---------------
529 * 10 | 160
530 * 500 | 670
531 * 1000 | 680
532 * 5000 | 700
533 * 7000 | 700
534 * 8000 | 700
535 * 9000 | 710 <- ceil
536 * 10000 | 710
537 * 100000 | 710
538 * 1000000 | 710
539 *
540 */
541static unsigned int hlua_nb_instruction = 10000;
542
Willy Tarreaucdb53462020-12-02 12:12:00 +0100543/* Descriptor for the memory allocation state. The limit is pre-initialised to
544 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
545 * is replaced with ~0 during post_init after everything was loaded. This way
546 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
547 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100548 */
549struct hlua_mem_allocator {
550 size_t allocated;
551 size_t limit;
552};
553
Willy Tarreaucdb53462020-12-02 12:12:00 +0100554static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100555
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100556/* hlua event subscription */
557struct hlua_event_sub {
558 int fcn_ref;
559 int state_id;
560 struct hlua *hlua;
561 struct task *task;
562 event_hdl_async_equeue equeue;
563 struct event_hdl_sub *sub;
564 uint8_t paused;
565};
566
567/* This is the memory pool containing struct hlua_event_sub
568 * for event subscriptions from lua
569 */
570DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
571
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100572/* These functions converts types between HAProxy internal args or
573 * sample and LUA types. Another function permits to check if the
574 * LUA stack contains arguments according with an required ARG_T
575 * format.
576 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200577__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100578static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100579__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100580 uint64_t mask, struct proxy *p);
Aurelien DARRAGON41217722023-05-17 10:44:47 +0200581__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp);
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +0200582__LJMP static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100583static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
584
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100585__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200586
Thierry Fournier59f11be2020-11-29 00:37:41 +0100587struct prepend_path {
588 struct list l;
589 char *type;
590 char *path;
591};
592
593static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
594
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200595#define SEND_ERR(__be, __fmt, __args...) \
596 do { \
597 send_log(__be, LOG_ERR, __fmt, ## __args); \
598 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100599 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200600 } while (0)
601
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100602static inline struct hlua_function *new_hlua_function()
603{
604 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100605 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100606
607 fcn = calloc(1, sizeof(*fcn));
608 if (!fcn)
609 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200610 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100611 for (i = 0; i < MAX_THREADS + 1; i++)
612 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100613 return fcn;
614}
615
Christopher Fauletdda44442021-04-12 14:05:43 +0200616static inline void release_hlua_function(struct hlua_function *fcn)
617{
618 if (!fcn)
619 return;
620 if (fcn->name)
621 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200622 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200623 ha_free(&fcn);
624}
625
Thierry Fournierc7492592020-11-28 23:57:24 +0100626/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
627static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
628{
629 if (fcn->function_ref[0] == -1)
630 return tid + 1;
631 return 0;
632}
633
Christopher Faulet69c581a2021-05-31 08:54:04 +0200634/* Create a new registered filter. Only its name is filled */
635static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
636{
637 struct hlua_reg_filter *reg_flt;
638 int i;
639
640 reg_flt = calloc(1, sizeof(*reg_flt));
641 if (!reg_flt)
642 return NULL;
643 reg_flt->name = strdup(name);
644 if (!reg_flt->name) {
645 free(reg_flt);
646 return NULL;
647 }
648 LIST_APPEND(&referenced_filters, &reg_flt->l);
649 for (i = 0; i < MAX_THREADS + 1; i++) {
650 reg_flt->flt_ref[i] = -1;
651 reg_flt->fun_ref[i] = -1;
652 }
653 return reg_flt;
654}
655
656/* Release a registered filter */
657static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
658{
659 if (!reg_flt)
660 return;
661 if (reg_flt->name)
662 ha_free(&reg_flt->name);
663 LIST_DELETE(&reg_flt->l);
664 ha_free(&reg_flt);
665}
666
667/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
668static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
669{
670 if (reg_flt->fun_ref[0] == -1)
671 return tid + 1;
672 return 0;
673}
674
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100675/* Used to check an Lua function type in the stack. It creates and
676 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100677 * error if the argument is not a "function".
678 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100679 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100680__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100681{
682 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100683 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100684 WILL_LJMP(luaL_argerror(L, argno, msg));
685 }
686 lua_pushvalue(L, argno);
687 return luaL_ref(L, LUA_REGISTRYINDEX);
688}
689
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100690/* Used to check an Lua table type in the stack. It creates and
691 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100692 * error if the argument is not a "table".
693 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100694 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100695__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100696{
697 if (!lua_istable(L, argno)) {
698 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
699 WILL_LJMP(luaL_argerror(L, argno, msg));
700 }
701 lua_pushvalue(L, argno);
702 return luaL_ref(L, LUA_REGISTRYINDEX);
703}
704
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100705/* Get a reference to the object that is at the top of the stack
706 * The referenced object will be popped from the stack
707 *
708 * The function returns the reference to the object which must
709 * be cleared using hlua_unref() when no longer used
710 */
711__LJMP int hlua_ref(lua_State *L)
712{
713 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
714}
715
716/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
717 * on <L> stack
718 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
719 *
720 * When the reference is no longer used, it should be released by calling
721 * hlua_unref()
722 *
723 * <L> can be from any co-routine as long as it belongs to the same lua
724 * parent state that the one used to get the reference.
725 */
726void hlua_pushref(lua_State *L, int ref)
727{
728 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
729}
730
731/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
732 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
733 *
734 * This will allow the reference to be reused and the referred object
735 * to be garbage collected.
736 *
737 * <L> can be from any co-routine as long as it belongs to the same lua
738 * parent state that the one used to get the reference.
739 */
740void hlua_unref(lua_State *L, int ref)
741{
742 luaL_unref(L, LUA_REGISTRYINDEX, ref);
743}
744
Christopher Fauletd09cc512021-03-24 14:48:45 +0100745__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200746{
747 lua_Debug ar;
748 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200749 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200750
751 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200752 /* Fill fields:
753 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
754 * 'l': fills in the field currentline;
755 * 'n': fills in the field name and namewhat;
756 * 't': fills in the field istailcall;
757 */
758 lua_getinfo(L, "Slnt", &ar);
759
Willy Tarreau5c143402022-06-19 17:35:53 +0200760 /* skip these empty entries, usually they come from deep C functions */
761 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
762 continue;
763
764 /* Add separator */
765 if (b_data(msg))
766 chunk_appendf(msg, "%s", sep);
767
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200768 /* Append code localisation */
769 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100770 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200771 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100772 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200773
774 /*
775 * Get function name
776 *
777 * if namewhat is no empty, name is defined.
778 * what contains "Lua" for Lua function, "C" for C function,
779 * or "main" for main code.
780 */
781 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100782 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200783
784 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100785 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200786
787 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100788 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200789
790 else /* nothing left... */
791 chunk_appendf(msg, "?");
792
793
794 /* Display tailed call */
795 if (ar.istailcall)
796 chunk_appendf(msg, " ...");
797 }
798
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200799 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200800}
801
802
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100803/* This function check the number of arguments available in the
804 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500805 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100806 */
807__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
808{
809 if (lua_gettop(L) == nb)
810 return;
811 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
812}
813
Mark Lakes22154b42018-01-29 14:38:40 -0800814/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100815 * and the line number where the error is encountered.
816 */
817static int hlua_pusherror(lua_State *L, const char *fmt, ...)
818{
819 va_list argp;
820 va_start(argp, fmt);
821 luaL_where(L, 1);
822 lua_pushvfstring(L, fmt, argp);
823 va_end(argp);
824 lua_concat(L, 2);
825 return 1;
826}
827
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100828/* This functions is used with sample fetch and converters. It
829 * converts the HAProxy configuration argument in a lua stack
830 * values.
831 *
832 * It takes an array of "arg", and each entry of the array is
833 * converted and pushed in the LUA stack.
834 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200835__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100836{
837 switch (arg->type) {
838 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100839 case ARGT_TIME:
840 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100841 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100842 break;
843
844 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200845 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100846 break;
847
848 case ARGT_IPV4:
849 case ARGT_IPV6:
850 case ARGT_MSK4:
851 case ARGT_MSK6:
852 case ARGT_FE:
853 case ARGT_BE:
854 case ARGT_TAB:
855 case ARGT_SRV:
856 case ARGT_USR:
857 case ARGT_MAP:
858 default:
859 lua_pushnil(L);
860 break;
861 }
862 return 1;
863}
864
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500865/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100866 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500867 * with sample fetch wrappers. The input arguments are given to the
868 * lua wrapper and converted as arg list by the function.
Aurelien DARRAGON0aaf6c42023-05-17 15:33:59 +0200869 *
870 * Note: although lua_tolstring() may raise a memory error according to
871 * lua documentation, in practise this could only happen when using to
872 * use lua_tolstring() on a number (lua will try to push the number as a
873 * string on the stack, and this may result in memory failure), so here we
874 * assume that hlua_lua2arg() will never raise an exception since it is
875 * exclusively used with lua string inputs.
876 *
877 * Note2: You should be extra careful when using <arg> argument, since
878 * string arguments rely on lua_tolstring() which returns a pointer to lua
879 * object that may be garbage collected at any time when removed from lua
880 * stack, thus you should make sure that <arg> is only used from a local
881 * scope within lua context (and not exported or stored in a lua-independent
882 * ctx) and that related lua object still exists when accessing arg data.
883 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100884 */
885static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
886{
887 switch (lua_type(L, ud)) {
888
889 case LUA_TNUMBER:
890 case LUA_TBOOLEAN:
891 arg->type = ARGT_SINT;
892 arg->data.sint = lua_tointeger(L, ud);
893 break;
894
895 case LUA_TSTRING:
896 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200897 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200898 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200899 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200900 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100901 break;
902
903 case LUA_TUSERDATA:
904 case LUA_TNIL:
905 case LUA_TTABLE:
906 case LUA_TFUNCTION:
907 case LUA_TTHREAD:
908 case LUA_TLIGHTUSERDATA:
909 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200910 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100911 break;
912 }
913 return 1;
914}
915
916/* the following functions are used to convert a struct sample
917 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500918 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100919 */
Aurelien DARRAGON41217722023-05-17 10:44:47 +0200920__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100921{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200922 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100923 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100924 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200925 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100926 break;
927
928 case SMP_T_BIN:
929 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200930 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100931 break;
932
933 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200934 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100935 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
936 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
937 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
938 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
939 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
940 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
941 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
942 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
943 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200944 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100945 break;
946 default:
947 lua_pushnil(L);
948 break;
949 }
950 break;
951
952 case SMP_T_IPV4:
953 case SMP_T_IPV6:
954 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200955 if (sample_casts[smp->data.type][SMP_T_STR] &&
956 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200957 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100958 else
959 lua_pushnil(L);
960 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100961 default:
962 lua_pushnil(L);
963 break;
964 }
965 return 1;
966}
967
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100968/* the following functions are used to convert a struct sample
969 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500970 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100971 */
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +0200972__LJMP static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100973{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200974 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100975
976 case SMP_T_BIN:
977 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200978 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100979 break;
980
981 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200982 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100983 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
984 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
985 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
986 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
987 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
988 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
989 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
990 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
991 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200992 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100993 break;
994 default:
995 lua_pushstring(L, "");
996 break;
997 }
998 break;
999
1000 case SMP_T_SINT:
1001 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001002 case SMP_T_IPV4:
1003 case SMP_T_IPV6:
1004 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001005 if (sample_casts[smp->data.type][SMP_T_STR] &&
1006 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001007 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01001008 else
1009 lua_pushstring(L, "");
1010 break;
1011 default:
1012 lua_pushstring(L, "");
1013 break;
1014 }
1015 return 1;
1016}
1017
Aurelien DARRAGONa3624cb2023-05-17 15:44:45 +02001018/* The following function is used to convert a Lua type to a
1019 * struct sample. This is useful to provide data from LUA code to
1020 * a converter.
1021 *
1022 * Note: although lua_tolstring() may raise a memory error according to
1023 * lua documentation, in practise this could only happen when using to
1024 * use lua_tolstring() on a number (lua will try to push the number as a
1025 * string on the stack, and this may result in memory failure), so here we
1026 * assume that hlua_lua2arg() will never raise an exception since it is
1027 * exclusively used with lua string inputs.
1028 *
1029 * Note2: You should be extra careful when using <smp> argument, since
1030 * string arguments rely on lua_tolstring() which returns a pointer to lua
1031 * object that may be garbage collected at any time when removed from lua
1032 * stack, thus you should make sure that <smp> is only used from a local
1033 * scope within lua context (not exported or stored in a lua-independent
1034 * ctx) and that related lua object still exists when accessing arg data.
1035 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
1036 *
1037 * If you don't comply with this usage restriction, then you should consider
1038 * duplicating the smp using smp_dup() to make it portable (little overhead),
1039 * as this will ensure that the smp always points to valid memory block.
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001040 */
1041static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
1042{
1043 switch (lua_type(L, ud)) {
1044
1045 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001046 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001047 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001048 break;
1049
1050
1051 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001052 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001053 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001054 break;
1055
1056 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001057 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001058 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +02001059 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +02001060 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001061 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +02001062 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001063 break;
1064
1065 case LUA_TUSERDATA:
1066 case LUA_TNIL:
1067 case LUA_TTABLE:
1068 case LUA_TFUNCTION:
1069 case LUA_TTHREAD:
1070 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +02001071 case LUA_TNONE:
1072 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001073 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001074 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001075 break;
1076 }
1077 return 1;
1078}
1079
Ilya Shipitsind4259502020-04-08 01:07:56 +05001080/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001081 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001082 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001083 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001084 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +02001085 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001086 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001087__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +01001088 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001089{
1090 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001091 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001092 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +02001093 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001094 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001095 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001096 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001097
1098 idx = 0;
1099 min_arg = ARGM(mask);
1100 mask >>= ARGM_BITS;
1101
1102 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001103 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001104
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001105 /* Check for mandatory arguments. */
1106 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001107 if (idx < min_arg) {
1108
1109 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001110 if (idx > 0) {
1111 msg = "Mandatory argument expected";
1112 goto error;
1113 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001114
1115 /* If first argument have a certain type, some default values
1116 * may be used. See the function smp_resolve_args().
1117 */
1118 switch (mask & ARGT_MASK) {
1119
1120 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001121 if (!(p->cap & PR_CAP_FE)) {
1122 msg = "Mandatory argument expected";
1123 goto error;
1124 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001125 argp[idx].data.prx = p;
1126 argp[idx].type = ARGT_FE;
1127 argp[idx+1].type = ARGT_STOP;
1128 break;
1129
1130 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001131 if (!(p->cap & PR_CAP_BE)) {
1132 msg = "Mandatory argument expected";
1133 goto error;
1134 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001135 argp[idx].data.prx = p;
1136 argp[idx].type = ARGT_BE;
1137 argp[idx+1].type = ARGT_STOP;
1138 break;
1139
1140 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001141 if (!p->table) {
1142 msg = "Mandatory argument expected";
1143 goto error;
1144 }
1145 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001146 argp[idx].type = ARGT_TAB;
1147 argp[idx+1].type = ARGT_STOP;
1148 break;
1149
1150 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001151 msg = "Mandatory argument expected";
1152 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001153 break;
1154 }
1155 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001156 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001157 }
1158
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001159 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001160 if ((mask & ARGT_MASK) == ARGT_STOP &&
1161 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001162 msg = "Last argument expected";
1163 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001164 }
1165
1166 if ((mask & ARGT_MASK) == ARGT_STOP &&
1167 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001168 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001169 }
1170
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001171 /* Convert some argument types. All string in argp[] are for not
1172 * duplicated yet.
1173 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001174 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001175 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001176 if (argp[idx].type != ARGT_SINT) {
1177 msg = "integer expected";
1178 goto error;
1179 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001180 argp[idx].type = ARGT_SINT;
1181 break;
1182
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001183 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001184 if (argp[idx].type != ARGT_SINT) {
1185 msg = "integer expected";
1186 goto error;
1187 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001188 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001189 break;
1190
1191 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001192 if (argp[idx].type != ARGT_SINT) {
1193 msg = "integer expected";
1194 goto error;
1195 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001196 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001197 break;
1198
1199 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001200 if (argp[idx].type != ARGT_STR) {
1201 msg = "string expected";
1202 goto error;
1203 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001204 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001205 if (!argp[idx].data.prx) {
1206 msg = "frontend doesn't exist";
1207 goto error;
1208 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001209 argp[idx].type = ARGT_FE;
1210 break;
1211
1212 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001213 if (argp[idx].type != ARGT_STR) {
1214 msg = "string expected";
1215 goto error;
1216 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001217 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001218 if (!argp[idx].data.prx) {
1219 msg = "backend doesn't exist";
1220 goto error;
1221 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001222 argp[idx].type = ARGT_BE;
1223 break;
1224
1225 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001226 if (argp[idx].type != ARGT_STR) {
1227 msg = "string expected";
1228 goto error;
1229 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001230 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001231 if (!argp[idx].data.t) {
1232 msg = "table doesn't exist";
1233 goto error;
1234 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001235 argp[idx].type = ARGT_TAB;
1236 break;
1237
1238 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001239 if (argp[idx].type != ARGT_STR) {
1240 msg = "string expected";
1241 goto error;
1242 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001243 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001244 if (sname) {
1245 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001246 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001247 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001248 if (!px) {
1249 msg = "backend doesn't exist";
1250 goto error;
1251 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001252 }
1253 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001254 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001255 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001256 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001257 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001258 if (!argp[idx].data.srv) {
1259 msg = "server doesn't exist";
1260 goto error;
1261 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001262 argp[idx].type = ARGT_SRV;
1263 break;
1264
1265 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001266 if (argp[idx].type != ARGT_STR) {
1267 msg = "string expected";
1268 goto error;
1269 }
1270 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1271 msg = "invalid IPv4 address";
1272 goto error;
1273 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001274 argp[idx].type = ARGT_IPV4;
1275 break;
1276
1277 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001278 if (argp[idx].type == ARGT_SINT)
1279 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1280 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001281 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1282 msg = "invalid IPv4 mask";
1283 goto error;
1284 }
1285 }
1286 else {
1287 msg = "integer or string expected";
1288 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001289 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001290 argp[idx].type = ARGT_MSK4;
1291 break;
1292
1293 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001294 if (argp[idx].type != ARGT_STR) {
1295 msg = "string expected";
1296 goto error;
1297 }
1298 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1299 msg = "invalid IPv6 address";
1300 goto error;
1301 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001302 argp[idx].type = ARGT_IPV6;
1303 break;
1304
1305 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001306 if (argp[idx].type == ARGT_SINT)
1307 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1308 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001309 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1310 msg = "invalid IPv6 mask";
1311 goto error;
1312 }
1313 }
1314 else {
1315 msg = "integer or string expected";
1316 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001317 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001318 argp[idx].type = ARGT_MSK6;
1319 break;
1320
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001321 case ARGT_REG:
1322 if (argp[idx].type != ARGT_STR) {
1323 msg = "string expected";
1324 goto error;
1325 }
1326 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1327 if (!reg) {
1328 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1329 argp[idx].data.str.area, err);
1330 free(err);
1331 goto error;
1332 }
1333 argp[idx].type = ARGT_REG;
1334 argp[idx].data.reg = reg;
1335 break;
1336
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001337 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001338 if (argp[idx].type != ARGT_STR) {
1339 msg = "string expected";
1340 goto error;
1341 }
1342 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001343 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001344 ul = p->uri_auth->userlist;
1345 else
1346 ul = auth_find_userlist(argp[idx].data.str.area);
1347
1348 if (!ul) {
1349 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1350 goto error;
1351 }
1352 argp[idx].type = ARGT_USR;
1353 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001354 break;
1355
1356 case ARGT_STR:
1357 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1358 msg = "unable to duplicate string arg";
1359 goto error;
1360 }
1361 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001362 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001363
Christopher Fauletd25d9262020-08-06 11:04:46 +02001364 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001365 msg = "type not yet supported";
1366 goto error;
1367 break;
1368
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001369 }
1370
1371 /* Check for type of argument. */
1372 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001373 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1374 arg_type_names[(mask & ARGT_MASK)],
1375 arg_type_names[argp[idx].type & ARGT_MASK]);
1376 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001377 }
1378
1379 /* Next argument. */
1380 mask >>= ARGT_BITS;
1381 idx++;
1382 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001383 return 0;
1384
1385 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001386 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001387 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001388 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1389 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001390}
1391
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001392/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001393 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001394 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001395 *
1396 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001397 * - hlua_sethlua : create the association between hlua context and lua_state.
1398 */
Aurelien DARRAGON40cd44f2023-05-04 13:59:48 +02001399inline struct hlua *hlua_gethlua(lua_State *L)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001400{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001401 struct hlua **hlua = lua_getextraspace(L);
1402 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001403}
1404static inline void hlua_sethlua(struct hlua *hlua)
1405{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001406 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1407 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001408}
1409
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001410/* Will return a non-NULL string indicating the Lua call trace if the caller
1411 * currently is executing from within a Lua function. One line per entry will
1412 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1413 * Lua function is not detected, NULL is returned.
1414 */
1415const char *hlua_show_current_location(const char *pfx)
1416{
1417 lua_State *L;
1418 lua_Debug ar;
1419
1420 /* global or per-thread stack initializing ? */
1421 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1422 return hlua_traceback(L, pfx);
1423
1424 /* per-thread stack running ? */
1425 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1426 return hlua_traceback(L, pfx);
1427
1428 /* global stack running ? */
1429 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1430 return hlua_traceback(L, pfx);
1431
1432 return NULL;
1433}
1434
Tristan2632d042023-10-23 13:07:39 +01001435/* This function is used to send logs. It tries to send them to:
1436 * - the log target applicable in the current context, AND
1437 * - stderr if not in quiet mode or explicitly disabled
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001438 */
1439static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1440{
1441 struct tm tm;
1442 char *p;
1443
1444 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001445 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001446 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001447 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001448 /* Break the message if exceed the buffer size. */
1449 *(p-4) = ' ';
1450 *(p-3) = '.';
1451 *(p-2) = '.';
1452 *(p-1) = '.';
1453 break;
1454 }
Willy Tarreau90807112020-02-25 08:16:33 +01001455 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001456 *p = *msg;
1457 else
1458 *p = '.';
1459 }
1460 *p = '\0';
1461
Tristan2632d042023-10-23 13:07:39 +01001462 if (hlua_log_opts & HLUA_LOG_LOGGERS_ON)
1463 send_log(px, level, "%s\n", trash.area);
1464
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001465 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Tristan2632d042023-10-23 13:07:39 +01001466 if (!(hlua_log_opts & HLUA_LOG_STDERR_MASK))
1467 return;
1468
1469 /* when logging via stderr is set to 'auto', it behaves like 'off' unless one of:
1470 * - logging via loggers is disabled
1471 * - this is a non-proxy context and there is no global logger configured
1472 * - this is a proxy context and the proxy has no logger configured
1473 */
1474 if ((hlua_log_opts & (HLUA_LOG_STDERR_MASK | HLUA_LOG_LOGGERS_ON)) == (HLUA_LOG_STDERR_AUTO | HLUA_LOG_LOGGERS_ON)) {
1475 /* AUTO=OFF in non-proxy context only if at least one global logger is defined */
1476 if ((px == NULL) && (!LIST_ISEMPTY(&global.logsrvs)))
1477 return;
1478
1479 /* AUTO=OFF in proxy context only if at least one logger is configured for the proxy */
1480 if ((px != NULL) && (!LIST_ISEMPTY(&px->logsrvs)))
1481 return;
1482 }
1483
Christopher Fauletf98d8212020-10-02 18:13:52 +02001484 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1485 return;
1486
Willy Tarreaua678b432015-08-28 10:14:59 +02001487 get_localtime(date.tv_sec, &tm);
1488 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001489 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001490 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001491 fflush(stderr);
1492 }
1493}
1494
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001495/* This function just ensure that the yield will be always
1496 * returned with a timeout and permit to set some flags
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02001497 * <timeout> is a tick value
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001498 */
Aurelien DARRAGONbcdf07e2023-07-13 10:18:04 +02001499__LJMP void hlua_yieldk(lua_State *L, int nresults, lua_KContext ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001500 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001501{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001502 struct hlua *hlua;
1503
1504 /* Get hlua struct, or NULL if we execute from main lua state */
1505 hlua = hlua_gethlua(L);
1506 if (!hlua) {
1507 return;
1508 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001509
1510 /* Set the wake timeout. If timeout is required, we set
1511 * the expiration time.
1512 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001513 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001514
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001515 hlua->flags |= flags;
1516
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001517 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001518 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001519}
1520
Willy Tarreau87b09662015-04-03 00:22:06 +02001521/* This function initialises the Lua environment stored in the stream.
1522 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001523 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001524 *
1525 * This function is particular. it initialises a new Lua thread. If the
1526 * initialisation fails (example: out of memory error), the lua function
1527 * throws an error (longjmp).
1528 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001529 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001530 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001531 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001532 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001533 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001534int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001535{
1536 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001537 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001538 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001539 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001540 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001541 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001542 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001543 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001544 if (!SET_SAFE_LJMP_PARENT(lua)) {
1545 lua->Tref = LUA_REFNIL;
1546 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001547 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001548 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001549 if (!lua->T) {
1550 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001551 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001552 return 0;
1553 }
1554 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001555 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001556 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001557 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001558 return 1;
1559}
1560
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001561/* kill all associated httpclient to this hlua task
1562 * We must take extra precautions as we're manipulating lua-exposed
1563 * objects without the main lua lock.
1564 */
William Lallemandbb581422022-10-20 10:57:28 +02001565static void hlua_httpclient_destroy_all(struct hlua *hlua)
1566{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001567 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001568
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001569 /* use thread-safe accessors for hc_list since GC cycle initiated by
1570 * another thread sharing the same main lua stack (lua coroutine)
1571 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1572 * in parallel: Lua GC applies on the main stack, it is not limited to
1573 * a single coroutine stack, see Github issue #2037 for reference.
1574 * Remember, coroutines created using lua_newthread() are not meant to
1575 * be thread safe in Lua. (From lua co-author:
1576 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1577 *
1578 * This security measure is superfluous when 'lua-load-per-thread' is used
1579 * since in this case coroutines exclusively run on the same thread
1580 * (main stack is not shared between OS threads).
1581 */
1582 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1583 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001584 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001585 }
1586}
1587
1588
Willy Tarreau87b09662015-04-03 00:22:06 +02001589/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001590 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001591 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001592 */
1593void hlua_ctx_destroy(struct hlua *lua)
1594{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001595 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001596 return;
1597
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001598 if (!lua->T)
1599 goto end;
1600
William Lallemandbb581422022-10-20 10:57:28 +02001601 /* clean all running httpclient */
1602 hlua_httpclient_destroy_all(lua);
1603
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001604 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001605 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001606
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001607 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001608 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001609 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001610 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001611
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001612 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001613 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001614 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001615 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001616 /* Forces a garbage collecting process. If the Lua program is finished
1617 * without error, we run the GC on the thread pointer. Its freed all
1618 * the unused memory.
1619 * If the thread is finnish with an error or is currently yielded,
1620 * it seems that the GC applied on the thread doesn't clean anything,
1621 * so e run the GC on the main thread.
1622 * NOTE: maybe this action locks all the Lua threads untiml the en of
1623 * the garbage collection.
1624 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001625 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001626 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001627 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001628 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001629 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001630 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001631
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001632 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001633
1634end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001635 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001636}
1637
1638/* This function is used to restore the Lua context when a coroutine
1639 * fails. This function copy the common memory between old coroutine
1640 * and the new coroutine. The old coroutine is destroyed, and its
1641 * replaced by the new coroutine.
1642 * If the flag "keep_msg" is set, the last entry of the old is assumed
1643 * as string error message and it is copied in the new stack.
1644 */
1645static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1646{
1647 lua_State *T;
1648 int new_ref;
1649
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001650 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001651 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001652 if (!T)
1653 return 0;
1654
1655 /* Copy last error message. */
1656 if (keep_msg)
1657 lua_xmove(lua->T, T, 1);
1658
1659 /* Copy data between the coroutines. */
1660 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1661 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001662 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001663
1664 /* Destroy old data. */
1665 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1666
1667 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001668 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001669
1670 /* Fill the struct with the new coroutine values. */
1671 lua->Mref = new_ref;
1672 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001673 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001674
1675 /* Set context. */
1676 hlua_sethlua(lua);
1677
1678 return 1;
1679}
1680
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001681void hlua_hook(lua_State *L, lua_Debug *ar)
1682{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001683 struct hlua *hlua;
1684
1685 /* Get hlua struct, or NULL if we execute from main lua state */
1686 hlua = hlua_gethlua(L);
1687 if (!hlua)
1688 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001689
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001690 if (hlua->T != L) {
1691 /* We don't want to enforce a yield on a sub coroutine, since
1692 * we have no guarantees that the yield will be handled properly.
1693 * Indeed, only the hlua->T coroutine is being handled through
1694 * hlua_ctx_resume() function.
1695 *
1696 * Instead, we simply check for timeouts and wait for the sub
1697 * coroutine to finish..
1698 */
1699 goto check_timeout;
1700 }
1701
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001702 /* Lua cannot yield when its returning from a function,
1703 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001704 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001705 */
1706 if (lua_gethookmask(L) & LUA_MASKRET) {
1707 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1708 return;
1709 }
1710
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001711 /* If we interrupt the Lua processing in yieldable state, we yield.
1712 * If the state is not yieldable, trying yield causes an error.
1713 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001714 if (lua_isyieldable(L)) {
1715 /* note: for converters/fetches.. where yielding is not allowed
1716 * hlua_ctx_resume() will simply perform a goto resume_execution
1717 * instead of rescheduling hlua->task.
1718 * also: hlua_ctx_resume() will take care of checking execution
1719 * timeout and re-applying the hook as needed.
1720 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001721 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001722 /* lua docs says that the hook should return immediately after lua_yieldk
1723 *
1724 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1725 *
1726 * Moreover, it seems that we don't want to continue after the yield
1727 * because the end of the function is about handling unyieldable function,
1728 * which is not the case here.
1729 *
1730 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1731 * in the function.
1732 */
1733 return;
1734 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001735
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001736 check_timeout:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001737 /* If we cannot yield, check the timeout. */
1738 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001739 lua_pushfstring(L, "execution timeout");
1740 WILL_LJMP(lua_error(L));
1741 }
1742
1743 /* Try to interrupt the process at the end of the current
1744 * unyieldable function.
1745 */
1746 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001747}
1748
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001749/* This function start or resumes the Lua stack execution. If the flag
1750 * "yield_allowed" if no set and the LUA stack execution returns a yield
1751 * The function return an error.
1752 *
1753 * The function can returns 4 values:
1754 * - HLUA_E_OK : The execution is terminated without any errors.
1755 * - HLUA_E_AGAIN : The execution must continue at the next associated
1756 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001757 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001758 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001759 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001760 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001761 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001762 * LUA code.
1763 */
1764static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1765{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001766#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1767 int nres;
1768#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001769 int ret;
1770 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001771 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001772
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001773 /* Lock the whole Lua execution. This lock must be before the
1774 * label "resume_execution".
1775 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001776 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001777
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001778 /* reset the timer as we might be re-entering the function to
1779 * resume the coroutine after a successful yield
1780 * (cumulative time will be updated)
1781 */
1782 hlua_timer_reset(&lua->timer);
1783
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001784resume_execution:
1785
1786 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1787 * instructions. it is used for preventing infinite loops.
1788 */
1789 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1790
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001791 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001792 HLUA_SET_RUN(lua);
1793 HLUA_CLR_CTRLYIELD(lua);
1794 HLUA_CLR_WAKERESWR(lua);
1795 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001796 HLUA_CLR_NOYIELD(lua);
1797 if (!yield_allowed)
1798 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001799
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001800 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001801 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001802
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001803 /* start the timer as we're about to start lua processing */
1804 hlua_timer_start(&lua->timer);
1805
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001806 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001807#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001808 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001809#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001810 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001811#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001812
1813 /* out of lua processing, stop the timer */
1814 hlua_timer_stop(&lua->timer);
1815
Aurelien DARRAGONfa76a102023-09-08 14:00:27 +02001816 /* reset nargs because those possibly passed to the lua_resume() call
1817 * were already consumed, and since we may call lua_resume() again
1818 * after a successful yield, we don't want to pass stale nargs hint
1819 * to the Lua API. As such, nargs should be set explicitly before each
1820 * lua_resume() (or hlua_ctx_resume()) invocation if needed.
1821 */
1822 lua->nargs = 0;
1823
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001824 switch (ret) {
1825
1826 case LUA_OK:
1827 ret = HLUA_E_OK;
1828 break;
1829
1830 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001831 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001832 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001833 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001834 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001835 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001836 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001837 break;
1838 }
1839 /* Process the forced yield. if the general yield is not allowed or
1840 * if no task were associated this the current Lua execution
1841 * coroutine, we resume the execution. Else we want to return in the
1842 * scheduler and we want to be waked up again, to continue the
1843 * current Lua execution. So we schedule our own task.
1844 */
1845 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001846 if (!yield_allowed || !lua->task)
1847 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001848 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001849 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001850 if (!yield_allowed) {
1851 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001852 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001853 break;
1854 }
1855 ret = HLUA_E_AGAIN;
1856 break;
1857
1858 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001859
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001860 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001861 * because the errors ares the only one mean to return immediately
1862 * from and lua execution.
1863 */
1864 if (lua->flags & HLUA_EXIT) {
1865 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001866 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001867 break;
1868 }
1869
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001870 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001871 if (!lua_checkstack(lua->T, 1)) {
1872 ret = HLUA_E_ERR;
1873 break;
1874 }
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01001875 msg = hlua_tostring_safe(lua->T, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001876 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001877 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001878 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001879 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001880 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +01001881
1882 /* Move the error msg at the top and then empty the stack except last msg */
1883 lua_insert(lua->T, -lua_gettop(lua->T));
1884 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001885 ret = HLUA_E_ERRMSG;
1886 break;
1887
1888 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001889 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001890 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001891 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001892 break;
1893
1894 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001895 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001896 if (!lua_checkstack(lua->T, 1)) {
1897 ret = HLUA_E_ERR;
1898 break;
1899 }
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01001900 msg = hlua_tostring_safe(lua->T, -1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001901 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001902 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001903 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001904 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +01001905
1906 /* Move the error msg at the top and then empty the stack except last msg */
1907 lua_insert(lua->T, -lua_gettop(lua->T));
1908 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001909 ret = HLUA_E_ERRMSG;
1910 break;
1911
1912 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001913 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001914 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001915 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001916 break;
1917 }
1918
1919 switch (ret) {
1920 case HLUA_E_AGAIN:
1921 break;
1922
1923 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001924 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001925 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001926 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001927 break;
1928
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001929 case HLUA_E_ETMOUT:
1930 case HLUA_E_NOMEM:
1931 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001932 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001933 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001934 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001935 hlua_ctx_renew(lua, 0);
1936 break;
1937
1938 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001939 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001940 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001941 break;
1942 }
1943
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001944 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001945 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001946
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001947 return ret;
1948}
1949
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001950/* This function exit the current code. */
1951__LJMP static int hlua_done(lua_State *L)
1952{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001953 struct hlua *hlua;
1954
1955 /* Get hlua struct, or NULL if we execute from main lua state */
1956 hlua = hlua_gethlua(L);
1957 if (!hlua)
1958 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001959
1960 hlua->flags |= HLUA_EXIT;
1961 WILL_LJMP(lua_error(L));
1962
1963 return 0;
1964}
1965
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001966/* This function is an LUA binding. It provides a function
1967 * for deleting ACL from a referenced ACL file.
1968 */
1969__LJMP static int hlua_del_acl(lua_State *L)
1970{
1971 const char *name;
1972 const char *key;
1973 struct pat_ref *ref;
1974
1975 MAY_LJMP(check_args(L, 2, "del_acl"));
1976
1977 name = MAY_LJMP(luaL_checkstring(L, 1));
1978 key = MAY_LJMP(luaL_checkstring(L, 2));
1979
1980 ref = pat_ref_lookup(name);
1981 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001982 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001983
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001984 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001985 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001986 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001987 return 0;
1988}
1989
1990/* This function is an LUA binding. It provides a function
1991 * for deleting map entry from a referenced map file.
1992 */
1993static int hlua_del_map(lua_State *L)
1994{
1995 const char *name;
1996 const char *key;
1997 struct pat_ref *ref;
1998
1999 MAY_LJMP(check_args(L, 2, "del_map"));
2000
2001 name = MAY_LJMP(luaL_checkstring(L, 1));
2002 key = MAY_LJMP(luaL_checkstring(L, 2));
2003
2004 ref = pat_ref_lookup(name);
2005 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02002006 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002007
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002008 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002009 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002010 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002011 return 0;
2012}
2013
2014/* This function is an LUA binding. It provides a function
2015 * for adding ACL pattern from a referenced ACL file.
2016 */
2017static int hlua_add_acl(lua_State *L)
2018{
2019 const char *name;
2020 const char *key;
2021 struct pat_ref *ref;
2022
2023 MAY_LJMP(check_args(L, 2, "add_acl"));
2024
2025 name = MAY_LJMP(luaL_checkstring(L, 1));
2026 key = MAY_LJMP(luaL_checkstring(L, 2));
2027
2028 ref = pat_ref_lookup(name);
2029 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02002030 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002031
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002032 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002033 if (pat_ref_find_elt(ref, key) == NULL)
2034 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002035 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002036 return 0;
2037}
2038
2039/* This function is an LUA binding. It provides a function
2040 * for setting map pattern and sample from a referenced map
2041 * file.
2042 */
2043static int hlua_set_map(lua_State *L)
2044{
2045 const char *name;
2046 const char *key;
2047 const char *value;
2048 struct pat_ref *ref;
2049
2050 MAY_LJMP(check_args(L, 3, "set_map"));
2051
2052 name = MAY_LJMP(luaL_checkstring(L, 1));
2053 key = MAY_LJMP(luaL_checkstring(L, 2));
2054 value = MAY_LJMP(luaL_checkstring(L, 3));
2055
2056 ref = pat_ref_lookup(name);
2057 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02002058 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002059
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002060 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002061 if (pat_ref_find_elt(ref, key) != NULL)
2062 pat_ref_set(ref, key, value, NULL);
2063 else
2064 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02002065 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01002066 return 0;
2067}
2068
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +02002069/* This function disables the sending of email through the
2070 * legacy email sending function which is implemented using
2071 * checks.
2072 *
2073 * It may not be used during runtime.
2074 */
2075__LJMP static int hlua_disable_legacy_mailers(lua_State *L)
2076{
2077 if (hlua_gethlua(L))
2078 WILL_LJMP(luaL_error(L, "disable_legacy_mailers: "
2079 "not available outside of init or body context"));
2080 send_email_disabled = 1;
2081 return 0;
2082}
2083
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002084/* A class is a lot of memory that contain data. This data can be a table,
2085 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002086 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002087 * the name of the object (_G[<name>] = <metable> ).
2088 *
2089 * A metable is a table that modify the standard behavior of a standard
2090 * access to the associated data. The entries of this new metatable are
2091 * defined as is:
2092 *
2093 * http://lua-users.org/wiki/MetatableEvents
2094 *
2095 * __index
2096 *
2097 * we access an absent field in a table, the result is nil. This is
2098 * true, but it is not the whole truth. Actually, such access triggers
2099 * the interpreter to look for an __index metamethod: If there is no
2100 * such method, as usually happens, then the access results in nil;
2101 * otherwise, the metamethod will provide the result.
2102 *
2103 * Control 'prototype' inheritance. When accessing "myTable[key]" and
2104 * the key does not appear in the table, but the metatable has an __index
2105 * property:
2106 *
2107 * - if the value is a function, the function is called, passing in the
2108 * table and the key; the return value of that function is returned as
2109 * the result.
2110 *
2111 * - if the value is another table, the value of the key in that table is
2112 * asked for and returned (and if it doesn't exist in that table, but that
2113 * table's metatable has an __index property, then it continues on up)
2114 *
2115 * - Use "rawget(myTable,key)" to skip this metamethod.
2116 *
2117 * http://www.lua.org/pil/13.4.1.html
2118 *
2119 * __newindex
2120 *
2121 * Like __index, but control property assignment.
2122 *
2123 * __mode - Control weak references. A string value with one or both
2124 * of the characters 'k' and 'v' which specifies that the the
2125 * keys and/or values in the table are weak references.
2126 *
2127 * __call - Treat a table like a function. When a table is followed by
2128 * parenthesis such as "myTable( 'foo' )" and the metatable has
2129 * a __call key pointing to a function, that function is invoked
2130 * (passing any specified arguments) and the return value is
2131 * returned.
2132 *
2133 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
2134 * called, if the metatable for myTable has a __metatable
2135 * key, the value of that key is returned instead of the
2136 * actual metatable.
2137 *
2138 * __tostring - Control string representation. When the builtin
2139 * "tostring( myTable )" function is called, if the metatable
2140 * for myTable has a __tostring property set to a function,
2141 * that function is invoked (passing myTable to it) and the
2142 * return value is used as the string representation.
2143 *
2144 * __len - Control table length. When the table length is requested using
2145 * the length operator ( '#' ), if the metatable for myTable has
2146 * a __len key pointing to a function, that function is invoked
2147 * (passing myTable to it) and the return value used as the value
2148 * of "#myTable".
2149 *
2150 * __gc - Userdata finalizer code. When userdata is set to be garbage
2151 * collected, if the metatable has a __gc field pointing to a
2152 * function, that function is first invoked, passing the userdata
2153 * to it. The __gc metamethod is not called for tables.
2154 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
2155 *
2156 * Special metamethods for redefining standard operators:
2157 * http://www.lua.org/pil/13.1.html
2158 *
2159 * __add "+"
2160 * __sub "-"
2161 * __mul "*"
2162 * __div "/"
2163 * __unm "!"
2164 * __pow "^"
2165 * __concat ".."
2166 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002167 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002168 * http://www.lua.org/pil/13.2.html
2169 *
2170 * __eq "=="
2171 * __lt "<"
2172 * __le "<="
2173 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
2175/*
2176 *
2177 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002178 * Class Map
2179 *
2180 *
2181 */
2182
2183/* Returns a struct hlua_map if the stack entry "ud" is
2184 * a class session, otherwise it throws an error.
2185 */
2186__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2187{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002188 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002189}
2190
2191/* This function is the map constructor. It don't need
2192 * the class Map object. It creates and return a new Map
2193 * object. It must be called only during "body" or "init"
2194 * context because it process some filesystem accesses.
2195 */
2196__LJMP static int hlua_map_new(struct lua_State *L)
2197{
2198 const char *fn;
2199 int match = PAT_MATCH_STR;
2200 struct sample_conv conv;
2201 const char *file = "";
2202 int line = 0;
2203 lua_Debug ar;
2204 char *err = NULL;
2205 struct arg args[2];
2206
2207 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2208 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2209
2210 fn = MAY_LJMP(luaL_checkstring(L, 1));
2211
2212 if (lua_gettop(L) >= 2) {
2213 match = MAY_LJMP(luaL_checkinteger(L, 2));
2214 if (match < 0 || match >= PAT_MATCH_NUM)
2215 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2216 }
2217
2218 /* Get Lua filename and line number. */
2219 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2220 lua_getinfo(L, "Sl", &ar); /* get info about it */
2221 if (ar.currentline > 0) { /* is there info? */
2222 file = ar.short_src;
2223 line = ar.currentline;
2224 }
2225 }
2226
2227 /* fill fake sample_conv struct. */
2228 conv.kw = ""; /* unused. */
2229 conv.process = NULL; /* unused. */
2230 conv.arg_mask = 0; /* unused. */
2231 conv.val_args = NULL; /* unused. */
2232 conv.out_type = SMP_T_STR;
2233 conv.private = (void *)(long)match;
2234 switch (match) {
2235 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2236 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2237 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2238 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2239 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2240 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2241 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002242 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002243 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2244 default:
2245 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2246 }
2247
2248 /* fill fake args. */
2249 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002250 args[0].data.str.area = strdup(fn);
2251 args[0].data.str.data = strlen(fn);
2252 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002253 args[1].type = ARGT_STOP;
2254
2255 /* load the map. */
2256 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002257 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002258 * free the err variable.
2259 */
2260 luaL_where(L, 1);
2261 lua_pushfstring(L, "'new': %s.", err);
2262 lua_concat(L, 2);
2263 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002264 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002265 WILL_LJMP(lua_error(L));
2266 }
2267
2268 /* create the lua object. */
2269 lua_newtable(L);
2270 lua_pushlightuserdata(L, args[0].data.map);
2271 lua_rawseti(L, -2, 0);
2272
2273 /* Pop a class Map metatable and affect it to the userdata. */
2274 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2275 lua_setmetatable(L, -2);
2276
2277
2278 return 1;
2279}
2280
2281__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2282{
2283 struct map_descriptor *desc;
2284 struct pattern *pat;
2285 struct sample smp;
2286
2287 MAY_LJMP(check_args(L, 2, "lookup"));
2288 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002289 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002290 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002291 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002292 }
2293 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002294 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002295 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002296 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 +01002297 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002298 }
2299
2300 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002301 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002302 if (str)
2303 lua_pushstring(L, "");
2304 else
2305 lua_pushnil(L);
2306 return 1;
2307 }
2308
2309 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002310 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002311 return 1;
2312}
2313
2314__LJMP static int hlua_map_lookup(struct lua_State *L)
2315{
2316 return _hlua_map_lookup(L, 0);
2317}
2318
2319__LJMP static int hlua_map_slookup(struct lua_State *L)
2320{
2321 return _hlua_map_lookup(L, 1);
2322}
2323
2324/*
2325 *
2326 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327 * Class Socket
2328 *
2329 *
2330 */
2331
2332__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2333{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002334 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335}
2336
2337/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002338 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339 * received.
2340 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002341static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342{
Willy Tarreau5321da92022-05-06 11:57:34 +02002343 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002344 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345
Christopher Faulet31572222023-03-31 11:13:48 +02002346 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 +02002347 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Christopher Faulet31572222023-03-31 11:13:48 +02002348 notification_wake(&ctx->wake_on_read);
2349 notification_wake(&ctx->wake_on_write);
2350 return;
2351 }
2352
Willy Tarreau5321da92022-05-06 11:57:34 +02002353 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002354 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002355 notification_wake(&ctx->wake_on_read);
2356 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002357 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002358 }
2359
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002360 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002361 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002362 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002363
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002364 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002365 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002366 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002367
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002368 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002369 * to be notified whenever the connection completes.
2370 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002371 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002372 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002373 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002374 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002375 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002376 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377
2378 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002379 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002381 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002382 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002383 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384
2385 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet0dbc16b2024-02-16 15:33:44 +01002386 if (!channel_is_empty(sc_oc(sc))) {
Willy Tarreau5321da92022-05-06 11:57:34 +02002387 notification_wake(&ctx->wake_on_read);
Christopher Faulet0dbc16b2024-02-16 15:33:44 +01002388 applet_wont_consume(appctx);
2389 }
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002390
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002391 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002392 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002393 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002394 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002395 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396}
2397
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002398static int hlua_socket_init(struct appctx *appctx)
2399{
Christopher Fauletcb068552023-09-27 17:34:24 +02002400 struct hlua_csk_ctx *csk_ctx = appctx->svcctx;
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002401 struct stream *s;
2402
2403 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2404 goto error;
2405
2406 s = appctx_strm(appctx);
2407
Willy Tarreau4596fe22022-05-17 19:07:51 +02002408 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002409 * and retrieve data from the server. The connection is initialized
2410 * with the "struct server".
2411 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002412 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002413
2414 /* Force destination server. */
2415 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Christopher Faulet9a278fd2023-09-27 17:47:45 +02002416 s->target = &csk_ctx->srv->obj_type;
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002417
Christopher Fauletcb068552023-09-27 17:34:24 +02002418 if (csk_ctx->timeout) {
2419 s->sess->fe->timeout.connect = csk_ctx->timeout;
2420 s->scf->ioto = csk_ctx->timeout;
2421 s->scb->ioto = csk_ctx->timeout;
2422 }
2423
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002424 return 0;
2425
2426 error:
2427 return -1;
2428}
2429
Willy Tarreau87b09662015-04-03 00:22:06 +02002430/* This function is called when the "struct stream" is destroyed.
2431 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002432 * Wake all the pending signals.
2433 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002434static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435{
Willy Tarreau5321da92022-05-06 11:57:34 +02002436 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002437 struct xref *peer;
2438
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002439 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002440 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002441 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002442 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443
2444 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002445 notification_wake(&ctx->wake_on_read);
2446 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447}
2448
2449/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002450 * uses this object. If the stream does not exists, just quit.
2451 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002452 * pending signal can rest in the read and write lists. destroy
2453 * it.
2454 */
2455__LJMP static int hlua_socket_gc(lua_State *L)
2456{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002457 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002458 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002459 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002460
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002461 MAY_LJMP(check_args(L, 1, "__gc"));
2462
2463 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002464 peer = xref_get_peer_and_lock(&socket->xref);
2465 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002466 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002467
2468 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002469
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002470 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002471 xref_disconnect(&socket->xref, peer);
Christopher Faulet5b62e092024-02-16 15:00:54 +01002472
2473 if (se_fl_test(ctx->appctx->sedesc, SE_FL_ORPHAN)) {
2474 /* The applet was never initialized, just release it */
2475 appctx_free(ctx->appctx);
2476 }
2477 else {
2478 /* Otherwise, notify it that is must die and wake it up */
2479 ctx->die = 1;
2480 appctx_wakeup(ctx->appctx);
2481 }
2482
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002483 return 0;
2484}
2485
2486/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002487 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002488 */
sada05ed3302018-05-11 11:48:18 -07002489__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002490{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002491 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002492 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002493 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002494 struct hlua *hlua;
2495
2496 /* Get hlua struct, or NULL if we execute from main lua state */
2497 hlua = hlua_gethlua(L);
2498 if (!hlua)
2499 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002501 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002502
2503 /* Check if we run on the same thread than the xreator thread.
2504 * We cannot access to the socket if the thread is different.
2505 */
2506 if (socket->tid != tid)
2507 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2508
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002509 peer = xref_get_peer_and_lock(&socket->xref);
2510 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002511 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002512
2513 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002514 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002516 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002517 ctx->die = 1;
2518 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002520 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002521 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522 return 0;
2523}
2524
sada05ed3302018-05-11 11:48:18 -07002525/* The close function calls close_helper.
2526 */
2527__LJMP static int hlua_socket_close(lua_State *L)
2528{
2529 MAY_LJMP(check_args(L, 1, "close"));
2530 return hlua_socket_close_helper(L);
2531}
2532
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002533/* This Lua function assumes that the stack contain three parameters.
2534 * 1 - USERDATA containing a struct socket
2535 * 2 - INTEGER with values of the macro defined below
2536 * If the integer is -1, we must read at most one line.
2537 * If the integer is -2, we ust read all the data until the
2538 * end of the stream.
2539 * If the integer is positive value, we must read a number of
2540 * bytes corresponding to this value.
2541 */
2542#define HLSR_READ_LINE (-1)
2543#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002544__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002545{
2546 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2547 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002548 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002549 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002551 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002552 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002553 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002554 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002555 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002556 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002557 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002558 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002559 struct stream *s;
2560 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002561 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002562
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002563 /* Get hlua struct, or NULL if we execute from main lua state */
2564 hlua = hlua_gethlua(L);
2565
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002566 /* Check if this lua stack is schedulable. */
2567 if (!hlua || !hlua->task)
2568 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2569 "'frontend', 'backend' or 'task'"));
2570
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002571 /* Check if we run on the same thread than the xreator thread.
2572 * We cannot access to the socket if the thread is different.
2573 */
2574 if (socket->tid != tid)
2575 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2576
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002577 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002578 peer = xref_get_peer_and_lock(&socket->xref);
2579 if (!peer)
2580 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002581
2582 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
Christopher Faulet714476c2023-09-27 17:22:41 +02002583 if (!csk_ctx->connected)
2584 goto connection_closed;
2585
Willy Tarreau5321da92022-05-06 11:57:34 +02002586 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002587 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002588
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002589 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002590 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002591 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002592 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593 if (nblk < 0) /* Connection close. */
2594 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002595 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002597
2598 /* remove final \r\n. */
2599 if (nblk == 1) {
2600 if (blk1[len1-1] == '\n') {
2601 len1--;
2602 skip_at_end++;
2603 if (blk1[len1-1] == '\r') {
2604 len1--;
2605 skip_at_end++;
2606 }
2607 }
2608 }
2609 else {
2610 if (blk2[len2-1] == '\n') {
2611 len2--;
2612 skip_at_end++;
2613 if (blk2[len2-1] == '\r') {
2614 len2--;
2615 skip_at_end++;
2616 }
2617 }
2618 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619 }
2620
2621 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002622 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002623 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002624 if (nblk < 0) /* Connection close. */
2625 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002626 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002627 goto connection_empty;
2628 }
2629
2630 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002631 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002632 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633 if (nblk < 0) /* Connection close. */
2634 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002635 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002636 goto connection_empty;
2637
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002638 missing_bytes = wanted - socket->b.n;
2639 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002640 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002641 len1 = missing_bytes;
2642 } if (nblk == 2 && len1 + len2 > missing_bytes)
2643 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644 }
2645
2646 len = len1;
2647
2648 luaL_addlstring(&socket->b, blk1, len1);
2649 if (nblk == 2) {
2650 len += len2;
2651 luaL_addlstring(&socket->b, blk2, len2);
2652 }
2653
2654 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002655 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656
2657 /* Don't wait anything. */
Christopher Faulet0dbc16b2024-02-16 15:33:44 +01002658 applet_will_consume(appctx);
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002659 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002660
2661 /* If the pattern reclaim to read all the data
2662 * in the connection, got out.
2663 */
2664 if (wanted == HLSR_READ_ALL)
2665 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002666 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 goto connection_empty;
2668
2669 /* Return result. */
2670 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002671 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002672 return 1;
2673
2674connection_closed:
2675
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002676 xref_unlock(&socket->xref, peer);
2677
2678no_peer:
2679
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680 /* If the buffer containds data. */
2681 if (socket->b.n > 0) {
2682 luaL_pushresult(&socket->b);
2683 return 1;
2684 }
2685 lua_pushnil(L);
2686 lua_pushstring(L, "connection closed.");
2687 return 2;
2688
2689connection_empty:
2690
Willy Tarreau5321da92022-05-06 11:57:34 +02002691 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002692 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002693 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002694 }
2695 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002696 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002697 return 0;
2698}
2699
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002700/* This Lua function gets two parameters. The first one can be string
2701 * or a number. If the string is "*l", the user requires one line. If
2702 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002703 * If the value is a number, the user require a number of bytes equal
2704 * to the value. The default value is "*l" (a line).
2705 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002706 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002707 * integer takes this values:
2708 * -1 : read a line
2709 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002710 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002712 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713 * concatenated with the read data.
2714 */
2715__LJMP static int hlua_socket_receive(struct lua_State *L)
2716{
2717 int wanted = HLSR_READ_LINE;
2718 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002719 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002720 char *error;
2721 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002722 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723
2724 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2725 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2726
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002727 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002728
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002729 /* Check if we run on the same thread than the xreator thread.
2730 * We cannot access to the socket if the thread is different.
2731 */
2732 if (socket->tid != tid)
2733 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2734
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002735 /* check for pattern. */
2736 if (lua_gettop(L) >= 2) {
2737 type = lua_type(L, 2);
2738 if (type == LUA_TSTRING) {
2739 pattern = lua_tostring(L, 2);
2740 if (strcmp(pattern, "*a") == 0)
2741 wanted = HLSR_READ_ALL;
2742 else if (strcmp(pattern, "*l") == 0)
2743 wanted = HLSR_READ_LINE;
2744 else {
2745 wanted = strtoll(pattern, &error, 10);
2746 if (*error != '\0')
2747 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2748 }
2749 }
2750 else if (type == LUA_TNUMBER) {
2751 wanted = lua_tointeger(L, 2);
2752 if (wanted < 0)
2753 WILL_LJMP(luaL_error(L, "Unsupported size."));
2754 }
2755 }
2756
2757 /* Set pattern. */
2758 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002759
2760 /* Check if we would replace the top by itself. */
2761 if (lua_gettop(L) != 2)
2762 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002763
Christopher Fauletc31b2002021-05-03 10:11:13 +02002764 /* Save index of the top of the stack because since buffers are used, it
2765 * may change
2766 */
2767 lastarg = lua_gettop(L);
2768
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002769 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002770 luaL_buffinit(L, &socket->b);
2771
2772 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002773 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002774 if (lua_type(L, 3) != LUA_TSTRING)
2775 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2776 pattern = lua_tolstring(L, 3, &len);
2777 luaL_addlstring(&socket->b, pattern, len);
2778 }
2779
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002780 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002781}
2782
2783/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002784 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002785 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002786static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002787{
2788 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002789 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002790 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002791 struct appctx *appctx;
2792 size_t buf_len;
2793 const char *buf;
2794 int len;
2795 int send_len;
2796 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002797 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002798 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002799 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002800
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002801 /* Get hlua struct, or NULL if we execute from main lua state */
2802 hlua = hlua_gethlua(L);
2803
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002804 /* Check if this lua stack is schedulable. */
2805 if (!hlua || !hlua->task)
2806 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2807 "'frontend', 'backend' or 'task'"));
2808
2809 /* Get object */
2810 socket = MAY_LJMP(hlua_checksocket(L, 1));
2811 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002812 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002814 /* Check if we run on the same thread than the xreator thread.
2815 * We cannot access to the socket if the thread is different.
2816 */
2817 if (socket->tid != tid)
2818 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2819
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002820 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002821 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002822 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002823 lua_pushinteger(L, -1);
2824 return 1;
2825 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002826
2827 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
Christopher Faulet714476c2023-09-27 17:22:41 +02002828 if (!csk_ctx->connected) {
2829 xref_unlock(&socket->xref, peer);
2830 lua_pushinteger(L, -1);
2831 return 1;
2832 }
2833
Willy Tarreau5321da92022-05-06 11:57:34 +02002834 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002835 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002836 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002837
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002838 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002839 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002840 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002841 lua_pushinteger(L, -1);
2842 return 1;
2843 }
2844
2845 /* Update the input buffer data. */
2846 buf += sent;
2847 send_len = buf_len - sent;
2848
2849 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002850 if (sent >= buf_len) {
2851 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002852 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002853 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002854
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002855 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002856 * the request buffer if its not required.
2857 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002858 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002859 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002860 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002861 }
2862
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002863 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002864 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002865 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002866 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002867 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002868
2869 /* send data */
2870 if (len < send_len)
2871 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002872 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002873
2874 /* "Not enough space" (-1), "Buffer too little to contain
2875 * the data" (-2) are not expected because the available length
2876 * is tested.
2877 * Other unknown error are also not expected.
2878 */
2879 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002880 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002881 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002882
sada05ed3302018-05-11 11:48:18 -07002883 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002884 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002885 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002886 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002887 return 1;
2888 }
2889
2890 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002891 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002892
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002893 /* Update length sent. */
2894 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002895 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002896
2897 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002898 if (sent + len >= buf_len) {
2899 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002900 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002901 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002902
2903hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002904 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002905 xref_unlock(&socket->xref, peer);
2906 WILL_LJMP(luaL_error(L, "out of memory"));
2907 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002908 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002909 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910 return 0;
2911}
2912
2913/* This function initiate the send of data. It just check the input
2914 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002915 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002916 * "hlua_socket_write_yield" that can yield.
2917 *
2918 * The Lua function gets between 3 and 4 parameters. The first one is
2919 * the associated object. The second is a string buffer. The third is
2920 * a facultative integer that represents where is the buffer position
2921 * of the start of the data that can send. The first byte is the
2922 * position "1". The default value is "1". The fourth argument is a
2923 * facultative integer that represents where is the buffer position
2924 * of the end of the data that can send. The default is the last byte.
2925 */
2926static int hlua_socket_send(struct lua_State *L)
2927{
2928 int i;
2929 int j;
2930 const char *buf;
2931 size_t buf_len;
2932
2933 /* Check number of arguments. */
2934 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2935 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2936
2937 /* Get the string. */
2938 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2939
2940 /* Get and check j. */
2941 if (lua_gettop(L) == 4) {
2942 j = MAY_LJMP(luaL_checkinteger(L, 4));
2943 if (j < 0)
2944 j = buf_len + j + 1;
2945 if (j > buf_len)
2946 j = buf_len + 1;
2947 lua_pop(L, 1);
2948 }
2949 else
2950 j = buf_len;
2951
2952 /* Get and check i. */
2953 if (lua_gettop(L) == 3) {
2954 i = MAY_LJMP(luaL_checkinteger(L, 3));
2955 if (i < 0)
2956 i = buf_len + i + 1;
2957 if (i > buf_len)
2958 i = buf_len + 1;
2959 lua_pop(L, 1);
2960 } else
2961 i = 1;
2962
2963 /* Check bth i and j. */
2964 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002965 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002966 return 1;
2967 }
2968 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002969 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970 return 1;
2971 }
2972 if (i == 0)
2973 i = 1;
2974 if (j == 0)
2975 j = 1;
2976
2977 /* Pop the string. */
2978 lua_pop(L, 1);
2979
2980 /* Update the buffer length. */
2981 buf += i - 1;
2982 buf_len = j - i + 1;
2983 lua_pushlstring(L, buf, buf_len);
2984
2985 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002986 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002987
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002988 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002989}
2990
Willy Tarreau22b0a682015-06-17 19:43:49 +02002991#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002992__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002993{
2994 static char buffer[SOCKET_INFO_MAX_LEN];
2995 int ret;
2996 int len;
2997 char *p;
2998
2999 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
3000 if (ret <= 0) {
3001 lua_pushnil(L);
3002 return 1;
3003 }
3004
3005 if (ret == AF_UNIX) {
3006 lua_pushstring(L, buffer+1);
3007 return 1;
3008 }
3009 else if (ret == AF_INET6) {
3010 buffer[0] = '[';
3011 len = strlen(buffer);
3012 buffer[len] = ']';
3013 len++;
3014 buffer[len] = ':';
3015 len++;
3016 p = buffer;
3017 }
3018 else if (ret == AF_INET) {
3019 p = buffer + 1;
3020 len = strlen(p);
3021 p[len] = ':';
3022 len++;
3023 }
3024 else {
3025 lua_pushnil(L);
3026 return 1;
3027 }
3028
3029 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
3030 lua_pushnil(L);
3031 return 1;
3032 }
3033
3034 lua_pushstring(L, p);
3035 return 1;
3036}
3037
3038/* Returns information about the peer of the connection. */
3039__LJMP static int hlua_socket_getpeername(struct lua_State *L)
3040{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003041 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003042 struct xref *peer;
Christopher Faulet714476c2023-09-27 17:22:41 +02003043 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003044 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003045 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02003046 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003047 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003048
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003049 MAY_LJMP(check_args(L, 1, "getpeername"));
3050
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003051 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003052
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003053 /* Check if we run on the same thread than the xreator thread.
3054 * We cannot access to the socket if the thread is different.
3055 */
3056 if (socket->tid != tid)
3057 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3058
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003059 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003060 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003061 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003062 lua_pushnil(L);
3063 return 1;
3064 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003065
Christopher Faulet714476c2023-09-27 17:22:41 +02003066 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3067 if (!csk_ctx->connected) {
3068 xref_unlock(&socket->xref, peer);
3069 lua_pushnil(L);
3070 return 1;
3071 }
3072
3073 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003074 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003075 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02003076 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003077 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01003078 lua_pushnil(L);
3079 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003080 }
3081
Christopher Faulet16f16af2021-10-27 09:34:56 +02003082 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003083 xref_unlock(&socket->xref, peer);
3084 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003085}
3086
3087/* Returns information about my connection side. */
3088static int hlua_socket_getsockname(struct lua_State *L)
3089{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003090 struct hlua_socket *socket;
3091 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003092 struct appctx *appctx;
3093 struct xref *peer;
Christopher Faulet714476c2023-09-27 17:22:41 +02003094 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003095 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003096 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003097
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003098 MAY_LJMP(check_args(L, 1, "getsockname"));
3099
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003100 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003101
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003102 /* Check if we run on the same thread than the xreator thread.
3103 * We cannot access to the socket if the thread is different.
3104 */
3105 if (socket->tid != tid)
3106 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3107
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003108 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003109 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003110 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003111 lua_pushnil(L);
3112 return 1;
3113 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003114
Christopher Faulet714476c2023-09-27 17:22:41 +02003115 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3116 if (!csk_ctx->connected) {
3117 xref_unlock(&socket->xref, peer);
3118 lua_pushnil(L);
3119 return 1;
3120 }
3121
3122 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003123 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003124
Willy Tarreaufd9417b2022-05-18 16:23:22 +02003125 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02003126 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003127 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003128 lua_pushnil(L);
3129 return 1;
3130 }
3131
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003132 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003133 xref_unlock(&socket->xref, peer);
3134 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003135}
3136
3137/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02003138static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003139 .obj_type = OBJ_TYPE_APPLET,
3140 .name = "<LUA_TCP>",
3141 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003142 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003143 .release = hlua_socket_release,
3144};
3145
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003146__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003147{
3148 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003149 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003150 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02003151 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003152 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003153 struct stream *s;
3154
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003155 /* Get hlua struct, or NULL if we execute from main lua state */
3156 hlua = hlua_gethlua(L);
3157 if (!hlua)
3158 return 0;
3159
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003160 /* Check if we run on the same thread than the xreator thread.
3161 * We cannot access to the socket if the thread is different.
3162 */
3163 if (socket->tid != tid)
3164 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3165
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003166 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003167 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003168 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003169 lua_pushnil(L);
3170 lua_pushstring(L, "Can't connect");
3171 return 2;
3172 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003173
3174 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3175 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003176 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003177
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003178 /* Check if we run on the same thread than the xreator thread.
3179 * We cannot access to the socket if the thread is different.
3180 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003181 if (socket->tid != tid) {
3182 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003183 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003184 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003185
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003186 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003187 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003188 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003189 lua_pushnil(L);
3190 lua_pushstring(L, "Can't connect");
3191 return 2;
3192 }
3193
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02003194 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003195
3196 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003197 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003198 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003199 lua_pushinteger(L, 1);
3200 return 1;
3201 }
3202
Willy Tarreau5321da92022-05-06 11:57:34 +02003203 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003204 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003205 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003206 }
3207 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003208 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003209 return 0;
3210}
3211
3212/* This function fail or initite the connection. */
3213__LJMP static int hlua_socket_connect(struct lua_State *L)
3214{
3215 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003216 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003217 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003218 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003219 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003220 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003221 int low, high;
3222 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003223 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003224 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003225
Christopher Faulet6db178d2023-09-27 17:42:38 +02003226 /* Get hlua struct, or NULL if we execute from main lua state */
3227 hlua = hlua_gethlua(L);
3228 if (!hlua)
3229 return 0;
3230
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003231 if (lua_gettop(L) < 2)
3232 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003233
3234 /* Get args. */
3235 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003236
3237 /* Check if we run on the same thread than the xreator thread.
3238 * We cannot access to the socket if the thread is different.
3239 */
3240 if (socket->tid != tid)
3241 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3242
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003243 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003244 if (lua_gettop(L) >= 3) {
3245 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003246 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003247
Tim Duesterhus6edab862018-01-06 19:04:45 +01003248 /* Force the ip to end with a colon, to support IPv6 addresses
3249 * that are not enclosed within square brackets.
3250 */
3251 if (port > 0) {
3252 luaL_buffinit(L, &b);
3253 luaL_addstring(&b, ip);
3254 luaL_addchar(&b, ':');
3255 luaL_pushresult(&b);
3256 ip = lua_tolstring(L, lua_gettop(L), NULL);
3257 }
3258 }
3259
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003260 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003261 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003262 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003263 lua_pushnil(L);
3264 return 1;
3265 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003266
Christopher Faulet26786572023-09-27 17:39:44 +02003267 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3268 if (!csk_ctx->srv)
3269 csk_ctx->srv = socket_tcp;
3270
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003271 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003272 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 +02003273 if (!addr) {
3274 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003275 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003276 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003277
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003278 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003279 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003280 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003281 if (port == -1) {
3282 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003283 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003284 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003285 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3286 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003287 if (port == -1) {
3288 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003289 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003290 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003291 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003292 }
3293 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003294
Willy Tarreau5321da92022-05-06 11:57:34 +02003295 appctx = csk_ctx->appctx;
Christopher Faulet9a278fd2023-09-27 17:47:45 +02003296 if (appctx_sc(appctx)) {
3297 xref_unlock(&socket->xref, peer);
3298 WILL_LJMP(luaL_error(L, "connect: connect already performed\n"));
3299 }
3300
3301 if (appctx_init(appctx) == -1) {
3302 xref_unlock(&socket->xref, peer);
3303 WILL_LJMP(luaL_error(L, "connect: fail to init applet."));
3304 }
3305
Willy Tarreauc12b3212022-05-27 11:08:15 +02003306 sc = appctx_sc(appctx);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003307
Willy Tarreau3e7be362022-05-27 10:35:27 +02003308 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003309 xref_unlock(&socket->xref, peer);
3310 WILL_LJMP(luaL_error(L, "connect: internal error"));
3311 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003312
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003313 /* inform the stream that we want to be notified whenever the
3314 * connection completes.
3315 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003316 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003317 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003318 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003319
Willy Tarreau5321da92022-05-06 11:57:34 +02003320 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003321 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003322 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003323 }
3324 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003325
PiBa-NL706d5ee2018-05-05 23:51:42 +02003326 /* Return yield waiting for connection. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003327 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003328
3329 return 0;
3330}
3331
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003332#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003333__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3334{
3335 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003336 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003337
3338 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3339 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003340
3341 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003342 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003343 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003344 lua_pushnil(L);
3345 return 1;
3346 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003347
Christopher Faulet26786572023-09-27 17:39:44 +02003348 container_of(peer, struct hlua_csk_ctx, xref)->srv = socket_ssl;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003349
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003350 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003351 return MAY_LJMP(hlua_socket_connect(L));
3352}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003353#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003354
3355__LJMP static int hlua_socket_setoption(struct lua_State *L)
3356{
3357 return 0;
3358}
3359
3360__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3361{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003362 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003363 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003364 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003365 struct xref *peer;
Christopher Fauletcb068552023-09-27 17:34:24 +02003366 struct hlua_csk_ctx *csk_ctx;
3367 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003368 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003369
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003370 MAY_LJMP(check_args(L, 2, "settimeout"));
3371
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003372 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003373
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003374 /* convert the timeout to millis */
3375 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003376
Thierry Fournier17a921b2018-03-08 09:59:02 +01003377 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003378 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003379 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3380
Mark Lakes56cc1252018-03-27 09:48:06 +02003381 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003382 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003383
3384 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003385 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003386 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003387
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003388 /* Check if we run on the same thread than the xreator thread.
3389 * We cannot access to the socket if the thread is different.
3390 */
3391 if (socket->tid != tid)
3392 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3393
Mark Lakes56cc1252018-03-27 09:48:06 +02003394 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003395 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003396 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003397 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3398 WILL_LJMP(lua_error(L));
3399 return 0;
3400 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003401
Christopher Fauletcb068552023-09-27 17:34:24 +02003402 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3403 csk_ctx->timeout = tmout;
3404
3405 appctx = csk_ctx->appctx;
3406 if (!appctx_sc(appctx))
3407 goto end;
3408
3409 s = appctx_strm(csk_ctx->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003410
Cyril Bonté7bb63452018-08-17 23:51:02 +02003411 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003412 s->scf->ioto = tmout;
3413 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003414
Christopher Fauletcb068552023-09-27 17:34:24 +02003415 s->task->expire = (tick_is_expired(s->task->expire, now_ms) ? 0 : s->task->expire);
3416 s->task->expire = tick_first(s->task->expire, tick_add_ifset(now_ms, tmout));
Cyril Bonté7bb63452018-08-17 23:51:02 +02003417 task_queue(s->task);
3418
Christopher Fauletcb068552023-09-27 17:34:24 +02003419 end:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003420 xref_unlock(&socket->xref, peer);
Thierry Fourniere9636f12018-03-08 09:54:32 +01003421 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003422 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003423}
3424
3425__LJMP static int hlua_socket_new(lua_State *L)
3426{
3427 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003428 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003429 struct appctx *appctx;
Christopher Faulet5b62e092024-02-16 15:00:54 +01003430 struct hlua *hlua;
3431
3432 /* Get hlua struct, or NULL if we execute from main lua state */
3433 hlua = hlua_gethlua(L);
3434 if (!hlua)
3435 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003436
3437 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003438 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003439 hlua_pusherror(L, "socket: full stack");
3440 goto out_fail_conf;
3441 }
3442
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003443 /* Create the object: obj[0] = userdata. */
3444 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003445 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003446 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003447 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003448 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003449
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003450 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003451 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003452 hlua_pusherror(L, "socket: uninitialized pools.");
3453 goto out_fail_conf;
3454 }
3455
Willy Tarreau87b09662015-04-03 00:22:06 +02003456 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003457 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3458 lua_setmetatable(L, -2);
3459
Willy Tarreaud420a972015-04-06 00:39:18 +02003460 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003461 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003462 if (!appctx) {
3463 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003464 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003465 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003466 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3467 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003468 ctx->die = 0;
Christopher Faulet26786572023-09-27 17:39:44 +02003469 ctx->srv = NULL;
Christopher Fauletcb068552023-09-27 17:34:24 +02003470 ctx->timeout = 0;
Christopher Faulet75d1bfb2023-09-27 17:17:48 +02003471 ctx->appctx = appctx;
Willy Tarreau5321da92022-05-06 11:57:34 +02003472 LIST_INIT(&ctx->wake_on_write);
3473 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003474
Christopher Faulet5b62e092024-02-16 15:00:54 +01003475 hlua->gc_count++;
3476
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003477 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003478 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003479 return 1;
3480
Christopher Faulet13a35e52021-12-20 15:34:16 +01003481 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003482 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003483 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003484 WILL_LJMP(lua_error(L));
3485 return 0;
3486}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003487
3488/*
3489 *
3490 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003491 * Class Channel
3492 *
3493 *
3494 */
3495
3496/* Returns the struct hlua_channel join to the class channel in the
3497 * stack entry "ud" or throws an argument error.
3498 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003499__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003500{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003501 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003502}
3503
Willy Tarreau47860ed2015-03-10 14:07:50 +01003504/* Pushes the channel onto the top of the stack. If the stask does not have a
3505 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003506 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003507static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003508{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003509 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003510 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003511 return 0;
3512
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003513 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003514 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003515 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003516
3517 /* Pop a class sesison metatable and affect it to the userdata. */
3518 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3519 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003520 return 1;
3521}
3522
Christopher Faulet9f55a502020-02-25 15:21:02 +01003523/* Helper function returning a filter attached to a channel at the position <ud>
3524 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003525 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003526 * initialized.
3527 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003528static 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 +01003529{
3530 struct filter *filter = NULL;
3531
3532 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3533 struct hlua_flt_ctx *flt_ctx;
3534
3535 filter = lua_touserdata (L, -1);
3536 flt_ctx = filter->ctx;
3537 if (hlua_filter_from_payload(filter)) {
3538 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3539 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3540 }
3541 }
3542
3543 lua_pop(L, 1);
3544 return filter;
3545}
3546
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003547/* Copies <len> bytes of data present in the channel's buffer, starting at the
3548* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003549* responsibility to ensure <len> and <offset> are valid. It always return the
3550* length of the built string. <len> may be 0, in this case, an empty string is
3551* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003552*/
3553static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003554{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003555 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003556 luaL_Buffer b;
3557
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003558 block1 = len;
3559 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3560 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3561 block2 = len - block1;
3562
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003563 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003564 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3565 if (block2)
3566 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003567 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003568 return len;
3569}
3570
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003571/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3572 * function returns -1 if data cannot be copied. Otherwise, it returns the
3573 * number of bytes copied.
3574 */
3575static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3576{
3577 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003578
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003579 /* Nothing to do, just return */
3580 if (unlikely(istlen(str) == 0))
3581 goto end;
3582
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003583 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003584 ret = -1;
3585 goto end;
3586 }
3587 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3588
3589 end:
3590 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003591}
3592
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003593/* Removes <len> bytes of data at the absolute position <offset>.
3594 */
3595static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3596{
3597 size_t end = offset + len;
3598
3599 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3600 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3601 b_data(&chn->buf) - end, -len);
3602 b_sub(&chn->buf, len);
3603}
3604
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003605/* Copies input data in the channel's buffer. It is possible to set a specific
3606 * offset (0 by default) and a length (all remaining input data starting for the
3607 * offset by default). If there is not enough input data and more data can be
3608 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003609 *
3610 * From an action, All input data are considered. For a filter, the offset and
3611 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003612 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003613__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003614{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003615 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003616 struct filter *filter;
3617 size_t input, output;
3618 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003619
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003620 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003622 output = co_data(chn);
3623 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3626 if (filter && !hlua_filter_from_payload(filter))
3627 WILL_LJMP(lua_error(L));
3628
3629 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 if (lua_gettop(L) > 1) {
3631 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3632 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003633 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003634 offset += output;
3635 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003636 lua_pushfstring(L, "offset out of range.");
3637 WILL_LJMP(lua_error(L));
3638 }
3639 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003640 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003641 if (lua_gettop(L) == 3) {
3642 len = MAY_LJMP(luaL_checkinteger(L, 3));
3643 if (!len)
3644 goto dup;
3645 if (len == -1)
3646 len = global.tune.bufsize;
3647 if (len < 0) {
3648 lua_pushfstring(L, "length out of range.");
3649 WILL_LJMP(lua_error(L));
3650 }
3651 }
3652
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003653 /* Wait for more data if possible if no length was specified and there
3654 * is no data or not enough data was received.
3655 */
3656 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003657 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3658 /* Yield waiting for more data, as requested */
3659 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3660 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003661
3662 /* Return 'nil' if there is no data and the channel can't receive more data */
3663 if (!len) {
3664 lua_pushnil(L);
3665 return -1;
3666 }
3667
3668 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003669 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003670 }
3671
3672 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003673 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003674 return 1;
3675}
3676
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003677/* Copies the first line (including the trailing LF) of input data in the
3678 * channel's buffer. It is possible to set a specific offset (0 by default) and
3679 * a length (all remaining input data starting for the offset by default). If
3680 * there is not enough input data and more data can be received, the function
3681 * yields. If a length is explicitly specified, no more data are
3682 * copied. Otherwise, if no LF is found and more data can be received, this
3683 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003684 *
3685 * From an action, All input data are considered. For a filter, the offset and
3686 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003687 */
3688__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003689{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003690 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003691 struct filter *filter;
3692 size_t l, input, output;
3693 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003694
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003695 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003696 output = co_data(chn);
3697 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003698
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003699 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3700 if (filter && !hlua_filter_from_payload(filter))
3701 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003702
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003703 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003704 if (lua_gettop(L) > 1) {
3705 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3706 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003707 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003708 offset += output;
3709 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003710 lua_pushfstring(L, "offset out of range.");
3711 WILL_LJMP(lua_error(L));
3712 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003713 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003714
3715 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003716 if (lua_gettop(L) == 3) {
3717 len = MAY_LJMP(luaL_checkinteger(L, 3));
3718 if (!len)
3719 goto dup;
3720 if (len == -1)
3721 len = global.tune.bufsize;
3722 if (len < 0) {
3723 lua_pushfstring(L, "length out of range.");
3724 WILL_LJMP(lua_error(L));
3725 }
3726 }
3727
3728 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003730 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003731 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003732 len = l+1;
3733 goto dup;
3734 }
3735 }
3736
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003737 /* Wait for more data if possible if no line is found and no length was
3738 * specified or not enough data was received.
3739 */
3740 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003741 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3742 /* Yield waiting for more data */
3743 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3744 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003745
3746 /* Return 'nil' if there is no data and the channel can't receive more data */
3747 if (!len) {
3748 lua_pushnil(L);
3749 return -1;
3750 }
3751
3752 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003753 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003754 }
3755
3756 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003757 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003758 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003759}
3760
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003761/* [ DEPRECATED ]
3762 *
3763 * Duplicate all input data foud in the channel's buffer. The data are not
3764 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003765 *
3766 * From an action, All input data are considered. For a filter, the offset and
3767 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003768 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003769__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003770{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003771 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003772 struct filter *filter;
3773 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003774
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003775 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003776 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003777 if (IS_HTX_STRM(chn_strm(chn))) {
3778 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3779 WILL_LJMP(lua_error(L));
3780 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003781
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003782 offset = co_data(chn);
3783 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003784
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003785 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3786 if (filter && !hlua_filter_from_payload(filter))
3787 WILL_LJMP(lua_error(L));
3788
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003789 if (!ci_data(chn) && channel_input_closed(chn)) {
3790 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003791 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003792 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003793
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003794 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003795 return 1;
3796}
3797
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003798/* [ DEPRECATED ]
3799 *
3800 * Get all input data foud in the channel's buffer. The data are removed from
3801 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3802 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003803 *
3804 * From an action, All input data are considered. For a filter, the offset and
3805 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003806 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003807__LJMP static int hlua_channel_get(lua_State *L)
3808{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003809 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003810 struct filter *filter;
3811 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003812 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003813
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003814 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003815 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3816 if (IS_HTX_STRM(chn_strm(chn))) {
3817 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3818 WILL_LJMP(lua_error(L));
3819 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003820
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003821 offset = co_data(chn);
3822 len = ci_data(chn);
3823
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003824 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3825 if (filter && !hlua_filter_from_payload(filter))
3826 WILL_LJMP(lua_error(L));
3827
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003828 if (!ci_data(chn) && channel_input_closed(chn)) {
3829 lua_pushnil(L);
3830 return 1;
3831 }
3832
3833 ret = _hlua_channel_dup(chn, L, offset, len);
3834 _hlua_channel_delete(chn, offset, ret);
3835 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003836}
3837
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003838/* This functions consumes and returns one line. If the channel is closed,
3839 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003840 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003841 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842 *
3843 * From an action, All input data are considered. For a filter, the offset and
3844 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003845 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003846__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003847{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003848 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003849 struct filter *filter;
3850 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003851 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003852
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003853 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003854
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003855 offset = co_data(chn);
3856 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003857
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003858 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3859 if (filter && !hlua_filter_from_payload(filter))
3860 WILL_LJMP(lua_error(L));
3861
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003862 if (!ci_data(chn) && channel_input_closed(chn)) {
3863 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003864 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003865 }
3866
3867 for (l = 0; l < len; l++) {
3868 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3869 len = l+1;
3870 goto dup;
3871 }
3872 }
3873
3874 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3875 /* Yield waiting for more data */
3876 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3877 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003878
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003879 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003880 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003881 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003882 return 1;
3883}
3884
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003885/* [ DEPRECATED ]
3886 *
3887 * Check arguments for the function "hlua_channel_getline_yield".
3888 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003889__LJMP static int hlua_channel_getline(lua_State *L)
3890{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003891 struct channel *chn;
3892
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003893 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003894 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3895 if (IS_HTX_STRM(chn_strm(chn))) {
3896 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3897 WILL_LJMP(lua_error(L));
3898 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003899 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3900}
3901
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003902/* Retrieves a given amount of input data at the given offset. By default all
3903 * available input data are returned. The offset may be negactive to start from
3904 * the end of input data. The length may be -1 to set it to the maximum buffer
3905 * size.
3906 */
3907__LJMP static int hlua_channel_get_data(lua_State *L)
3908{
3909 struct channel *chn;
3910
3911 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3912 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3913 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3914 if (IS_HTX_STRM(chn_strm(chn))) {
3915 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3916 WILL_LJMP(lua_error(L));
3917 }
3918 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3919}
3920
3921/* Retrieves a given amount of input data at the given offset. By default all
3922 * available input data are returned. The offset may be negactive to start from
3923 * the end of input data. The length may be -1 to set it to the maximum buffer
3924 * size.
3925 */
3926__LJMP static int hlua_channel_get_line(lua_State *L)
3927{
3928 struct channel *chn;
3929
3930 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3931 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3932 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3933 if (IS_HTX_STRM(chn_strm(chn))) {
3934 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3935 WILL_LJMP(lua_error(L));
3936 }
3937 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3938}
3939
3940/* Appends a string into the input side of channel. It returns the length of the
3941 * written string, or -1 if the channel is closed or if the buffer size is too
3942 * little for the data. 0 may be returned if nothing is copied. This function
3943 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003944 *
3945 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003946 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003947__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003948{
Christopher Faulet23976d92021-08-06 09:59:49 +02003949 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003950 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003951 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003952 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003953 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003954
3955 MAY_LJMP(check_args(L, 2, "append"));
3956 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003957 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003958 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003959 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003960 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003961 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003962
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003963 offset = co_data(chn);
3964 len = ci_data(chn);
3965
3966 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3967 if (filter && !hlua_filter_from_payload(filter))
3968 WILL_LJMP(lua_error(L));
3969
3970 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3971 if (ret > 0 && filter) {
3972 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3973
3974 flt_update_offsets(filter, chn, ret);
3975 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3976 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003977 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003978 return 1;
3979}
3980
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003981/* Prepends a string into the input side of channel. It returns the length of the
3982 * written string, or -1 if the channel is closed or if the buffer size is too
3983 * little for the data. 0 may be returned if nothing is copied. This function
3984 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003985 *
3986 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003987 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003988__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003989{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003990 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003991 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003992 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003993 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003994 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003995
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003996 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003997 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003998 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3999 if (IS_HTX_STRM(chn_strm(chn))) {
4000 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4001 WILL_LJMP(lua_error(L));
4002 }
4003
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004004 offset = co_data(chn);
4005 len = ci_data(chn);
4006
4007 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4008 if (filter && !hlua_filter_from_payload(filter))
4009 WILL_LJMP(lua_error(L));
4010
4011 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4012 if (ret > 0 && filter) {
4013 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4014
4015 flt_update_offsets(filter, chn, ret);
4016 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
4017 }
4018
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004019 lua_pushinteger(L, ret);
4020 return 1;
4021}
4022
4023/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02004024 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004025 * returns the length of the written string, or -1 if the channel is closed or
4026 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004027 *
4028 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004029 */
4030__LJMP static int hlua_channel_insert_data(lua_State *L)
4031{
4032 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004033 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004034 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004035 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004036 int ret, offset;
4037
4038 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
4039 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
4040 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4041 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004042
4043 output = co_data(chn);
4044 input = ci_data(chn);
4045
4046 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4047 if (filter && !hlua_filter_from_payload(filter))
4048 WILL_LJMP(lua_error(L));
4049
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02004050 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004051 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004052 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004053 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004054 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004055 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02004056 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004057 lua_pushfstring(L, "offset out of range.");
4058 WILL_LJMP(lua_error(L));
4059 }
4060 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004061 if (IS_HTX_STRM(chn_strm(chn))) {
4062 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4063 WILL_LJMP(lua_error(L));
4064 }
4065
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004066 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4067 if (ret > 0 && filter) {
4068 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004069
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004070 flt_update_offsets(filter, chn, ret);
4071 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004072 }
4073
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004074 lua_pushinteger(L, ret);
4075 return 1;
4076}
4077/* Replaces a given amount of input data at the given offset by a string
4078 * content. By default all remaining data are removed (offset = 0 and len =
4079 * -1). It returns the length of the written string, or -1 if the channel is
4080 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004081 *
4082 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004083 */
4084__LJMP static int hlua_channel_set_data(lua_State *L)
4085{
4086 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004087 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004088 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004089 size_t sz, input, output;
4090 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004091
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004092 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
4093 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
4094 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4095 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004096
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01004097 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02004098 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01004099 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02004100 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004101
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004102 output = co_data(chn);
4103 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004104
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004105 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4106 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004107 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004108
4109 offset = output;
4110 if (lua_gettop(L) > 2) {
4111 offset = MAY_LJMP(luaL_checkinteger(L, 3));
4112 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004113 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004114 offset += output;
4115 if (offset < output || offset > input + output) {
4116 lua_pushfstring(L, "offset out of range.");
4117 WILL_LJMP(lua_error(L));
4118 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004119 }
4120
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004121 len = output + input - offset;
4122 if (lua_gettop(L) == 4) {
4123 len = MAY_LJMP(luaL_checkinteger(L, 4));
4124 if (!len)
4125 goto set;
4126 if (len == -1)
4127 len = output + input - offset;
4128 if (len < 0 || offset + len > output + input) {
4129 lua_pushfstring(L, "length out of range.");
4130 WILL_LJMP(lua_error(L));
4131 }
4132 }
4133
4134 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02004135 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004136 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02004137 lua_pushinteger(L, -1);
4138 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004139 _hlua_channel_delete(chn, offset, len);
4140 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4141 if (filter) {
4142 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4143
4144 len -= (ret > 0 ? ret : 0);
4145 flt_update_offsets(filter, chn, -len);
4146 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4147 }
4148
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004149 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02004150 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004151 return 1;
4152}
4153
4154/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004155 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004156 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004157 *
4158 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004159 */
4160__LJMP static int hlua_channel_del_data(lua_State *L)
4161{
4162 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004163 struct filter *filter;
4164 size_t input, output;
4165 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004166
4167 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
4168 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
4169 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004170
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004171 if (IS_HTX_STRM(chn_strm(chn))) {
4172 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4173 WILL_LJMP(lua_error(L));
4174 }
4175
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004176 output = co_data(chn);
4177 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004178
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004179 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4180 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004181 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004182
4183 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00004184 if (lua_gettop(L) > 1) {
4185 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004186 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004187 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004188 offset += output;
4189 if (offset < output || offset > input + output) {
4190 lua_pushfstring(L, "offset out of range.");
4191 WILL_LJMP(lua_error(L));
4192 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004193 }
4194
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004195 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00004196 if (lua_gettop(L) == 3) {
4197 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004198 if (!len)
4199 goto end;
4200 if (len == -1)
4201 len = output + input - offset;
4202 if (len < 0 || offset + len > output + input) {
4203 lua_pushfstring(L, "length out of range.");
4204 WILL_LJMP(lua_error(L));
4205 }
4206 }
4207
4208 _hlua_channel_delete(chn, offset, len);
4209 if (filter) {
4210 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4211
4212 flt_update_offsets(filter, chn, -len);
4213 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4214 }
4215
4216 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004217 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02004218 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004219}
4220
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004221/* Append data in the output side of the buffer. This data is immediately
4222 * sent. The function returns the amount of data written. If the buffer
4223 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004224 * if the channel is closed.
4225 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004226__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004227{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004228 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004229 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004230 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004231 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004232 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004233 struct hlua *hlua;
4234
4235 /* Get hlua struct, or NULL if we execute from main lua state */
4236 hlua = hlua_gethlua(L);
4237 if (!hlua) {
4238 lua_pushnil(L);
4239 return 1;
4240 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004241
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004242 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4243 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4244 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004245
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004246 offset = co_data(chn);
4247 len = ci_data(chn);
4248
4249 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4250 if (filter && !hlua_filter_from_payload(filter))
4251 WILL_LJMP(lua_error(L));
4252
4253
Willy Tarreau47860ed2015-03-10 14:07:50 +01004254 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004255 lua_pushinteger(L, -1);
4256 return 1;
4257 }
4258
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004259 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004260 if (len > sz -l) {
4261 if (filter) {
4262 lua_pushinteger(L, -1);
4263 return 1;
4264 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004265 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004266 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004267
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004268 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004269 if (ret == -1) {
4270 lua_pop(L, 1);
4271 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004272 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004273 }
4274 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004275 if (filter) {
4276 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4277
4278
4279 flt_update_offsets(filter, chn, ret);
4280 FLT_OFF(filter, chn) += ret;
4281 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4282 }
4283 else
4284 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004285
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004286 l += ret;
4287 lua_pop(L, 1);
4288 lua_pushinteger(L, l);
4289 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004290
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004291 if (l < sz) {
4292 /* Yield only if the channel's output is not empty.
4293 * Otherwise it means we cannot add more data. */
4294 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004295 return 1;
4296
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004297 /* If we are waiting for space in the response buffer, we
4298 * must set the flag WAKERESWR. This flag required the task
4299 * wake up if any activity is detected on the response buffer.
4300 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004301 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004302 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004303 else
4304 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004305 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004306 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004307
4308 return 1;
4309}
4310
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004311/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004312 * yield the LUA process, and resume it without checking the
4313 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004314 *
4315 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004316 */
4317__LJMP static int hlua_channel_send(lua_State *L)
4318{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004319 struct channel *chn;
4320
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004321 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004322 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4323 if (IS_HTX_STRM(chn_strm(chn))) {
4324 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4325 WILL_LJMP(lua_error(L));
4326 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004327 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004328 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004329}
4330
4331/* This function forward and amount of butes. The data pass from
4332 * the input side of the buffer to the output side, and can be
4333 * forwarded. This function never fails.
4334 *
4335 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004336 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004337 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004338__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004339{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004340 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004341 struct filter *filter;
4342 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004343 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004344 struct hlua *hlua;
4345
4346 /* Get hlua struct, or NULL if we execute from main lua state */
4347 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004348 if (!hlua) {
4349 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004350 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004351 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004352
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004353 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004354 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004355 l = MAY_LJMP(luaL_checkinteger(L, -1));
4356
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004357 offset = co_data(chn);
4358 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004359
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004360 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4361 if (filter && !hlua_filter_from_payload(filter))
4362 WILL_LJMP(lua_error(L));
4363
4364 max = fwd - l;
4365 if (max > len)
4366 max = len;
4367
4368 if (filter) {
4369 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4370
4371 FLT_OFF(filter, chn) += max;
4372 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4373 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4374 }
4375 else
4376 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004377
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004378 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004379 lua_pop(L, 1);
4380 lua_pushinteger(L, l);
4381
4382 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004383 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004384 /* The the input channel or the output channel are closed, we
4385 * must return the amount of data forwarded.
4386 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004387 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004388 return 1;
4389
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004390 /* If we are waiting for space data in the response buffer, we
4391 * must set the flag WAKERESWR. This flag required the task
4392 * wake up if any activity is detected on the response buffer.
4393 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004394 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004395 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004396 else
4397 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004398
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004399 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004400 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004401 }
4402
4403 return 1;
4404}
4405
4406/* Just check the input and prepare the stack for the previous
4407 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004408 *
4409 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004410 */
4411__LJMP static int hlua_channel_forward(lua_State *L)
4412{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004413 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004414
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004415 MAY_LJMP(check_args(L, 2, "forward"));
4416 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4417 if (IS_HTX_STRM(chn_strm(chn))) {
4418 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4419 WILL_LJMP(lua_error(L));
4420 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004421 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004422 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004423}
4424
4425/* Just returns the number of bytes available in the input
4426 * side of the buffer. This function never fails.
4427 */
4428__LJMP static int hlua_channel_get_in_len(lua_State *L)
4429{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004430 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004431 struct filter *filter;
4432 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004433
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004434 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004435 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004436
4437 output = co_data(chn);
4438 input = ci_data(chn);
4439 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4440 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4441 lua_pushinteger(L, input);
4442 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004443 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004444
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004445 lua_pushinteger(L, htx->data - co_data(chn));
4446 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004447 return 1;
4448}
4449
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004450/* Returns true if the channel is full. */
4451__LJMP static int hlua_channel_is_full(lua_State *L)
4452{
4453 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004454
4455 MAY_LJMP(check_args(L, 1, "is_full"));
4456 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004457 /* ignore the reserve, we are not on a producer side (ie in an
4458 * applet).
4459 */
4460 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004461 return 1;
4462}
4463
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004464/* Returns true if the channel may still receive data. */
4465__LJMP static int hlua_channel_may_recv(lua_State *L)
4466{
4467 struct channel *chn;
4468
4469 MAY_LJMP(check_args(L, 1, "may_recv"));
4470 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4471 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4472 return 1;
4473}
4474
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004475/* Returns true if the channel is the response channel. */
4476__LJMP static int hlua_channel_is_resp(lua_State *L)
4477{
4478 struct channel *chn;
4479
4480 MAY_LJMP(check_args(L, 1, "is_resp"));
4481 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4482
4483 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4484 return 1;
4485}
4486
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004487/* Just returns the number of bytes available in the output
4488 * side of the buffer. This function never fails.
4489 */
4490__LJMP static int hlua_channel_get_out_len(lua_State *L)
4491{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004492 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004493 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004494
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004495 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004496 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004497
4498 output = co_data(chn);
4499 input = ci_data(chn);
4500 hlua_channel_filter(L, 1, chn, &output, &input);
4501
4502 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004503 return 1;
4504}
4505
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004506/*
4507 *
4508 *
4509 * Class Fetches
4510 *
4511 *
4512 */
4513
4514/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004515 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004516 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004517__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004518{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004519 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004520}
4521
4522/* This function creates and push in the stack a fetch object according
4523 * with a current TXN.
4524 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004525static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004526{
Willy Tarreau7073c472015-04-06 11:15:40 +02004527 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004528
4529 /* Check stack size. */
4530 if (!lua_checkstack(L, 3))
4531 return 0;
4532
4533 /* Create the object: obj[0] = userdata.
4534 * Note that the base of the Fetches object is the
4535 * transaction object.
4536 */
4537 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004538 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004539 lua_rawseti(L, -2, 0);
4540
Willy Tarreau7073c472015-04-06 11:15:40 +02004541 hsmp->s = txn->s;
4542 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004543 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004544 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004545
4546 /* Pop a class sesison metatable and affect it to the userdata. */
4547 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4548 lua_setmetatable(L, -2);
4549
4550 return 1;
4551}
4552
4553/* This function is an LUA binding. It is called with each sample-fetch.
4554 * It uses closure argument to store the associated sample-fetch. It
4555 * returns only one argument or throws an error. An error is thrown
4556 * only if an error is encountered during the argument parsing. If
4557 * the "sample-fetch" function fails, nil is returned.
4558 */
4559__LJMP static int hlua_run_sample_fetch(lua_State *L)
4560{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004561 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004562 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004563 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004564 int i;
4565 struct sample smp;
4566
4567 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004568 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004569
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004570 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004571 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004572
Thierry FOURNIERca988662015-12-20 18:43:03 +01004573 /* Check execution authorization. */
4574 if (f->use & SMP_USE_HTTP_ANY &&
4575 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4576 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4577 "is not available in Lua services", f->kw);
4578 WILL_LJMP(lua_error(L));
4579 }
4580
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004581 /* Get extra arguments. */
4582 for (i = 0; i < lua_gettop(L) - 1; i++) {
4583 if (i >= ARGM_NBARGS)
4584 break;
4585 hlua_lua2arg(L, i + 2, &args[i]);
4586 }
4587 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004588 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004589
4590 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004591 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004592
4593 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004594 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004595 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004596 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004597 }
4598
4599 /* Initialise the sample. */
4600 memset(&smp, 0, sizeof(smp));
4601
4602 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004603 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004604 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004605 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004606 lua_pushstring(L, "");
4607 else
4608 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004609 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004610 }
4611
4612 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004613 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004614 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004615 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004616 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004617
4618 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004619 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004620 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004621
4622 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004623 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004624 WILL_LJMP(lua_error(L));
4625 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004626}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004627
4628/*
4629 *
4630 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004631 * Class Converters
4632 *
4633 *
4634 */
4635
4636/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004637 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004638 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004639__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004640{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004641 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004642}
4643
4644/* This function creates and push in the stack a Converters object
4645 * according with a current TXN.
4646 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004647static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004648{
Willy Tarreau7073c472015-04-06 11:15:40 +02004649 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004650
4651 /* Check stack size. */
4652 if (!lua_checkstack(L, 3))
4653 return 0;
4654
4655 /* Create the object: obj[0] = userdata.
4656 * Note that the base of the Converters object is the
4657 * same than the TXN object.
4658 */
4659 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004660 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004661 lua_rawseti(L, -2, 0);
4662
Willy Tarreau7073c472015-04-06 11:15:40 +02004663 hsmp->s = txn->s;
4664 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004665 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004666 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004667
Willy Tarreau87b09662015-04-03 00:22:06 +02004668 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004669 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4670 lua_setmetatable(L, -2);
4671
4672 return 1;
4673}
4674
4675/* This function is an LUA binding. It is called with each converter.
4676 * It uses closure argument to store the associated converter. It
4677 * returns only one argument or throws an error. An error is thrown
4678 * only if an error is encountered during the argument parsing. If
4679 * the converter function function fails, nil is returned.
4680 */
4681__LJMP static int hlua_run_sample_conv(lua_State *L)
4682{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004683 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004684 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004685 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004686 int i;
4687 struct sample smp;
4688
4689 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004690 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004691
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004692 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004693 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004694
4695 /* Get extra arguments. */
4696 for (i = 0; i < lua_gettop(L) - 2; i++) {
4697 if (i >= ARGM_NBARGS)
4698 break;
4699 hlua_lua2arg(L, i + 3, &args[i]);
4700 }
4701 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004702 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004703
4704 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004705 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004706
4707 /* Run the special args checker. */
4708 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4709 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004710 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004711 }
4712
4713 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004714 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004715 if (!hlua_lua2smp(L, 2, &smp)) {
4716 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004717 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004718 }
4719
Willy Tarreau1777ea62016-03-10 16:15:46 +01004720 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4721
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004722 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004723 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004724 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004725 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004726 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004727 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004728 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4729 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004730 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004731 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004732 }
4733
4734 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004735 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004736 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004737 lua_pushstring(L, "");
4738 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004739 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004740 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004741 }
4742
4743 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004744 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004745 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004746 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004747 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004748 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004749 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004750 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004751
4752 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004753 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004754 WILL_LJMP(lua_error(L));
4755 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004756}
4757
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004758/*
4759 *
4760 *
4761 * Class AppletTCP
4762 *
4763 *
4764 */
4765
4766/* Returns a struct hlua_txn if the stack entry "ud" is
4767 * a class stream, otherwise it throws an error.
4768 */
4769__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4770{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004771 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004772}
4773
4774/* This function creates and push in the stack an Applet object
4775 * according with a current TXN.
4776 */
4777static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4778{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004779 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004780 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004781 struct proxy *p;
4782
4783 ALREADY_CHECKED(s);
4784 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004785
4786 /* Check stack size. */
4787 if (!lua_checkstack(L, 3))
4788 return 0;
4789
4790 /* Create the object: obj[0] = userdata.
4791 * Note that the base of the Converters object is the
4792 * same than the TXN object.
4793 */
4794 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004795 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004796 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004797 luactx->appctx = ctx;
4798 luactx->htxn.s = s;
4799 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004800
4801 /* Create the "f" field that contains a list of fetches. */
4802 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004803 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004804 return 0;
4805 lua_settable(L, -3);
4806
4807 /* Create the "sf" field that contains a list of stringsafe fetches. */
4808 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004809 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004810 return 0;
4811 lua_settable(L, -3);
4812
4813 /* Create the "c" field that contains a list of converters. */
4814 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004815 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004816 return 0;
4817 lua_settable(L, -3);
4818
4819 /* Create the "sc" field that contains a list of stringsafe converters. */
4820 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004821 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004822 return 0;
4823 lua_settable(L, -3);
4824
4825 /* Pop a class stream metatable and affect it to the table. */
4826 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4827 lua_setmetatable(L, -2);
4828
4829 return 1;
4830}
4831
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004832__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4833{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004834 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004835 struct stream *s;
4836 const char *name;
4837 size_t len;
4838 struct sample smp;
4839
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004840 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4841 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004842
4843 /* It is useles to retrieve the stream, but this function
4844 * runs only in a stream context.
4845 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004846 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004847 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004848 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004849
4850 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004851 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004852 hlua_lua2smp(L, 3, &smp);
4853
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02004854 /* Store the sample in a variable. We don't need to dup the smp, vars API
4855 * already takes care of duplicating dynamic var data.
4856 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004857 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004858
4859 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4860 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4861 else
4862 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4863
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004864 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004865}
4866
4867__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4868{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004869 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004870 struct stream *s;
4871 const char *name;
4872 size_t len;
4873 struct sample smp;
4874
4875 MAY_LJMP(check_args(L, 2, "unset_var"));
4876
4877 /* It is useles to retrieve the stream, but this function
4878 * runs only in a stream context.
4879 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004880 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004881 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004882 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883
4884 /* Unset the variable. */
4885 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004886 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4887 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888}
4889
4890__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4891{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004892 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004893 struct stream *s;
4894 const char *name;
4895 size_t len;
4896 struct sample smp;
4897
4898 MAY_LJMP(check_args(L, 2, "get_var"));
4899
4900 /* It is useles to retrieve the stream, but this function
4901 * runs only in a stream context.
4902 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004903 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004905 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004906
4907 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004908 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004909 lua_pushnil(L);
4910 return 1;
4911 }
4912
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004913 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004914}
4915
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004916__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4917{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004918 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4919 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004920 struct hlua *hlua;
4921
4922 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004923 if (!s->hlua)
4924 return 0;
4925 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004926
4927 MAY_LJMP(check_args(L, 2, "set_priv"));
4928
4929 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004930 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004931
4932 /* Get and store new value. */
4933 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4934 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4935
4936 return 0;
4937}
4938
4939__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4940{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004941 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4942 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004943 struct hlua *hlua;
4944
4945 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004946 if (!s->hlua) {
4947 lua_pushnil(L);
4948 return 1;
4949 }
4950 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004951
4952 /* Push configuration index in the stack. */
4953 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4954
4955 return 1;
4956}
4957
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004958/* If expected data not yet available, it returns a yield. This function
4959 * consumes the data in the buffer. It returns a string containing the
4960 * data. This string can be empty.
4961 */
4962__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4963{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004964 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004965 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004966 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004967 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004968 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004969 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004970 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004971
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004972 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004973 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004974
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004975 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004976 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004977 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004978 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004979 }
4980
4981 /* End of data: commit the total strings and return. */
4982 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004983 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004984 return 1;
4985 }
4986
4987 /* Ensure that the block 2 length is usable. */
4988 if (ret == 1)
4989 len2 = 0;
4990
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004991 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004992 luaL_addlstring(&luactx->b, blk1, len1);
4993 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004994
4995 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004996 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004997 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004998 return 1;
4999}
5000
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005001/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005002__LJMP static int hlua_applet_tcp_getline(lua_State *L)
5003{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005004 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005005
5006 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005007 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005008
5009 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
5010}
5011
5012/* If expected data not yet available, it returns a yield. This function
5013 * consumes the data in the buffer. It returns a string containing the
5014 * data. This string can be empty.
5015 */
5016__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
5017{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005019 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005020 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005021 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02005022 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005023 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02005024 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02005025 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005026
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005027 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02005028 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005029
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005030 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005031 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005032 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005033 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005034 }
5035
5036 /* End of data: commit the total strings and return. */
5037 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02005038 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005039 return 1;
5040 }
5041
5042 /* Ensure that the block 2 length is usable. */
5043 if (ret == 1)
5044 len2 = 0;
5045
5046 if (len == -1) {
5047
5048 /* If len == -1, catenate all the data avalaile and
5049 * yield because we want to get all the data until
5050 * the end of data stream.
5051 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005052 luaL_addlstring(&luactx->b, blk1, len1);
5053 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005054 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02005055 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005056 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005057
5058 } else {
5059
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005060 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005061 if (len1 > len)
5062 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005063 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005064 len -= len1;
5065
5066 /* Copy the second block. */
5067 if (len2 > len)
5068 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005069 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005070 len -= len2;
5071
5072 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02005073 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005074
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005075 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005076 if (len > 0) {
5077 lua_pushinteger(L, len);
5078 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02005079 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005080 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005081 }
5082
5083 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005084 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005085 return 1;
5086 }
5087
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005088 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005089 hlua_pusherror(L, "Lua: internal error");
5090 WILL_LJMP(lua_error(L));
5091 return 0;
5092}
5093
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005094/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005095__LJMP static int hlua_applet_tcp_recv(lua_State *L)
5096{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005097 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005098 int len = -1;
5099
5100 if (lua_gettop(L) > 2)
5101 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5102 if (lua_gettop(L) >= 2) {
5103 len = MAY_LJMP(luaL_checkinteger(L, 2));
5104 lua_pop(L, 1);
5105 }
5106
5107 /* Confirm or set the required length */
5108 lua_pushinteger(L, len);
5109
5110 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005111 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005112
5113 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
5114}
5115
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005116/* Append data in the output side of the buffer. This data is immediately
5117 * sent. The function returns the amount of data written. If the buffer
5118 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005119 * if the channel is closed.
5120 */
5121__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
5122{
5123 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005124 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005125 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
5126 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005127 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005128 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005129 int max;
5130
5131 /* Get the max amount of data which can write as input in the channel. */
5132 max = channel_recv_max(chn);
5133 if (max > (len - l))
5134 max = len - l;
5135
5136 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005137 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005138
5139 /* update counters. */
5140 l += max;
5141 lua_pop(L, 1);
5142 lua_pushinteger(L, l);
5143
5144 /* If some data is not send, declares the situation to the
5145 * applet, and returns a yield.
5146 */
5147 if (l < len) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005148 sc_need_room(sc, channel_recv_max(chn) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005149 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005150 }
5151
5152 return 1;
5153}
5154
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005155/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005156 * yield the LUA process, and resume it without checking the
5157 * input arguments.
5158 */
5159__LJMP static int hlua_applet_tcp_send(lua_State *L)
5160{
5161 MAY_LJMP(check_args(L, 2, "send"));
5162 lua_pushinteger(L, 0);
5163
5164 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
5165}
5166
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005167/*
5168 *
5169 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005170 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005171 *
5172 *
5173 */
5174
5175/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005176 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005177 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005178__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005179{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005180 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005181}
5182
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005183/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005184 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005185 * It relies on the caller to have already reserved the room in ctx->svcctx
5186 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005187 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005188static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005189{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005190 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005191 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01005192 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02005193 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005194 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02005195 struct htx *htx;
5196 struct htx_blk *blk;
5197 struct htx_sl *sl;
5198 struct ist path;
5199 unsigned long long len = 0;
5200 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02005201 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005202
5203 /* Check stack size. */
5204 if (!lua_checkstack(L, 3))
5205 return 0;
5206
5207 /* Create the object: obj[0] = userdata.
5208 * Note that the base of the Converters object is the
5209 * same than the TXN object.
5210 */
5211 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005212 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005213 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005214 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005215 http_ctx->status = 200; /* Default status code returned. */
5216 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005217 luactx->htxn.s = s;
5218 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005219
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005220 /* Create the "f" field that contains a list of fetches. */
5221 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005222 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005223 return 0;
5224 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005225
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005226 /* Create the "sf" field that contains a list of stringsafe fetches. */
5227 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005228 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005229 return 0;
5230 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005231
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005232 /* Create the "c" field that contains a list of converters. */
5233 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005234 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005235 return 0;
5236 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005237
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238 /* Create the "sc" field that contains a list of stringsafe converters. */
5239 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005240 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005241 return 0;
5242 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005243
Christopher Fauleta2097962019-07-15 16:25:33 +02005244 htx = htxbuf(&s->req.buf);
5245 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005246 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005247 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005248
Christopher Fauleta2097962019-07-15 16:25:33 +02005249 /* Stores the request method. */
5250 lua_pushstring(L, "method");
5251 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5252 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005253
Christopher Fauleta2097962019-07-15 16:25:33 +02005254 /* Stores the http version. */
5255 lua_pushstring(L, "version");
5256 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5257 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005258
Christopher Fauleta2097962019-07-15 16:25:33 +02005259 /* creates an array of headers. hlua_http_get_headers() crates and push
5260 * the array on the top of the stack.
5261 */
5262 lua_pushstring(L, "headers");
5263 htxn.s = s;
5264 htxn.p = px;
5265 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005266 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005267 return 0;
5268 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005269
Amaury Denoyellec453f952021-07-06 11:40:12 +02005270 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5271 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005272 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005273 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005274
Christopher Fauleta2097962019-07-15 16:25:33 +02005275 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005276 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005277 q = p;
5278 while (q < end && *q != '?')
5279 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005280
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005281 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005282 lua_pushstring(L, "path");
5283 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005284 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005285
Christopher Fauleta2097962019-07-15 16:25:33 +02005286 /* Stores the query string. */
5287 lua_pushstring(L, "qs");
5288 if (*q == '?')
5289 q++;
5290 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005291 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005292 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005293
Christopher Fauleta2097962019-07-15 16:25:33 +02005294 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5295 struct htx_blk *blk = htx_get_blk(htx, pos);
5296 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005297
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005298 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005299 break;
5300 if (type == HTX_BLK_DATA)
5301 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005302 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005303 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005304 len += htx->extra;
5305
5306 /* Stores the request path. */
5307 lua_pushstring(L, "length");
5308 lua_pushinteger(L, len);
5309 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005310
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005311 /* Create an empty array of HTTP request headers. */
5312 lua_pushstring(L, "response");
5313 lua_newtable(L);
5314 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005315
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005316 /* Pop a class stream metatable and affect it to the table. */
5317 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5318 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005319
5320 return 1;
5321}
5322
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005323__LJMP static int hlua_applet_http_set_var(lua_State *L)
5324{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005325 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005326 struct stream *s;
5327 const char *name;
5328 size_t len;
5329 struct sample smp;
5330
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005331 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5332 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005333
5334 /* It is useles to retrieve the stream, but this function
5335 * runs only in a stream context.
5336 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005337 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005338 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005339 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005340
5341 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005342 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005343 hlua_lua2smp(L, 3, &smp);
5344
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02005345 /* Store the sample in a variable. We don't need to dup the smp, vars API
5346 * already takes care of duplicating dynamic var data.
5347 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005348 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005349
5350 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5351 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5352 else
5353 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5354
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005355 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005356}
5357
5358__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5359{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005360 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005361 struct stream *s;
5362 const char *name;
5363 size_t len;
5364 struct sample smp;
5365
5366 MAY_LJMP(check_args(L, 2, "unset_var"));
5367
5368 /* It is useles to retrieve the stream, but this function
5369 * runs only in a stream context.
5370 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005371 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005372 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005373 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005374
5375 /* Unset the variable. */
5376 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005377 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5378 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005379}
5380
5381__LJMP static int hlua_applet_http_get_var(lua_State *L)
5382{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005383 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005384 struct stream *s;
5385 const char *name;
5386 size_t len;
5387 struct sample smp;
5388
5389 MAY_LJMP(check_args(L, 2, "get_var"));
5390
5391 /* It is useles to retrieve the stream, but this function
5392 * runs only in a stream context.
5393 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005394 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005395 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005396 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005397
5398 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005399 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005400 lua_pushnil(L);
5401 return 1;
5402 }
5403
Aurelien DARRAGON41217722023-05-17 10:44:47 +02005404 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005405}
5406
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005407__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5408{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005409 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5410 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005411 struct hlua *hlua;
5412
5413 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005414 if (!s->hlua)
5415 return 0;
5416 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005417
5418 MAY_LJMP(check_args(L, 2, "set_priv"));
5419
5420 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005421 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005422
5423 /* Get and store new value. */
5424 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5425 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5426
5427 return 0;
5428}
5429
5430__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5431{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005432 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5433 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005434 struct hlua *hlua;
5435
5436 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005437 if (!s->hlua) {
5438 lua_pushnil(L);
5439 return 1;
5440 }
5441 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005442
5443 /* Push configuration index in the stack. */
5444 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5445
5446 return 1;
5447}
5448
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005449/* If expected data not yet available, it returns a yield. This function
5450 * consumes the data in the buffer. It returns a string containing the
5451 * data. This string can be empty.
5452 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005453__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005454{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005455 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005456 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005457 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005458 struct htx *htx;
5459 struct htx_blk *blk;
5460 size_t count;
5461 int stop = 0;
5462
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005463 htx = htx_from_buf(&req->buf);
5464 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005465 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005466
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005467 while (count && !stop && blk) {
5468 enum htx_blk_type type = htx_get_blk_type(blk);
5469 uint32_t sz = htx_get_blksz(blk);
5470 struct ist v;
5471 uint32_t vlen;
5472 char *nl;
5473
5474 vlen = sz;
5475 if (vlen > count) {
5476 if (type != HTX_BLK_DATA)
5477 break;
5478 vlen = count;
5479 }
5480
5481 switch (type) {
5482 case HTX_BLK_UNUSED:
5483 break;
5484
5485 case HTX_BLK_DATA:
5486 v = htx_get_blk_value(htx, blk);
5487 v.len = vlen;
5488 nl = istchr(v, '\n');
5489 if (nl != NULL) {
5490 stop = 1;
5491 vlen = nl - v.ptr + 1;
5492 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005493 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005494 break;
5495
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005496 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005497 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005498 stop = 1;
5499 break;
5500
5501 default:
5502 break;
5503 }
5504
Willy Tarreau84240042022-02-28 16:51:23 +01005505 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005506 count -= vlen;
5507 if (sz == vlen)
5508 blk = htx_remove_blk(htx, blk);
5509 else {
5510 htx_cut_data_blk(htx, blk, vlen);
5511 break;
5512 }
5513 }
5514
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005515 /* The message was fully consumed and no more data are expected
5516 * (EOM flag set).
5517 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005518 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005519 stop = 1;
5520
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005521 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005522 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005523 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005524 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005525 }
5526
5527 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005528 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005529 return 1;
5530}
5531
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005532
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005533/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005534__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005535{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005536 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005537
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005538 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005539 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005540
Christopher Fauleta2097962019-07-15 16:25:33 +02005541 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005542}
5543
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005544/* If expected data not yet available, it returns a yield. This function
5545 * consumes the data in the buffer. It returns a string containing the
5546 * data. This string can be empty.
5547 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005548__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005550 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005551 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005552 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005553 struct htx *htx;
5554 struct htx_blk *blk;
5555 size_t count;
5556 int len;
5557
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005558 htx = htx_from_buf(&req->buf);
5559 len = MAY_LJMP(luaL_checkinteger(L, 2));
5560 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005561 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005562 while (count && len && blk) {
5563 enum htx_blk_type type = htx_get_blk_type(blk);
5564 uint32_t sz = htx_get_blksz(blk);
5565 struct ist v;
5566 uint32_t vlen;
5567
5568 vlen = sz;
5569 if (len > 0 && vlen > len)
5570 vlen = len;
5571 if (vlen > count) {
5572 if (type != HTX_BLK_DATA)
5573 break;
5574 vlen = count;
5575 }
5576
5577 switch (type) {
5578 case HTX_BLK_UNUSED:
5579 break;
5580
5581 case HTX_BLK_DATA:
5582 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005583 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005584 break;
5585
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005586 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005587 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005588 len = 0;
5589 break;
5590
5591 default:
5592 break;
5593 }
5594
Willy Tarreau84240042022-02-28 16:51:23 +01005595 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005596 count -= vlen;
5597 if (len > 0)
5598 len -= vlen;
5599 if (sz == vlen)
5600 blk = htx_remove_blk(htx, blk);
5601 else {
5602 htx_cut_data_blk(htx, blk, vlen);
5603 break;
5604 }
5605 }
5606
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005607 /* The message was fully consumed and no more data are expected
5608 * (EOM flag set).
5609 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005610 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005611 len = 0;
5612
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005613 htx_to_buf(htx, &req->buf);
5614
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005615 /* If we are no other data available, yield waiting for new data. */
5616 if (len) {
5617 if (len > 0) {
5618 lua_pushinteger(L, len);
5619 lua_replace(L, 2);
5620 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005621 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005622 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005623 }
5624
5625 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005626 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627 return 1;
5628}
5629
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005630/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005631__LJMP static int hlua_applet_http_recv(lua_State *L)
5632{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005633 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005634 int len = -1;
5635
5636 /* Check arguments. */
5637 if (lua_gettop(L) > 2)
5638 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5639 if (lua_gettop(L) >= 2) {
5640 len = MAY_LJMP(luaL_checkinteger(L, 2));
5641 lua_pop(L, 1);
5642 }
5643
Christopher Fauleta2097962019-07-15 16:25:33 +02005644 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005645
Christopher Fauleta2097962019-07-15 16:25:33 +02005646 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005647 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005648
Christopher Fauleta2097962019-07-15 16:25:33 +02005649 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005650}
5651
5652/* Append data in the output side of the buffer. This data is immediately
5653 * sent. The function returns the amount of data written. If the buffer
5654 * cannot contain the data, the function yields. The function returns -1
5655 * if the channel is closed.
5656 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005657__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005658{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005659 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005660 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005661 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005662 struct htx *htx = htx_from_buf(&res->buf);
5663 const char *data;
5664 size_t len;
5665 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5666 int max;
5667
Christopher Faulet9060fc02019-07-03 11:39:30 +02005668 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005669 if (!max)
5670 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005671
5672 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5673
5674 /* Get the max amount of data which can write as input in the channel. */
5675 if (max > (len - l))
5676 max = len - l;
5677
5678 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005679 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005680 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005681
5682 /* update counters. */
5683 l += max;
5684 lua_pop(L, 1);
5685 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005686
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005687 /* If some data is not send, declares the situation to the
5688 * applet, and returns a yield.
5689 */
5690 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005691 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005692 htx_to_buf(htx, &res->buf);
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005693 sc_need_room(sc, channel_recv_max(res) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005694 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005695 }
5696
Christopher Fauleta2097962019-07-15 16:25:33 +02005697 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005698 return 1;
5699}
5700
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005701/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005702 * yield the LUA process, and resume it without checking the
5703 * input arguments.
5704 */
5705__LJMP static int hlua_applet_http_send(lua_State *L)
5706{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005707 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005708 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005709
5710 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005711 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005712 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5713 WILL_LJMP(lua_error(L));
5714 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005715
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005716 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005717 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005718
Christopher Fauleta2097962019-07-15 16:25:33 +02005719 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005720}
5721
5722__LJMP static int hlua_applet_http_addheader(lua_State *L)
5723{
5724 const char *name;
5725 int ret;
5726
5727 MAY_LJMP(hlua_checkapplet_http(L, 1));
5728 name = MAY_LJMP(luaL_checkstring(L, 2));
5729 MAY_LJMP(luaL_checkstring(L, 3));
5730
5731 /* Push in the stack the "response" entry. */
5732 ret = lua_getfield(L, 1, "response");
5733 if (ret != LUA_TTABLE) {
5734 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5735 "is expected as an array. %s found", lua_typename(L, ret));
5736 WILL_LJMP(lua_error(L));
5737 }
5738
5739 /* check if the header is already registered if it is not
5740 * the case, register it.
5741 */
5742 ret = lua_getfield(L, -1, name);
5743 if (ret == LUA_TNIL) {
5744
5745 /* Entry not found. */
5746 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5747
5748 /* Insert the new header name in the array in the top of the stack.
5749 * It left the new array in the top of the stack.
5750 */
5751 lua_newtable(L);
5752 lua_pushvalue(L, 2);
5753 lua_pushvalue(L, -2);
5754 lua_settable(L, -4);
5755
5756 } else if (ret != LUA_TTABLE) {
5757
5758 /* corruption error. */
5759 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5760 "is expected as an array. %s found", name, lua_typename(L, ret));
5761 WILL_LJMP(lua_error(L));
5762 }
5763
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005764 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005765 * the header value as new entry.
5766 */
5767 lua_pushvalue(L, 3);
5768 ret = lua_rawlen(L, -2);
5769 lua_rawseti(L, -2, ret + 1);
5770 lua_pushboolean(L, 1);
5771 return 1;
5772}
5773
5774__LJMP static int hlua_applet_http_status(lua_State *L)
5775{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005776 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005777 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005778 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005779 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005780
5781 if (status < 100 || status > 599) {
5782 lua_pushboolean(L, 0);
5783 return 1;
5784 }
5785
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005786 http_ctx->status = status;
5787 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005788 lua_pushboolean(L, 1);
5789 return 1;
5790}
5791
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005792
Christopher Fauleta2097962019-07-15 16:25:33 +02005793__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005794{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005795 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005796 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005797 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005798 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005799 struct htx *htx;
5800 struct htx_sl *sl;
5801 struct h1m h1m;
5802 const char *status, *reason;
5803 const char *name, *value;
5804 size_t nlen, vlen;
5805 unsigned int flags;
5806
5807 /* Send the message at once. */
5808 htx = htx_from_buf(&res->buf);
5809 h1m_init_res(&h1m);
5810
5811 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005812 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5813 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005814 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005815 reason = http_get_reason(http_ctx->status);
5816 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005817 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5818 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5819 }
5820 else {
5821 flags = HTX_SL_F_IS_RESP;
5822 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5823 }
5824 if (!sl) {
5825 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005826 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005827 WILL_LJMP(lua_error(L));
5828 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005829 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005830
5831 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005832 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5833 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005834 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005835 WILL_LJMP(lua_error(L));
5836 }
5837
5838 /* Browse the list of headers. */
5839 lua_pushnil(L);
5840 while(lua_next(L, -2) != 0) {
5841 /* We expect a string as -2. */
5842 if (lua_type(L, -2) != LUA_TSTRING) {
5843 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005844 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005845 lua_typename(L, lua_type(L, -2)));
5846 WILL_LJMP(lua_error(L));
5847 }
5848 name = lua_tolstring(L, -2, &nlen);
5849
5850 /* We expect an array as -1. */
5851 if (lua_type(L, -1) != LUA_TTABLE) {
5852 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 +02005853 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005854 name,
5855 lua_typename(L, lua_type(L, -1)));
5856 WILL_LJMP(lua_error(L));
5857 }
5858
5859 /* Browse the table who is on the top of the stack. */
5860 lua_pushnil(L);
5861 while(lua_next(L, -2) != 0) {
5862 int id;
5863
5864 /* We expect a number as -2. */
5865 if (lua_type(L, -2) != LUA_TNUMBER) {
5866 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 +02005867 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005868 name,
5869 lua_typename(L, lua_type(L, -2)));
5870 WILL_LJMP(lua_error(L));
5871 }
5872 id = lua_tointeger(L, -2);
5873
5874 /* We expect a string as -2. */
5875 if (lua_type(L, -1) != LUA_TSTRING) {
5876 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 +02005877 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005878 name, id,
5879 lua_typename(L, lua_type(L, -1)));
5880 WILL_LJMP(lua_error(L));
5881 }
5882 value = lua_tolstring(L, -1, &vlen);
5883
5884 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005885 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5886 int ret;
5887
5888 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5889 if (ret < 0) {
5890 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5891 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5892 name);
5893 WILL_LJMP(lua_error(L));
5894 }
5895 else if (ret == 0)
5896 goto next; /* Skip it */
5897 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005898 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5899 struct ist v = ist2(value, vlen);
5900 int ret;
5901
5902 ret = h1_parse_cont_len_header(&h1m, &v);
5903 if (ret < 0) {
5904 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005905 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005906 name);
5907 WILL_LJMP(lua_error(L));
5908 }
5909 else if (ret == 0)
5910 goto next; /* Skip it */
5911 }
5912
5913 /* Add a new header */
5914 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5915 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005916 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005917 name);
5918 WILL_LJMP(lua_error(L));
5919 }
5920 next:
5921 /* Remove the array from the stack, and get next element with a remaining string. */
5922 lua_pop(L, 1);
5923 }
5924
5925 /* Remove the array from the stack, and get next element with a remaining string. */
5926 lua_pop(L, 1);
5927 }
5928
5929 if (h1m.flags & H1_MF_CHNK)
5930 h1m.flags &= ~H1_MF_CLEN;
5931 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5932 h1m.flags |= H1_MF_XFER_LEN;
5933
5934 /* Uset HTX start-line flags */
5935 if (h1m.flags & H1_MF_XFER_ENC)
5936 flags |= HTX_SL_F_XFER_ENC;
5937 if (h1m.flags & H1_MF_XFER_LEN) {
5938 flags |= HTX_SL_F_XFER_LEN;
5939 if (h1m.flags & H1_MF_CHNK)
5940 flags |= HTX_SL_F_CHNK;
5941 else if (h1m.flags & H1_MF_CLEN)
5942 flags |= HTX_SL_F_CLEN;
5943 if (h1m.body_len == 0)
5944 flags |= HTX_SL_F_BODYLESS;
5945 }
5946 sl->flags |= flags;
5947
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005948 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005949 * and the status code implies the presence of a message body, we must
5950 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005951 * for the keepalive compliance. If the applet announces a transfer-encoding
5952 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005953 */
5954 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005955 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005956 /* Add a new header */
5957 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5958 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5959 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005960 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005961 WILL_LJMP(lua_error(L));
5962 }
5963 }
5964
5965 /* Finalize headers. */
5966 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5967 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005968 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005969 WILL_LJMP(lua_error(L));
5970 }
5971
5972 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5973 b_reset(&res->buf);
5974 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5975 WILL_LJMP(lua_error(L));
5976 }
5977
5978 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005979 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005980
5981 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005982 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005983 return 0;
5984
5985}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005986/* We will build the status line and the headers of the HTTP response.
5987 * We will try send at once if its not possible, we give back the hand
5988 * waiting for more room.
5989 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005990__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005991{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005992 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005993 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005994 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005995
5996 if (co_data(res)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005997 sc_need_room(sc, -1);
Christopher Fauleta2097962019-07-15 16:25:33 +02005998 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005999 }
Christopher Fauleta2097962019-07-15 16:25:33 +02006000 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006001}
6002
6003
Christopher Fauleta2097962019-07-15 16:25:33 +02006004__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006005{
Christopher Fauleta2097962019-07-15 16:25:33 +02006006 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006007}
6008
Christopher Fauleta2097962019-07-15 16:25:33 +02006009/*
6010 *
6011 *
6012 * Class HTTP
6013 *
6014 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006015 */
Christopher Fauleta2097962019-07-15 16:25:33 +02006016
6017/* Returns a struct hlua_txn if the stack entry "ud" is
6018 * a class stream, otherwise it throws an error.
6019 */
6020__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006021{
Christopher Fauleta2097962019-07-15 16:25:33 +02006022 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
6023}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006024
Christopher Fauleta2097962019-07-15 16:25:33 +02006025/* This function creates and push in the stack a HTTP object
6026 * according with a current TXN.
6027 */
6028static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
6029{
6030 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006031
Christopher Fauleta2097962019-07-15 16:25:33 +02006032 /* Check stack size. */
6033 if (!lua_checkstack(L, 3))
6034 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006035
Christopher Fauleta2097962019-07-15 16:25:33 +02006036 /* Create the object: obj[0] = userdata.
6037 * Note that the base of the Converters object is the
6038 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006039 */
Christopher Fauleta2097962019-07-15 16:25:33 +02006040 lua_newtable(L);
6041 htxn = lua_newuserdata(L, sizeof(*htxn));
6042 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006043
6044 htxn->s = txn->s;
6045 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02006046 htxn->dir = txn->dir;
6047 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006048
6049 /* Pop a class stream metatable and affect it to the table. */
6050 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
6051 lua_setmetatable(L, -2);
6052
6053 return 1;
6054}
6055
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006056/* This function creates and returns an array containing the status-line
6057 * elements. This function does not fails.
6058 */
6059__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
6060{
6061 /* Create the table. */
6062 lua_newtable(L);
6063
6064 if (sl->flags & HTX_SL_F_IS_RESP) {
6065 lua_pushstring(L, "version");
6066 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
6067 lua_settable(L, -3);
6068 lua_pushstring(L, "code");
6069 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
6070 lua_settable(L, -3);
6071 lua_pushstring(L, "reason");
6072 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
6073 lua_settable(L, -3);
6074 }
6075 else {
6076 lua_pushstring(L, "method");
6077 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
6078 lua_settable(L, -3);
6079 lua_pushstring(L, "uri");
6080 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
6081 lua_settable(L, -3);
6082 lua_pushstring(L, "version");
6083 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
6084 lua_settable(L, -3);
6085 }
6086 return 1;
6087}
6088
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006089/* This function creates ans returns an array of HTTP headers.
6090 * This function does not fails. It is used as wrapper with the
6091 * 2 following functions.
6092 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006093__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006094{
Christopher Fauleta2097962019-07-15 16:25:33 +02006095 struct htx *htx;
6096 int32_t pos;
6097
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006098 /* Create the table. */
6099 lua_newtable(L);
6100
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006101
Christopher Fauleta2097962019-07-15 16:25:33 +02006102 htx = htxbuf(&msg->chn->buf);
6103 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
6104 struct htx_blk *blk = htx_get_blk(htx, pos);
6105 enum htx_blk_type type = htx_get_blk_type(blk);
6106 struct ist n, v;
6107 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006108
Christopher Fauleta2097962019-07-15 16:25:33 +02006109 if (type == HTX_BLK_HDR) {
6110 n = htx_get_blk_name(htx,blk);
6111 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01006112 }
Christopher Fauleta2097962019-07-15 16:25:33 +02006113 else if (type == HTX_BLK_EOH)
6114 break;
6115 else
6116 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006117
Christopher Fauleta2097962019-07-15 16:25:33 +02006118 /* Check for existing entry:
6119 * assume that the table is on the top of the stack, and
6120 * push the key in the stack, the function lua_gettable()
6121 * perform the lookup.
6122 */
6123 lua_pushlstring(L, n.ptr, n.len);
6124 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01006125
Christopher Fauleta2097962019-07-15 16:25:33 +02006126 switch (lua_type(L, -1)) {
6127 case LUA_TNIL:
6128 /* Table not found, create it. */
6129 lua_pop(L, 1); /* remove the nil value. */
6130 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
6131 lua_newtable(L); /* create and push empty table. */
6132 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
6133 lua_rawseti(L, -2, 0); /* index header value (pop it). */
6134 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01006135 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006136
Christopher Fauleta2097962019-07-15 16:25:33 +02006137 case LUA_TTABLE:
6138 /* Entry found: push the value in the table. */
6139 len = lua_rawlen(L, -1);
6140 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
6141 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
6142 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
6143 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006144
Christopher Fauleta2097962019-07-15 16:25:33 +02006145 default:
6146 /* Other cases are errors. */
6147 hlua_pusherror(L, "internal error during the parsing of headers.");
6148 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006149 }
6150 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006151 return 1;
6152}
6153
6154__LJMP static int hlua_http_req_get_headers(lua_State *L)
6155{
6156 struct hlua_txn *htxn;
6157
6158 MAY_LJMP(check_args(L, 1, "req_get_headers"));
6159 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6160
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006161 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006162 WILL_LJMP(lua_error(L));
6163
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006164 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006165}
6166
6167__LJMP static int hlua_http_res_get_headers(lua_State *L)
6168{
6169 struct hlua_txn *htxn;
6170
6171 MAY_LJMP(check_args(L, 1, "res_get_headers"));
6172 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6173
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006174 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006175 WILL_LJMP(lua_error(L));
6176
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006177 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006178}
6179
6180/* This function replace full header, or just a value in
6181 * the request or in the response. It is a wrapper fir the
6182 * 4 following functions.
6183 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006184__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006185{
6186 size_t name_len;
6187 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6188 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
6189 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02006190 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02006191 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006192
Dragan Dosen26743032019-04-30 15:54:36 +02006193 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006194 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
6195
Christopher Fauleta2097962019-07-15 16:25:33 +02006196 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006197 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02006198 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006199 return 0;
6200}
6201
6202__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
6203{
6204 struct hlua_txn *htxn;
6205
6206 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6207 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6208
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006209 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006210 WILL_LJMP(lua_error(L));
6211
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006212 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006213}
6214
6215__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
6216{
6217 struct hlua_txn *htxn;
6218
6219 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
6220 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6221
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006222 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006223 WILL_LJMP(lua_error(L));
6224
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006225 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006226}
6227
6228__LJMP static int hlua_http_req_rep_val(lua_State *L)
6229{
6230 struct hlua_txn *htxn;
6231
6232 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6233 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6234
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006235 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006236 WILL_LJMP(lua_error(L));
6237
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006238 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006239}
6240
6241__LJMP static int hlua_http_res_rep_val(lua_State *L)
6242{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006243 struct hlua_txn *htxn;
6244
6245 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6246 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6247
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006248 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006249 WILL_LJMP(lua_error(L));
6250
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006251 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006252}
6253
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006254/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006255 * It is a wrapper for the 2 following functions.
6256 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006257__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006258{
6259 size_t len;
6260 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006261 struct htx *htx = htxbuf(&msg->chn->buf);
6262 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006263
Christopher Fauleta2097962019-07-15 16:25:33 +02006264 ctx.blk = NULL;
6265 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6266 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006267 return 0;
6268}
6269
6270__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6271{
6272 struct hlua_txn *htxn;
6273
6274 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6275 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6276
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006277 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006278 WILL_LJMP(lua_error(L));
6279
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006280 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006281}
6282
6283__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6284{
6285 struct hlua_txn *htxn;
6286
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006287 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006288 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6289
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006290 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006291 WILL_LJMP(lua_error(L));
6292
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006293 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006294}
6295
6296/* This function adds an header. It is a wrapper used by
6297 * the 2 following functions.
6298 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006299__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006300{
6301 size_t name_len;
6302 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6303 size_t value_len;
6304 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006305 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006306
Christopher Fauleta2097962019-07-15 16:25:33 +02006307 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6308 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006309 return 0;
6310}
6311
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006312__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6313{
6314 struct hlua_txn *htxn;
6315
6316 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6317 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6318
6319 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6320 WILL_LJMP(lua_error(L));
6321
6322 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6323}
6324
6325__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6326{
6327 struct hlua_txn *htxn;
6328
6329 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6330 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6331
6332 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6333 WILL_LJMP(lua_error(L));
6334
6335 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6336}
6337
6338static int hlua_http_req_set_hdr(lua_State *L)
6339{
6340 struct hlua_txn *htxn;
6341
6342 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6343 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6344
6345 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6346 WILL_LJMP(lua_error(L));
6347
6348 hlua_http_del_hdr(L, &htxn->s->txn->req);
6349 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6350}
6351
6352static int hlua_http_res_set_hdr(lua_State *L)
6353{
6354 struct hlua_txn *htxn;
6355
6356 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6357 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6358
6359 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6360 WILL_LJMP(lua_error(L));
6361
6362 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6363 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6364}
6365
6366/* This function set the method. */
6367static int hlua_http_req_set_meth(lua_State *L)
6368{
6369 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6370 size_t name_len;
6371 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6372
6373 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6374 WILL_LJMP(lua_error(L));
6375
6376 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6377 return 1;
6378}
6379
6380/* This function set the method. */
6381static int hlua_http_req_set_path(lua_State *L)
6382{
6383 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6384 size_t name_len;
6385 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6386
6387 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6388 WILL_LJMP(lua_error(L));
6389
6390 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6391 return 1;
6392}
6393
6394/* This function set the query-string. */
6395static int hlua_http_req_set_query(lua_State *L)
6396{
6397 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6398 size_t name_len;
6399 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6400
6401 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6402 WILL_LJMP(lua_error(L));
6403
6404 /* Check length. */
6405 if (name_len > trash.size - 1) {
6406 lua_pushboolean(L, 0);
6407 return 1;
6408 }
6409
6410 /* Add the mark question as prefix. */
6411 chunk_reset(&trash);
6412 trash.area[trash.data++] = '?';
6413 memcpy(trash.area + trash.data, name, name_len);
6414 trash.data += name_len;
6415
6416 lua_pushboolean(L,
6417 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6418 return 1;
6419}
6420
6421/* This function set the uri. */
6422static int hlua_http_req_set_uri(lua_State *L)
6423{
6424 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6425 size_t name_len;
6426 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6427
6428 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6429 WILL_LJMP(lua_error(L));
6430
6431 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6432 return 1;
6433}
6434
6435/* This function set the response code & optionally reason. */
6436static int hlua_http_res_set_status(lua_State *L)
6437{
6438 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6439 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6440 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6441 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6442
6443 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6444 WILL_LJMP(lua_error(L));
6445
6446 http_res_set_status(code, reason, htxn->s);
6447 return 0;
6448}
6449
6450/*
6451 *
6452 *
6453 * Class HTTPMessage
6454 *
6455 *
6456 */
6457
6458/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6459 * otherwise it throws an error.
6460 */
6461__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6462{
6463 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6464}
6465
6466/* Creates and pushes on the stack a HTTP object according with a current TXN.
6467 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006468static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006469{
6470 /* Check stack size. */
6471 if (!lua_checkstack(L, 3))
6472 return 0;
6473
6474 lua_newtable(L);
6475 lua_pushlightuserdata(L, msg);
6476 lua_rawseti(L, -2, 0);
6477
6478 /* Create the "channel" field that contains the request channel object. */
6479 lua_pushstring(L, "channel");
6480 if (!hlua_channel_new(L, msg->chn))
6481 return 0;
6482 lua_rawset(L, -3);
6483
6484 /* Pop a class stream metatable and affect it to the table. */
6485 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6486 lua_setmetatable(L, -2);
6487
6488 return 1;
6489}
6490
6491/* Helper function returning a filter attached to the HTTP message at the
6492 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006493 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006494 * filled with output and input length respectively.
6495 */
6496static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6497{
6498 struct channel *chn = msg->chn;
6499 struct htx *htx = htxbuf(&chn->buf);
6500 struct filter *filter = NULL;
6501
6502 *offset = co_data(msg->chn);
6503 *len = htx->data - co_data(msg->chn);
6504
6505 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6506 filter = lua_touserdata (L, -1);
6507 if (msg->msg_state >= HTTP_MSG_DATA) {
6508 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6509
6510 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6511 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6512 }
6513 }
6514
6515 lua_pop(L, 1);
6516 return filter;
6517}
6518
6519/* Returns true if the channel attached to the HTTP message is the response
6520 * channel.
6521 */
6522__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6523{
6524 struct http_msg *msg;
6525
6526 MAY_LJMP(check_args(L, 1, "is_resp"));
6527 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6528
6529 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6530 return 1;
6531}
6532
6533/* Returns an array containing the elements status-line of the HTTP message. It relies
6534 * on hlua_http_get_stline().
6535 */
6536__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6537{
6538 struct http_msg *msg;
6539 struct htx *htx;
6540 struct htx_sl *sl;
6541
6542 MAY_LJMP(check_args(L, 1, "get_stline"));
6543 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6544
6545 if (msg->msg_state > HTTP_MSG_BODY)
6546 WILL_LJMP(lua_error(L));
6547
6548 htx = htxbuf(&msg->chn->buf);
6549 sl = http_get_stline(htx);
6550 if (!sl)
6551 return 0;
6552 return hlua_http_get_stline(L, sl);
6553}
6554
6555/* Returns an array containing all headers of the HTTP message. it relies on
6556 * hlua_http_get_headers().
6557 */
6558__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6559{
6560 struct http_msg *msg;
6561
6562 MAY_LJMP(check_args(L, 1, "get_headers"));
6563 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6564
6565 if (msg->msg_state > HTTP_MSG_BODY)
6566 WILL_LJMP(lua_error(L));
6567
6568 return hlua_http_get_headers(L, msg);
6569}
6570
6571/* Deletes all occurrences of an header in the HTTP message matching on its
6572 * name. It relies on hlua_http_del_hdr().
6573 */
6574__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6575{
6576 struct http_msg *msg;
6577
6578 MAY_LJMP(check_args(L, 2, "del_header"));
6579 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6580
6581 if (msg->msg_state > HTTP_MSG_BODY)
6582 WILL_LJMP(lua_error(L));
6583
6584 return hlua_http_del_hdr(L, msg);
6585}
6586
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006587/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006588 * message given its name against a regex and replaces it if it matches. It
6589 * relies on hlua_http_rep_hdr().
6590 */
6591__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6592{
6593 struct http_msg *msg;
6594
6595 MAY_LJMP(check_args(L, 4, "rep_header"));
6596 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6597
6598 if (msg->msg_state > HTTP_MSG_BODY)
6599 WILL_LJMP(lua_error(L));
6600
6601 return hlua_http_rep_hdr(L, msg, 1);
6602}
6603
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006604/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006605 * message given its name against a regex and replaces it if it matches. It
6606 * relies on hlua_http_rep_hdr().
6607 */
6608__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6609{
6610 struct http_msg *msg;
6611
6612 MAY_LJMP(check_args(L, 4, "rep_value"));
6613 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6614
6615 if (msg->msg_state > HTTP_MSG_BODY)
6616 WILL_LJMP(lua_error(L));
6617
6618 return hlua_http_rep_hdr(L, msg, 0);
6619}
6620
6621/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6622__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6623{
6624 struct http_msg *msg;
6625
6626 MAY_LJMP(check_args(L, 3, "add_header"));
6627 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6628
6629 if (msg->msg_state > HTTP_MSG_BODY)
6630 WILL_LJMP(lua_error(L));
6631
6632 return hlua_http_add_hdr(L, msg);
6633}
6634
6635/* Add an header in the HTTP message removing existing headers with the same
6636 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6637 */
6638__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6639{
6640 struct http_msg *msg;
6641
6642 MAY_LJMP(check_args(L, 3, "set_header"));
6643 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6644
6645 if (msg->msg_state > HTTP_MSG_BODY)
6646 WILL_LJMP(lua_error(L));
6647
6648 hlua_http_del_hdr(L, msg);
6649 return hlua_http_add_hdr(L, msg);
6650}
6651
6652/* Rewrites the request method. It relies on http_req_replace_stline(). */
6653__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6654{
6655 struct stream *s;
6656 struct http_msg *msg;
6657 const char *name;
6658 size_t name_len;
6659
6660 MAY_LJMP(check_args(L, 2, "set_method"));
6661 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6662 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6663
6664 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6665 WILL_LJMP(lua_error(L));
6666
6667 s = chn_strm(msg->chn);
6668 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6669 return 1;
6670}
6671
6672/* Rewrites the request path. It relies on http_req_replace_stline(). */
6673__LJMP static int hlua_http_msg_set_path(lua_State *L)
6674{
6675 struct stream *s;
6676 struct http_msg *msg;
6677 const char *name;
6678 size_t name_len;
6679
6680 MAY_LJMP(check_args(L, 2, "set_path"));
6681 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6682 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6683
6684 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6685 WILL_LJMP(lua_error(L));
6686
6687 s = chn_strm(msg->chn);
6688 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6689 return 1;
6690}
6691
6692/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6693__LJMP static int hlua_http_msg_set_query(lua_State *L)
6694{
6695 struct stream *s;
6696 struct http_msg *msg;
6697 const char *name;
6698 size_t name_len;
6699
6700 MAY_LJMP(check_args(L, 2, "set_query"));
6701 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6702 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6703
6704 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6705 WILL_LJMP(lua_error(L));
6706
6707 /* Check length. */
6708 if (name_len > trash.size - 1) {
6709 lua_pushboolean(L, 0);
6710 return 1;
6711 }
6712
6713 /* Add the mark question as prefix. */
6714 chunk_reset(&trash);
6715 trash.area[trash.data++] = '?';
6716 memcpy(trash.area + trash.data, name, name_len);
6717 trash.data += name_len;
6718
6719 s = chn_strm(msg->chn);
6720 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6721 return 1;
6722}
6723
6724/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6725__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6726{
6727 struct stream *s;
6728 struct http_msg *msg;
6729 const char *name;
6730 size_t name_len;
6731
6732 MAY_LJMP(check_args(L, 2, "set_uri"));
6733 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6734 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6735
6736 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6737 WILL_LJMP(lua_error(L));
6738
6739 s = chn_strm(msg->chn);
6740 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6741 return 1;
6742}
6743
6744/* Rewrites the response status code. It relies on http_res_set_status(). */
6745__LJMP static int hlua_http_msg_set_status(lua_State *L)
6746{
6747 struct http_msg *msg;
6748 unsigned int code;
6749 const char *reason;
6750 size_t reason_len;
6751
6752 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6753 code = MAY_LJMP(luaL_checkinteger(L, 2));
6754 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6755
6756 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6757 WILL_LJMP(lua_error(L));
6758
6759 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6760 return 1;
6761}
6762
6763/* Returns true if the HTTP message is full. */
6764__LJMP static int hlua_http_msg_is_full(lua_State *L)
6765{
6766 struct http_msg *msg;
6767
6768 MAY_LJMP(check_args(L, 1, "is_full"));
6769 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6770 lua_pushboolean(L, channel_full(msg->chn, 0));
6771 return 1;
6772}
6773
6774/* Returns true if the HTTP message may still receive data. */
6775__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6776{
6777 struct http_msg *msg;
6778 struct htx *htx;
6779
6780 MAY_LJMP(check_args(L, 1, "may_recv"));
6781 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6782 htx = htxbuf(&msg->chn->buf);
6783 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6784 return 1;
6785}
6786
6787/* Returns true if the HTTP message EOM was received */
6788__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6789{
6790 struct http_msg *msg;
6791 struct htx *htx;
6792
6793 MAY_LJMP(check_args(L, 1, "may_recv"));
6794 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6795 htx = htxbuf(&msg->chn->buf);
6796 lua_pushboolean(L, !htx_expect_more(htx));
6797 return 1;
6798}
6799
6800/* Returns the number of bytes available in the input side of the HTTP
6801 * message. This function never fails.
6802 */
6803__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6804{
6805 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006806 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006807
6808 MAY_LJMP(check_args(L, 1, "input"));
6809 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006810 hlua_http_msg_filter(L, 1, msg, &output, &input);
6811 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006812 return 1;
6813}
6814
6815/* Returns the number of bytes available in the output side of the HTTP
6816 * message. This function never fails.
6817 */
6818__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6819{
6820 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006821 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006822
6823 MAY_LJMP(check_args(L, 1, "output"));
6824 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006825 hlua_http_msg_filter(L, 1, msg, &output, &input);
6826 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006827 return 1;
6828}
6829
6830/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6831 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006832 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006833 * block. This function is called during the payload filtering, so the headers
6834 * are already scheduled for output (from the filter point of view).
6835 */
6836static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6837{
6838 struct htx *htx = htxbuf(&msg->chn->buf);
6839 struct htx_blk *blk;
6840 struct htx_ret htxret;
6841 luaL_Buffer b;
6842 int ret = 0;
6843
6844 luaL_buffinit(L, &b);
6845 htxret = htx_find_offset(htx, offset);
6846 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6847 enum htx_blk_type type = htx_get_blk_type(blk);
6848 struct ist v;
6849
6850 switch (type) {
6851 case HTX_BLK_UNUSED:
6852 break;
6853
6854 case HTX_BLK_DATA:
6855 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006856 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006857 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006858
6859 luaL_addlstring(&b, v.ptr, v.len);
6860 ret += v.len;
6861 break;
6862
6863 default:
vishnu0af4bd72021-10-24 06:46:24 +05306864 if (!ret)
6865 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006866 goto end;
6867 }
6868 offset = 0;
6869 }
6870
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006871end:
vishnu0af4bd72021-10-24 06:46:24 +05306872 if (!ret && (htx->flags & HTX_FL_EOM))
6873 goto no_data;
6874 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006875 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306876
6877 no_data:
6878 /* Remove the empty string and push nil on the stack */
6879 lua_pop(L, 1);
6880 lua_pushnil(L);
6881 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006882}
6883
6884/* Copies the string <str> to the HTTP message <msg> at the offset
6885 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006886 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006887 * the filter context.
6888 */
6889static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6890{
6891 struct htx *htx = htx_from_buf(&msg->chn->buf);
6892 struct htx_ret htxret;
6893 int /*max, */ret = 0;
6894
6895 /* Nothing to do, just return */
6896 if (unlikely(istlen(str) == 0))
6897 goto end;
6898
6899 if (istlen(str) > htx_free_data_space(htx)) {
6900 ret = -1;
6901 goto end;
6902 }
6903
6904 htxret = htx_find_offset(htx, offset);
6905 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6906 if (!htx_add_last_data(htx, str))
6907 goto end;
6908 }
6909 else {
6910 struct ist v = htx_get_blk_value(htx, htxret.blk);
6911 v.ptr += htxret.ret;
6912 v.len = 0;
6913 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6914 goto end;
6915 }
6916 ret = str.len;
6917 if (ret) {
6918 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6919 flt_update_offsets(filter, msg->chn, ret);
6920 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6921 }
6922
6923 end:
6924 htx_to_buf(htx, &msg->chn->buf);
6925 return ret;
6926}
6927
6928/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6929 * position <offset>. It stops on the first non-DATA HTX block. This function is
6930 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006931 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006932 * update the filter context.
6933 */
6934static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6935{
6936 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6937 struct htx *htx = htx_from_buf(&msg->chn->buf);
6938 struct htx_blk *blk;
6939 struct htx_ret htxret;
6940 size_t ret = 0;
6941
6942 /* Be sure <len> is always the amount of DATA to remove */
6943 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006944 /* When htx tail type == HTX_BLK_DATA, no need to take care
6945 * of special blocks like HTX_BLK_EOT.
6946 * We simply truncate after offset
6947 * (truncate targeted blk and discard the following ones)
6948 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006949 htx_truncate(htx, offset);
6950 ret = len;
6951 goto end;
6952 }
6953
6954 htxret = htx_find_offset(htx, offset);
6955 blk = htxret.blk;
6956 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006957 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006958 struct ist v;
6959
6960 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6961 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006962
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006963 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006964 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006965
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006966 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006967 /* trimming data in blk: discard everything after the offset
6968 * (replace 'v' with 'IST_NULL')
6969 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006970 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006971 if (blk && v.len < len) {
6972 /* In this case, caller wants to keep removing data,
6973 * but we need to spare current blk
6974 * because it was already trimmed
6975 */
6976 blk = htx_get_next_blk(htx, blk);
6977 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006978 len -= v.len;
6979 ret += v.len;
6980 }
6981
6982
6983 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006984 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006985 enum htx_blk_type type = htx_get_blk_type(blk);
6986 uint32_t sz = htx_get_blksz(blk);
6987
6988 switch (type) {
6989 case HTX_BLK_UNUSED:
6990 break;
6991
6992 case HTX_BLK_DATA:
6993 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006994 /* don't discard whole blk, only part of it
6995 * (from the beginning)
6996 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006997 htx_cut_data_blk(htx, blk, len);
6998 ret += len;
6999 goto end;
7000 }
7001 break;
7002
7003 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02007004 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007005 goto end;
7006 }
7007
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007008 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007009 len -= sz;
7010 ret += sz;
7011 blk = htx_remove_blk(htx, blk);
7012 }
7013
7014end:
7015 flt_update_offsets(filter, msg->chn, -ret);
7016 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7017 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
7018 * to loose the EOM flag if the message is empty.
7019 */
7020}
7021
7022/* Copies input data found in an HTTP message. Unlike the channel function used
7023 * to duplicate raw data, this one can only be called inside a filter, from
7024 * http_payload callback. So it cannot yield. An exception is returned if it is
7025 * called from another callback. If nothing was copied, a nil value is pushed on
7026 * the stack.
7027 */
7028__LJMP static int hlua_http_msg_get_body(lua_State *L)
7029{
7030 struct http_msg *msg;
7031 struct filter *filter;
7032 size_t output, input;
7033 int offset, len;
7034
7035 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
7036 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
7037 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7038
7039 if (msg->msg_state < HTTP_MSG_DATA)
7040 WILL_LJMP(lua_error(L));
7041
7042 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7043 if (!filter || !hlua_filter_from_payload(filter))
7044 WILL_LJMP(lua_error(L));
7045
7046 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
7047 lua_pushnil(L);
7048 return 1;
7049 }
7050
7051 offset = output;
7052 if (lua_gettop(L) > 1) {
7053 offset = MAY_LJMP(luaL_checkinteger(L, 2));
7054 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007055 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007056 offset += output;
7057 if (offset < output || offset > input + output) {
7058 lua_pushfstring(L, "offset out of range.");
7059 WILL_LJMP(lua_error(L));
7060 }
7061 }
7062 len = output + input - offset;
7063 if (lua_gettop(L) == 3) {
7064 len = MAY_LJMP(luaL_checkinteger(L, 3));
7065 if (!len)
7066 goto dup;
7067 if (len == -1)
7068 len = global.tune.bufsize;
7069 if (len < 0) {
7070 lua_pushfstring(L, "length out of range.");
7071 WILL_LJMP(lua_error(L));
7072 }
7073 }
7074
7075 dup:
7076 _hlua_http_msg_dup(msg, L, offset, len);
7077 return 1;
7078}
7079
7080/* Appends a string to the HTTP message, after all existing DATA blocks but
7081 * before the trailers, if any. It returns the amount of data written or -1 if
7082 * nothing was copied. Unlike the channel function used to append data, this one
7083 * can only be called inside a filter, from http_payload callback. So it cannot
7084 * yield. An exception is returned if it is called from another callback.
7085 */
7086__LJMP static int hlua_http_msg_append(lua_State *L)
7087{
7088 struct http_msg *msg;
7089 struct filter *filter;
7090 const char *str;
7091 size_t offset, len, sz;
7092 int ret;
7093
7094 MAY_LJMP(check_args(L, 2, "append"));
7095 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7096
7097 if (msg->msg_state < HTTP_MSG_DATA)
7098 WILL_LJMP(lua_error(L));
7099
7100 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7101 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7102 if (!filter || !hlua_filter_from_payload(filter))
7103 WILL_LJMP(lua_error(L));
7104
7105 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
7106 lua_pushinteger(L, ret);
7107 return 1;
7108}
7109
7110/* Prepends a string to the HTTP message, before all existing DATA blocks. It
7111 * returns the amount of data written or -1 if nothing was copied. Unlike the
7112 * channel function used to prepend data, this one can only be called inside a
7113 * filter, from http_payload callback. So it cannot yield. An exception is
7114 * returned if it is called from another callback.
7115 */
7116__LJMP static int hlua_http_msg_prepend(lua_State *L)
7117{
7118 struct http_msg *msg;
7119 struct filter *filter;
7120 const char *str;
7121 size_t offset, len, sz;
7122 int ret;
7123
7124 MAY_LJMP(check_args(L, 2, "prepend"));
7125 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007126
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007127 if (msg->msg_state < HTTP_MSG_DATA)
7128 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007129
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007130 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7131 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7132 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007133 WILL_LJMP(lua_error(L));
7134
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007135 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7136 lua_pushinteger(L, ret);
7137 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007138}
7139
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007140/* Inserts a string to the HTTP message at a given offset. By default the string
7141 * is appended at the end of DATA blocks. It returns the amount of data written
7142 * or -1 if nothing was copied. Unlike the channel function used to insert data,
7143 * this one can only be called inside a filter, from http_payload callback. So
7144 * it cannot yield. An exception is returned if it is called from another
7145 * callback.
7146 */
7147__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007148{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007149 struct http_msg *msg;
7150 struct filter *filter;
7151 const char *str;
7152 size_t input, output, sz;
7153 int offset;
7154 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007155
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007156 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
7157 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007158 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007159
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007160 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007161 WILL_LJMP(lua_error(L));
7162
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007163 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007164 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007165 if (!filter || !hlua_filter_from_payload(filter))
7166 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007167
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007168 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007169 if (lua_gettop(L) > 2) {
7170 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7171 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007172 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007173 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007174 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007175 lua_pushfstring(L, "offset out of range.");
7176 WILL_LJMP(lua_error(L));
7177 }
7178 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007179
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007180 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7181 lua_pushinteger(L, ret);
7182 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007183}
7184
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007185/* Removes a given amount of data from the HTTP message at a given offset. By
7186 * default all DATA blocks are removed. It returns the amount of data
7187 * removed. Unlike the channel function used to remove data, this one can only
7188 * be called inside a filter, from http_payload callback. So it cannot yield. An
7189 * exception is returned if it is called from another callback.
7190 */
7191__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007192{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007193 struct http_msg *msg;
7194 struct filter *filter;
7195 size_t input, output;
7196 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007197
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007198 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00007199 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007200 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007201
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007202 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007203 WILL_LJMP(lua_error(L));
7204
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007205 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007206 if (!filter || !hlua_filter_from_payload(filter))
7207 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007208
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007209 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00007210 if (lua_gettop(L) > 1) {
7211 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007212 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007213 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007214 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007215 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007216 lua_pushfstring(L, "offset out of range.");
7217 WILL_LJMP(lua_error(L));
7218 }
7219 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007220
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007221 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00007222 if (lua_gettop(L) == 3) {
7223 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007224 if (!len)
7225 goto end;
7226 if (len == -1)
7227 len = output + input - offset;
7228 if (len < 0 || offset + len > output + input) {
7229 lua_pushfstring(L, "length out of range.");
7230 WILL_LJMP(lua_error(L));
7231 }
7232 }
7233
7234 _hlua_http_msg_delete(msg, filter, offset, len);
7235
7236 end:
7237 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007238 return 1;
7239}
7240
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007241/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007242 * all remaining data are removed, accordingly to the filter context. It returns
7243 * the amount of data written or -1 if nothing was copied. Unlike the channel
7244 * function used to replace data, this one can only be called inside a filter,
7245 * from http_payload callback. So it cannot yield. An exception is returned if
7246 * it is called from another callback.
7247 */
7248__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007249{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007250 struct http_msg *msg;
7251 struct filter *filter;
7252 struct htx *htx;
7253 const char *str;
7254 size_t input, output, sz;
7255 int offset, len;
7256 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007257
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007258 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7259 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7260 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7261
7262 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007263 WILL_LJMP(lua_error(L));
7264
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007265 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7266 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7267 if (!filter || !hlua_filter_from_payload(filter))
7268 WILL_LJMP(lua_error(L));
7269
7270 offset = output;
7271 if (lua_gettop(L) > 2) {
7272 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7273 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007274 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007275 offset += output;
7276 if (offset < output || offset > input + output) {
7277 lua_pushfstring(L, "offset out of range.");
7278 WILL_LJMP(lua_error(L));
7279 }
7280 }
7281
7282 len = output + input - offset;
7283 if (lua_gettop(L) == 4) {
7284 len = MAY_LJMP(luaL_checkinteger(L, 4));
7285 if (!len)
7286 goto set;
7287 if (len == -1)
7288 len = output + input - offset;
7289 if (len < 0 || offset + len > output + input) {
7290 lua_pushfstring(L, "length out of range.");
7291 WILL_LJMP(lua_error(L));
7292 }
7293 }
7294
7295 set:
7296 /* Be sure we can copied the string once input data will be removed. */
7297 htx = htx_from_buf(&msg->chn->buf);
7298 if (sz > htx_free_data_space(htx) + len)
7299 lua_pushinteger(L, -1);
7300 else {
7301 _hlua_http_msg_delete(msg, filter, offset, len);
7302 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7303 lua_pushinteger(L, ret);
7304 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007305 return 1;
7306}
7307
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007308/* Prepends data into an HTTP message and forward it, from the filter point of
7309 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7310 * the channel function used to send data, this one can only be called inside a
7311 * filter, from http_payload callback. So it cannot yield. An exception is
7312 * returned if it is called from another callback.
7313 */
7314__LJMP static int hlua_http_msg_send(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 struct htx *htx;
7319 const char *str;
7320 size_t offset, len, sz;
7321 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007322
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007323 MAY_LJMP(check_args(L, 2, "send"));
7324 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7325
7326 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007327 WILL_LJMP(lua_error(L));
7328
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007329 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7330 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7331 if (!filter || !hlua_filter_from_payload(filter))
7332 WILL_LJMP(lua_error(L));
7333
7334 /* Return an error if the channel's output is closed */
7335 if (unlikely(channel_output_closed(msg->chn))) {
7336 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007337 return 1;
7338 }
7339
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007340 htx = htx_from_buf(&msg->chn->buf);
7341 if (sz > htx_free_data_space(htx)) {
7342 lua_pushinteger(L, -1);
7343 return 1;
7344 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007345
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007346 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7347 if (ret > 0) {
7348 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7349
7350 FLT_OFF(filter, msg->chn) += ret;
7351 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7352 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7353 }
7354
7355 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007356 return 1;
7357}
7358
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007359/* Forwards a given amount of bytes. It return -1 if the channel's output is
7360 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7361 * channel function used to forward data, this one can only be called inside a
7362 * filter, from http_payload callback. So it cannot yield. An exception is
7363 * returned if it is called from another callback. All other functions deal with
7364 * DATA block, this one not.
7365*/
7366__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007367{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007368 struct http_msg *msg;
7369 struct filter *filter;
7370 size_t offset, len;
7371 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007372
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007373 MAY_LJMP(check_args(L, 2, "forward"));
7374 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7375
7376 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007377 WILL_LJMP(lua_error(L));
7378
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007379 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7380 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7381 if (!filter || !hlua_filter_from_payload(filter))
7382 WILL_LJMP(lua_error(L));
7383
7384 /* Nothing to do, just return */
7385 if (!fwd)
7386 goto end;
7387
7388 /* Return an error if the channel's output is closed */
7389 if (unlikely(channel_output_closed(msg->chn))) {
7390 ret = -1;
7391 goto end;
7392 }
7393
7394 ret = fwd;
7395 if (ret > len)
7396 ret = len;
7397
7398 if (ret) {
7399 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7400
7401 FLT_OFF(filter, msg->chn) += ret;
7402 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7403 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7404 }
7405
7406 end:
7407 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007408 return 1;
7409}
7410
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007411/* Set EOM flag on the HTX message.
7412 *
7413 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7414 * really know how to do without this feature.
7415 */
7416__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007417{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007418 struct http_msg *msg;
7419 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007420
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007421 MAY_LJMP(check_args(L, 1, "set_eom"));
7422 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7423 htx = htxbuf(&msg->chn->buf);
7424 htx->flags |= HTX_FL_EOM;
7425 return 0;
7426}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007427
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007428/* Unset EOM flag on the HTX message.
7429 *
7430 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7431 * really know how to do without this feature.
7432 */
7433__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7434{
7435 struct http_msg *msg;
7436 struct htx *htx;
7437
7438 MAY_LJMP(check_args(L, 1, "set_eom"));
7439 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7440 htx = htxbuf(&msg->chn->buf);
7441 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007442 return 0;
7443}
7444
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007445/*
7446 *
7447 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007448 * Class HTTPClient
7449 *
7450 *
7451 */
7452__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7453{
7454 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7455}
7456
William Lallemandf77f1de2021-09-28 19:10:38 +02007457
7458/* stops the httpclient and ask it to kill itself */
7459__LJMP static int hlua_httpclient_gc(lua_State *L)
7460{
7461 struct hlua_httpclient *hlua_hc;
7462
7463 MAY_LJMP(check_args(L, 1, "__gc"));
7464
7465 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7466
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007467 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7468 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007469 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007470 hlua_hc->hc = NULL;
7471 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007472
7473 return 0;
7474}
7475
7476
William Lallemand3956c4e2021-09-21 16:25:15 +02007477__LJMP static int hlua_httpclient_new(lua_State *L)
7478{
7479 struct hlua_httpclient *hlua_hc;
7480 struct hlua *hlua;
7481
7482 /* Get hlua struct, or NULL if we execute from main lua state */
7483 hlua = hlua_gethlua(L);
7484 if (!hlua)
7485 return 0;
7486
7487 /* Check stack size. */
7488 if (!lua_checkstack(L, 3)) {
7489 hlua_pusherror(L, "httpclient: full stack");
7490 goto err;
7491 }
7492 /* Create the object: obj[0] = userdata. */
7493 lua_newtable(L);
7494 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7495 lua_rawseti(L, -2, 0);
7496 memset(hlua_hc, 0, sizeof(*hlua_hc));
7497
7498 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7499 if (!hlua_hc->hc)
7500 goto err;
7501
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007502 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007503
William Lallemand3956c4e2021-09-21 16:25:15 +02007504 /* Pop a class stream metatable and affect it to the userdata. */
7505 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7506 lua_setmetatable(L, -2);
7507
7508 return 1;
7509
7510 err:
7511 WILL_LJMP(lua_error(L));
7512 return 0;
7513}
7514
7515
7516/*
7517 * Callback of the httpclient, this callback wakes the lua task up, once the
7518 * httpclient receives some data
7519 *
7520 */
7521
William Lallemandbd5739e2021-10-28 15:41:38 +02007522static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007523{
7524 struct hlua *hlua = hc->caller;
7525
7526 if (!hlua || !hlua->task)
7527 return;
7528
7529 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7530}
7531
7532/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007533 * Fill the lua stack with headers from the httpclient response
7534 * This works the same way as the hlua_http_get_headers() function
7535 */
7536__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7537{
7538 struct http_hdr *hdr;
7539
7540 lua_newtable(L);
7541
William Lallemandef574b22021-10-05 16:19:31 +02007542 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007543 struct ist n, v;
7544 int len;
7545
7546 n = hdr->n;
7547 v = hdr->v;
7548
7549 /* Check for existing entry:
7550 * assume that the table is on the top of the stack, and
7551 * push the key in the stack, the function lua_gettable()
7552 * perform the lookup.
7553 */
7554
7555 lua_pushlstring(L, n.ptr, n.len);
7556 lua_gettable(L, -2);
7557
7558 switch (lua_type(L, -1)) {
7559 case LUA_TNIL:
7560 /* Table not found, create it. */
7561 lua_pop(L, 1); /* remove the nil value. */
7562 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7563 lua_newtable(L); /* create and push empty table. */
7564 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7565 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7566 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7567 break;
7568
7569 case LUA_TTABLE:
7570 /* Entry found: push the value in the table. */
7571 len = lua_rawlen(L, -1);
7572 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7573 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7574 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7575 break;
7576
7577 default:
7578 /* Other cases are errors. */
7579 hlua_pusherror(L, "internal error during the parsing of headers.");
7580 WILL_LJMP(lua_error(L));
7581 }
7582 }
7583 return 1;
7584}
7585
7586/*
William Lallemand746e6f32021-10-06 10:57:44 +02007587 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7588 *
7589 * Caller must free the result
7590 */
7591struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7592{
7593 struct http_hdr hdrs[global.tune.max_http_hdr];
7594 struct http_hdr *result = NULL;
7595 uint32_t hdr_num = 0;
7596
7597 lua_pushnil(L);
7598 while (lua_next(L, -2) != 0) {
7599 struct ist name, value;
7600 const char *n, *v;
7601 size_t nlen, vlen;
7602
7603 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7604 /* Skip element if the key is not a string or if the value is not a table */
7605 goto next_hdr;
7606 }
7607
7608 n = lua_tolstring(L, -2, &nlen);
7609 name = ist2(n, nlen);
7610
7611 /* Loop on header's values */
7612 lua_pushnil(L);
7613 while (lua_next(L, -2)) {
7614 if (!lua_isstring(L, -1)) {
7615 /* Skip the value if it is not a string */
7616 goto next_value;
7617 }
7618
7619 v = lua_tolstring(L, -1, &vlen);
7620 value = ist2(v, vlen);
7621 name = ist2(n, nlen);
7622
7623 hdrs[hdr_num].n = istdup(name);
7624 hdrs[hdr_num].v = istdup(value);
7625
7626 hdr_num++;
7627
7628 next_value:
7629 lua_pop(L, 1);
7630 }
7631
7632 next_hdr:
7633 lua_pop(L, 1);
7634
7635 }
7636
7637 if (hdr_num) {
7638 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007639 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007640 if (!result)
7641 goto skip_headers;
7642 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7643
7644 result[hdr_num].n = IST_NULL;
7645 result[hdr_num].v = IST_NULL;
7646 }
7647
7648skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007649
7650 return result;
7651}
7652
7653
William Lallemandbd5739e2021-10-28 15:41:38 +02007654/*
7655 * For each yield, checks if there is some data in the httpclient and push them
7656 * in the lua buffer, once the httpclient finished its job, push the result on
7657 * the stack
7658 */
7659__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7660{
7661 struct buffer *tr;
7662 int res;
7663 struct hlua *hlua = hlua_gethlua(L);
7664 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7665
7666
7667 tr = get_trash_chunk();
7668
7669 res = httpclient_res_xfer(hlua_hc->hc, tr);
7670 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7671
7672 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7673
7674 luaL_pushresult(&hlua_hc->b);
7675 lua_settable(L, -3);
7676
7677 lua_pushstring(L, "status");
7678 lua_pushinteger(L, hlua_hc->hc->res.status);
7679 lua_settable(L, -3);
7680
7681
7682 lua_pushstring(L, "reason");
7683 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7684 lua_settable(L, -3);
7685
7686 lua_pushstring(L, "headers");
7687 hlua_httpclient_get_headers(L, hlua_hc);
7688 lua_settable(L, -3);
7689
7690 return 1;
7691 }
7692
7693 if (httpclient_data(hlua_hc->hc))
7694 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7695
7696 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7697
7698 return 0;
7699}
7700
7701/*
7702 * Call this when trying to stream a body during a request
7703 */
7704__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7705{
7706 struct hlua *hlua;
7707 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7708 const char *body_str = NULL;
7709 int ret;
7710 int end = 0;
7711 size_t buf_len;
7712 size_t to_send = 0;
7713
7714 hlua = hlua_gethlua(L);
7715
7716 if (!hlua || !hlua->task)
7717 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7718 "'frontend', 'backend' or 'task'"));
7719
7720 ret = lua_getfield(L, -1, "body");
7721 if (ret != LUA_TSTRING)
7722 goto rcv;
7723
7724 body_str = lua_tolstring(L, -1, &buf_len);
7725 lua_pop(L, 1);
7726
Christopher Fauletfc591292022-01-12 14:46:03 +01007727 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007728
7729 if ((hlua_hc->sent + to_send) >= buf_len)
7730 end = 1;
7731
7732 /* the end flag is always set since we are using the whole remaining size */
7733 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7734
7735 if (buf_len > hlua_hc->sent) {
7736 /* still need to process the buffer */
7737 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7738 } else {
7739 goto rcv;
7740 /* we sent the whole request buffer we can recv */
7741 }
7742 return 0;
7743
7744rcv:
7745
7746 /* we return a "res" object */
7747 lua_newtable(L);
7748
William Lallemandbd5739e2021-10-28 15:41:38 +02007749 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007750 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007751
William Lallemand933fe392021-11-04 09:45:58 +01007752 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007753 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7754
7755 return 1;
7756}
William Lallemand746e6f32021-10-06 10:57:44 +02007757
William Lallemand3956c4e2021-09-21 16:25:15 +02007758/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007759 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007760 */
7761
William Lallemanddc2cc902021-10-26 11:43:26 +02007762__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007763{
7764 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007765 struct http_hdr *hdrs = NULL;
7766 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007767 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007768 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007769 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007770 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007771 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007772
7773 hlua = hlua_gethlua(L);
7774
7775 if (!hlua || !hlua->task)
7776 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7777 "'frontend', 'backend' or 'task'"));
7778
William Lallemand746e6f32021-10-06 10:57:44 +02007779 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7780 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7781
William Lallemand4f4f2b72022-02-17 20:00:23 +01007782 hlua_hc = hlua_checkhttpclient(L, 1);
7783
William Lallemand7177a952022-03-03 15:33:12 +01007784 lua_pushnil(L); /* first key */
7785 while (lua_next(L, 2)) {
7786 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7787 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7788 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007789
William Lallemand7177a952022-03-03 15:33:12 +01007790 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7791 if (lua_type(L, -1) != LUA_TSTRING)
7792 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7793 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007794
William Lallemand7177a952022-03-03 15:33:12 +01007795 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7796 if (lua_type(L, -1) != LUA_TNUMBER)
7797 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7798 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007799
William Lallemand7177a952022-03-03 15:33:12 +01007800 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7801 if (lua_type(L, -1) != LUA_TTABLE)
7802 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7803 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007804
William Lallemand7177a952022-03-03 15:33:12 +01007805 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7806 if (lua_type(L, -1) != LUA_TSTRING)
7807 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7808 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007809
William Lallemand7177a952022-03-03 15:33:12 +01007810 } else {
7811 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7812 }
7813 /* removes 'value'; keeps 'key' for next iteration */
7814 lua_pop(L, 1);
7815 }
William Lallemanddec25c32021-10-25 19:48:37 +02007816
William Lallemand746e6f32021-10-06 10:57:44 +02007817 if (!url_str) {
7818 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7819 return 0;
7820 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007821
William Lallemand10a37362022-03-02 16:18:26 +01007822 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007823
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007824 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007825 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007826 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007827
7828 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007829 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7830 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7831 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007832 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007833
William Lallemandbd5739e2021-10-28 15:41:38 +02007834 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007835 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007836 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7837 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007838
William Lallemandbd5739e2021-10-28 15:41:38 +02007839 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007840
William Lallemand746e6f32021-10-06 10:57:44 +02007841 /* free the temporary headers array */
7842 hdrs_i = hdrs;
7843 while (hdrs_i && isttest(hdrs_i->n)) {
7844 istfree(&hdrs_i->n);
7845 istfree(&hdrs_i->v);
7846 hdrs_i++;
7847 }
7848 ha_free(&hdrs);
7849
7850
William Lallemand6137a9e2021-10-26 15:01:53 +02007851 if (ret != ERR_NONE) {
7852 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7853 return 0;
7854 }
7855
William Lallemandc2d3db42022-04-26 11:46:13 +02007856 if (!httpclient_start(hlua_hc->hc))
7857 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007858
William Lallemandbd5739e2021-10-28 15:41:38 +02007859 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007860
William Lallemand3956c4e2021-09-21 16:25:15 +02007861 return 0;
7862}
7863
7864/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007865 * Sends an HTTP HEAD request and wait for a response
7866 *
7867 * httpclient:head(url, headers, payload)
7868 */
7869__LJMP static int hlua_httpclient_head(lua_State *L)
7870{
7871 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7872}
7873
7874/*
7875 * Send an HTTP GET request and wait for a response
7876 *
7877 * httpclient:get(url, headers, payload)
7878 */
7879__LJMP static int hlua_httpclient_get(lua_State *L)
7880{
7881 return hlua_httpclient_send(L, HTTP_METH_GET);
7882
7883}
7884
7885/*
7886 * Sends an HTTP PUT request and wait for a response
7887 *
7888 * httpclient:put(url, headers, payload)
7889 */
7890__LJMP static int hlua_httpclient_put(lua_State *L)
7891{
7892 return hlua_httpclient_send(L, HTTP_METH_PUT);
7893}
7894
7895/*
7896 * Send an HTTP POST request and wait for a response
7897 *
7898 * httpclient:post(url, headers, payload)
7899 */
7900__LJMP static int hlua_httpclient_post(lua_State *L)
7901{
7902 return hlua_httpclient_send(L, HTTP_METH_POST);
7903}
7904
7905
7906/*
7907 * Sends an HTTP DELETE request and wait for a response
7908 *
7909 * httpclient:delete(url, headers, payload)
7910 */
7911__LJMP static int hlua_httpclient_delete(lua_State *L)
7912{
7913 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7914}
7915
7916/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007917 *
7918 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007919 * Class TXN
7920 *
7921 *
7922 */
7923
7924/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007925 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007926 */
7927__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7928{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007929 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007930}
7931
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007932__LJMP static int hlua_set_var(lua_State *L)
7933{
7934 struct hlua_txn *htxn;
7935 const char *name;
7936 size_t len;
7937 struct sample smp;
7938
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007939 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7940 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007941
7942 /* It is useles to retrieve the stream, but this function
7943 * runs only in a stream context.
7944 */
7945 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7946 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7947
7948 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007949 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007950 hlua_lua2smp(L, 3, &smp);
7951
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02007952 /* Store the sample in a variable. We don't need to dup the smp, vars API
7953 * already takes care of duplicating dynamic var data.
7954 */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007955 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007956
7957 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7958 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7959 else
7960 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7961
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007962 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007963}
7964
Christopher Faulet85d79c92016-11-09 16:54:56 +01007965__LJMP static int hlua_unset_var(lua_State *L)
7966{
7967 struct hlua_txn *htxn;
7968 const char *name;
7969 size_t len;
7970 struct sample smp;
7971
7972 MAY_LJMP(check_args(L, 2, "unset_var"));
7973
7974 /* It is useles to retrieve the stream, but this function
7975 * runs only in a stream context.
7976 */
7977 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7978 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7979
7980 /* Unset the variable. */
7981 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007982 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7983 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007984}
7985
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007986__LJMP static int hlua_get_var(lua_State *L)
7987{
7988 struct hlua_txn *htxn;
7989 const char *name;
7990 size_t len;
7991 struct sample smp;
7992
7993 MAY_LJMP(check_args(L, 2, "get_var"));
7994
7995 /* It is useles to retrieve the stream, but this function
7996 * runs only in a stream context.
7997 */
7998 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7999 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
8000
Willy Tarreau7560dd42016-03-10 16:28:58 +01008001 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02008002 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008003 lua_pushnil(L);
8004 return 1;
8005 }
8006
Aurelien DARRAGON41217722023-05-17 10:44:47 +02008007 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02008008}
8009
Willy Tarreau59551662015-03-10 14:23:13 +01008010__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008011{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008012 struct hlua *hlua;
8013
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008014 MAY_LJMP(check_args(L, 2, "set_priv"));
8015
Willy Tarreau87b09662015-04-03 00:22:06 +02008016 /* It is useles to retrieve the stream, but this function
8017 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008018 */
8019 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008020
8021 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008022 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008023 if (!hlua)
8024 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008025
8026 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02008027 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008028
8029 /* Get and store new value. */
8030 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
8031 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
8032
8033 return 0;
8034}
8035
Willy Tarreau59551662015-03-10 14:23:13 +01008036__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008037{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008038 struct hlua *hlua;
8039
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008040 MAY_LJMP(check_args(L, 1, "get_priv"));
8041
Willy Tarreau87b09662015-04-03 00:22:06 +02008042 /* It is useles to retrieve the stream, but this function
8043 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008044 */
8045 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008046
8047 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008048 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008049 if (!hlua) {
8050 lua_pushnil(L);
8051 return 1;
8052 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008053
8054 /* Push configuration index in the stack. */
8055 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
8056
8057 return 1;
8058}
8059
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008060/* Create stack entry containing a class TXN. This function
8061 * return 0 if the stack does not contains free slots,
8062 * otherwise it returns 1.
8063 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008064static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008065{
Willy Tarreaude491382015-04-06 11:04:28 +02008066 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008067
8068 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01008069 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008070 return 0;
8071
8072 /* NOTE: The allocation never fails. The failure
8073 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008074 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008075 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01008076 /* Create the object: obj[0] = userdata. */
8077 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02008078 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01008079 lua_rawseti(L, -2, 0);
8080
Willy Tarreaude491382015-04-06 11:04:28 +02008081 htxn->s = s;
8082 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01008083 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008084 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008085
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008086 /* Create the "f" field that contains a list of fetches. */
8087 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01008088 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008089 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008090 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008091
8092 /* Create the "sf" field that contains a list of stringsafe fetches. */
8093 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01008094 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008095 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008096 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008097
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008098 /* Create the "c" field that contains a list of converters. */
8099 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02008100 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008101 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008102 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01008103
8104 /* Create the "sc" field that contains a list of stringsafe converters. */
8105 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01008106 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008107 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008108 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008109
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008110 /* Create the "req" field that contains the request channel object. */
8111 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01008112 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008113 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008114 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008115
8116 /* Create the "res" field that contains the response channel object. */
8117 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01008118 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008119 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008120 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008121
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008122 /* Creates the HTTP object is the current proxy allows http. */
8123 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01008124 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02008125 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008126 return 0;
8127 }
8128 else
8129 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008130 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008131
Christopher Faulet78c35472020-02-26 17:14:08 +01008132 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
8133 /* HTTPMessage object are created when a lua TXN is created from
8134 * a filter context only
8135 */
8136
8137 /* Creates the HTTP-Request object is the current proxy allows http. */
8138 lua_pushstring(L, "http_req");
8139 if (p->mode == PR_MODE_HTTP) {
8140 if (!hlua_http_msg_new(L, &s->txn->req))
8141 return 0;
8142 }
8143 else
8144 lua_pushnil(L);
8145 lua_rawset(L, -3);
8146
8147 /* Creates the HTTP-Response object is the current proxy allows http. */
8148 lua_pushstring(L, "http_res");
8149 if (p->mode == PR_MODE_HTTP) {
8150 if (!hlua_http_msg_new(L, &s->txn->rsp))
8151 return 0;
8152 }
8153 else
8154 lua_pushnil(L);
8155 lua_rawset(L, -3);
8156 }
8157
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008158 /* Pop a class sesison metatable and affect it to the userdata. */
8159 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
8160 lua_setmetatable(L, -2);
8161
8162 return 1;
8163}
8164
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008165__LJMP static int hlua_txn_deflog(lua_State *L)
8166{
8167 const char *msg;
8168 struct hlua_txn *htxn;
8169
8170 MAY_LJMP(check_args(L, 2, "deflog"));
8171 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8172 msg = MAY_LJMP(luaL_checkstring(L, 2));
8173
8174 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
8175 return 0;
8176}
8177
8178__LJMP static int hlua_txn_log(lua_State *L)
8179{
8180 int level;
8181 const char *msg;
8182 struct hlua_txn *htxn;
8183
8184 MAY_LJMP(check_args(L, 3, "log"));
8185 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8186 level = MAY_LJMP(luaL_checkinteger(L, 2));
8187 msg = MAY_LJMP(luaL_checkstring(L, 3));
8188
8189 if (level < 0 || level >= NB_LOG_LEVELS)
8190 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8191
8192 hlua_sendlog(htxn->s->be, level, msg);
8193 return 0;
8194}
8195
8196__LJMP static int hlua_txn_log_debug(lua_State *L)
8197{
8198 const char *msg;
8199 struct hlua_txn *htxn;
8200
8201 MAY_LJMP(check_args(L, 2, "Debug"));
8202 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8203 msg = MAY_LJMP(luaL_checkstring(L, 2));
8204 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
8205 return 0;
8206}
8207
8208__LJMP static int hlua_txn_log_info(lua_State *L)
8209{
8210 const char *msg;
8211 struct hlua_txn *htxn;
8212
8213 MAY_LJMP(check_args(L, 2, "Info"));
8214 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8215 msg = MAY_LJMP(luaL_checkstring(L, 2));
8216 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
8217 return 0;
8218}
8219
8220__LJMP static int hlua_txn_log_warning(lua_State *L)
8221{
8222 const char *msg;
8223 struct hlua_txn *htxn;
8224
8225 MAY_LJMP(check_args(L, 2, "Warning"));
8226 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8227 msg = MAY_LJMP(luaL_checkstring(L, 2));
8228 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
8229 return 0;
8230}
8231
8232__LJMP static int hlua_txn_log_alert(lua_State *L)
8233{
8234 const char *msg;
8235 struct hlua_txn *htxn;
8236
8237 MAY_LJMP(check_args(L, 2, "Alert"));
8238 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8239 msg = MAY_LJMP(luaL_checkstring(L, 2));
8240 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8241 return 0;
8242}
8243
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008244__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8245{
8246 struct hlua_txn *htxn;
8247 int ll;
8248
8249 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8250 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8251 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8252
Christopher Faulet12a5ee72024-02-29 15:41:17 +01008253 if (ll < -1 || ll > NB_LOG_LEVELS)
8254 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be one of the following value:"
8255 " core.silent(-1), core.emerg(0), core.alert(1), core.crit(2), core.error(3),"
8256 " core.warning(4), core.notice(5), core.info(6) or core.debug(7)"));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008257
Christopher Faulet12a5ee72024-02-29 15:41:17 +01008258 htxn->s->logs.level = (ll == -1) ? ll : ll + 1;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008259 return 0;
8260}
8261
8262__LJMP static int hlua_txn_set_tos(lua_State *L)
8263{
8264 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008265 int tos;
8266
8267 MAY_LJMP(check_args(L, 2, "set_tos"));
8268 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8269 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8270
Willy Tarreau1a18b542018-12-11 16:37:42 +01008271 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008272 return 0;
8273}
8274
8275__LJMP static int hlua_txn_set_mark(lua_State *L)
8276{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008277 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008278 int mark;
8279
8280 MAY_LJMP(check_args(L, 2, "set_mark"));
8281 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8282 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8283
Lukas Tribus579e3e32019-08-11 18:03:45 +02008284 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008285 return 0;
8286}
8287
Patrick Hemmer268a7072018-05-11 12:52:31 -04008288__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8289{
8290 struct hlua_txn *htxn;
8291
8292 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8293 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8294 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8295 return 0;
8296}
8297
8298__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8299{
8300 struct hlua_txn *htxn;
8301
8302 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8303 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8304 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8305 return 0;
8306}
8307
Christopher Faulet700d9e82020-01-31 12:21:52 +01008308/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008309 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008310 * message and terminate the transaction. It returns 1 on success and 0 on
8311 * error. The Reply must be on top of the stack.
8312 */
8313__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8314{
8315 struct htx *htx;
8316 struct htx_sl *sl;
8317 struct h1m h1m;
8318 const char *status, *reason, *body;
8319 size_t status_len, reason_len, body_len;
8320 int ret, code, flags;
8321
8322 code = 200;
8323 status = "200";
8324 status_len = 3;
8325 ret = lua_getfield(L, -1, "status");
8326 if (ret == LUA_TNUMBER) {
8327 code = lua_tointeger(L, -1);
8328 status = lua_tolstring(L, -1, &status_len);
8329 }
8330 lua_pop(L, 1);
8331
8332 reason = http_get_reason(code);
8333 reason_len = strlen(reason);
8334 ret = lua_getfield(L, -1, "reason");
8335 if (ret == LUA_TSTRING)
8336 reason = lua_tolstring(L, -1, &reason_len);
8337 lua_pop(L, 1);
8338
8339 body = NULL;
8340 body_len = 0;
8341 ret = lua_getfield(L, -1, "body");
8342 if (ret == LUA_TSTRING)
8343 body = lua_tolstring(L, -1, &body_len);
8344 lua_pop(L, 1);
8345
8346 /* Prepare the response before inserting the headers */
8347 h1m_init_res(&h1m);
8348 htx = htx_from_buf(&s->res.buf);
8349 channel_htx_truncate(&s->res, htx);
8350 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8351 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8352 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8353 ist2(status, status_len), ist2(reason, reason_len));
8354 }
8355 else {
8356 flags = HTX_SL_F_IS_RESP;
8357 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8358 ist2(status, status_len), ist2(reason, reason_len));
8359 }
8360 if (!sl)
8361 goto fail;
8362 sl->info.res.status = code;
8363
8364 /* Push in the stack the "headers" entry. */
8365 ret = lua_getfield(L, -1, "headers");
8366 if (ret != LUA_TTABLE)
8367 goto skip_headers;
8368
8369 lua_pushnil(L);
8370 while (lua_next(L, -2) != 0) {
8371 struct ist name, value;
8372 const char *n, *v;
8373 size_t nlen, vlen;
8374
8375 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8376 /* Skip element if the key is not a string or if the value is not a table */
8377 goto next_hdr;
8378 }
8379
8380 n = lua_tolstring(L, -2, &nlen);
8381 name = ist2(n, nlen);
8382 if (isteqi(name, ist("content-length"))) {
8383 /* Always skip content-length header. It will be added
8384 * later with the correct len
8385 */
8386 goto next_hdr;
8387 }
8388
8389 /* Loop on header's values */
8390 lua_pushnil(L);
8391 while (lua_next(L, -2)) {
8392 if (!lua_isstring(L, -1)) {
8393 /* Skip the value if it is not a string */
8394 goto next_value;
8395 }
8396
8397 v = lua_tolstring(L, -1, &vlen);
8398 value = ist2(v, vlen);
8399
8400 if (isteqi(name, ist("transfer-encoding")))
8401 h1_parse_xfer_enc_header(&h1m, value);
8402 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8403 goto fail;
8404
8405 next_value:
8406 lua_pop(L, 1);
8407 }
8408
8409 next_hdr:
8410 lua_pop(L, 1);
8411 }
8412 skip_headers:
8413 lua_pop(L, 1);
8414
8415 /* Update h1m flags: CLEN is set if CHNK is not present */
8416 if (!(h1m.flags & H1_MF_CHNK)) {
8417 const char *clen = ultoa(body_len);
8418
8419 h1m.flags |= H1_MF_CLEN;
8420 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8421 goto fail;
8422 }
8423 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8424 h1m.flags |= H1_MF_XFER_LEN;
8425
8426 /* Update HTX start-line flags */
8427 if (h1m.flags & H1_MF_XFER_ENC)
8428 flags |= HTX_SL_F_XFER_ENC;
8429 if (h1m.flags & H1_MF_XFER_LEN) {
8430 flags |= HTX_SL_F_XFER_LEN;
8431 if (h1m.flags & H1_MF_CHNK)
8432 flags |= HTX_SL_F_CHNK;
8433 else if (h1m.flags & H1_MF_CLEN)
8434 flags |= HTX_SL_F_CLEN;
8435 if (h1m.body_len == 0)
8436 flags |= HTX_SL_F_BODYLESS;
8437 }
8438 sl->flags |= flags;
8439
8440
8441 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008442 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008443 goto fail;
8444
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008445 htx->flags |= HTX_FL_EOM;
8446
Christopher Faulet700d9e82020-01-31 12:21:52 +01008447 /* Now, forward the response and terminate the transaction */
8448 s->txn->status = code;
8449 htx_to_buf(htx, &s->res.buf);
8450 if (!http_forward_proxy_resp(s, 1))
8451 goto fail;
8452
8453 return 1;
8454
8455 fail:
8456 channel_htx_truncate(&s->res, htx);
8457 return 0;
8458}
8459
8460/* Terminate a transaction if called from a lua action. For TCP streams,
8461 * processing is just aborted. Nothing is returned to the client and all
8462 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8463 * is forwarded to the client before terminating the transaction. On success,
8464 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8465 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8466 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008467 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008468__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008469{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008470 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008471 struct stream *s;
8472 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008473
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008474 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008475
Christopher Faulet700d9e82020-01-31 12:21:52 +01008476 /* If the flags NOTERM is set, we cannot terminate the session, so we
8477 * just end the execution of the current lua code. */
8478 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008479 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008480
Christopher Faulet700d9e82020-01-31 12:21:52 +01008481 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008482 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008483 struct channel *req = &s->req;
8484 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008485
Christopher Faulet700d9e82020-01-31 12:21:52 +01008486 channel_auto_read(req);
8487 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008488 channel_erase(req);
8489
Christopher Faulet700d9e82020-01-31 12:21:52 +01008490 channel_auto_read(res);
8491 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008492 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008493
8494 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8495 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008496 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008497
Christopher Faulet700d9e82020-01-31 12:21:52 +01008498 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8499 /* No reply or invalid reply */
8500 s->txn->status = 0;
8501 http_reply_and_close(s, 0, NULL);
8502 }
8503 else {
8504 /* Remove extra args to have the reply on top of the stack */
8505 if (lua_gettop(L) > 2)
8506 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008507
Christopher Faulet700d9e82020-01-31 12:21:52 +01008508 if (!hlua_txn_forward_reply(L, s)) {
8509 if (!(s->flags & SF_ERR_MASK))
8510 s->flags |= SF_ERR_PRXCOND;
8511 lua_pushinteger(L, ACT_RET_ERR);
8512 WILL_LJMP(hlua_done(L));
8513 return 0; /* Never reached */
8514 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008515 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008516
Christopher Faulet700d9e82020-01-31 12:21:52 +01008517 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8518 if (htxn->dir == SMP_OPT_DIR_REQ) {
8519 /* let's log the request time */
Willy Tarreau69530f52023-04-28 09:16:15 +02008520 s->logs.request_ts = now_ns;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008521 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008522 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008523 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008524
Christopher Faulet700d9e82020-01-31 12:21:52 +01008525 done:
8526 if (!(s->flags & SF_ERR_MASK))
8527 s->flags |= SF_ERR_LOCAL;
8528 if (!(s->flags & SF_FINST_MASK))
8529 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008530
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008531 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8532 lua_pushinteger(L, -1);
8533 else
8534 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008535 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008536 return 0;
8537}
8538
Christopher Faulet700d9e82020-01-31 12:21:52 +01008539/*
8540 *
8541 *
8542 * Class REPLY
8543 *
8544 *
8545 */
8546
8547/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8548 * free slots, the function fails and returns 0;
8549 */
8550static int hlua_txn_reply_new(lua_State *L)
8551{
8552 struct hlua_txn *htxn;
8553 const char *reason, *body = NULL;
8554 int ret, status;
8555
8556 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008557 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008558 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8559 WILL_LJMP(lua_error(L));
8560 }
8561
8562 /* Default value */
8563 status = 200;
8564 reason = http_get_reason(status);
8565
8566 if (lua_istable(L, 2)) {
8567 /* load status and reason from the table argument at index 2 */
8568 ret = lua_getfield(L, 2, "status");
8569 if (ret == LUA_TNIL)
8570 goto reason;
8571 else if (ret != LUA_TNUMBER) {
8572 /* invalid status: ignore the reason */
8573 goto body;
8574 }
8575 status = lua_tointeger(L, -1);
8576
8577 reason:
8578 lua_pop(L, 1); /* restore the stack: remove status */
8579 ret = lua_getfield(L, 2, "reason");
8580 if (ret == LUA_TSTRING)
8581 reason = lua_tostring(L, -1);
8582
8583 body:
8584 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8585 ret = lua_getfield(L, 2, "body");
8586 if (ret == LUA_TSTRING)
8587 body = lua_tostring(L, -1);
8588 lua_pop(L, 1); /* restore the stack: remove body */
8589 }
8590
8591 /* Create the Reply table */
8592 lua_newtable(L);
8593
8594 /* Add status element */
8595 lua_pushstring(L, "status");
8596 lua_pushinteger(L, status);
8597 lua_settable(L, -3);
8598
8599 /* Add reason element */
8600 reason = http_get_reason(status);
8601 lua_pushstring(L, "reason");
8602 lua_pushstring(L, reason);
8603 lua_settable(L, -3);
8604
8605 /* Add body element, nil if undefined */
8606 lua_pushstring(L, "body");
8607 if (body)
8608 lua_pushstring(L, body);
8609 else
8610 lua_pushnil(L);
8611 lua_settable(L, -3);
8612
8613 /* Add headers element */
8614 lua_pushstring(L, "headers");
8615 lua_newtable(L);
8616
8617 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8618 if (lua_istable(L, 2)) {
8619 /* load headers from the table argument at index 2. If it is a table, copy it. */
8620 ret = lua_getfield(L, 2, "headers");
8621 if (ret == LUA_TTABLE) {
8622 /* stack: [ ... <headers:table>, <table> ] */
8623 lua_pushnil(L);
8624 while (lua_next(L, -2) != 0) {
8625 /* stack: [ ... <headers:table>, <table>, k, v] */
8626 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8627 /* invalid value type, skip it */
8628 lua_pop(L, 1);
8629 continue;
8630 }
8631
8632
8633 /* Duplicate the key and swap it with the value. */
8634 lua_pushvalue(L, -2);
8635 lua_insert(L, -2);
8636 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8637
8638 lua_newtable(L);
8639 lua_insert(L, -2);
8640 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8641
8642 if (lua_isstring(L, -1)) {
8643 /* push the value in the inner table */
8644 lua_rawseti(L, -2, 1);
8645 }
8646 else { /* table */
8647 lua_pushnil(L);
8648 while (lua_next(L, -2) != 0) {
8649 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8650 if (!lua_isstring(L, -1)) {
8651 /* invalid value type, skip it*/
8652 lua_pop(L, 1);
8653 continue;
8654 }
8655 /* push the value in the inner table */
8656 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8657 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8658 }
8659 lua_pop(L, 1);
8660 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8661 }
8662
8663 /* push (k,v) on the stack in the headers table:
8664 * stack: [ ... <headers:table>, <table>, k, k, v ]
8665 */
8666 lua_settable(L, -5);
8667 /* stack: [ ... <headers:table>, <table>, k ] */
8668 }
8669 }
8670 lua_pop(L, 1);
8671 }
8672 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8673 lua_settable(L, -3);
8674 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8675
8676 /* Pop a class sesison metatable and affect it to the userdata. */
8677 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8678 lua_setmetatable(L, -2);
8679 return 1;
8680}
8681
8682/* Set the reply status code, and optionally the reason. If no reason is
8683 * provided, the default one corresponding to the status code is used.
8684 */
8685__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8686{
8687 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8688 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8689
8690 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008691 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008692
8693 if (status < 100 || status > 599) {
8694 lua_pushboolean(L, 0);
8695 return 1;
8696 }
8697 if (!reason)
8698 reason = http_get_reason(status);
8699
8700 lua_pushinteger(L, status);
8701 lua_setfield(L, 1, "status");
8702
8703 lua_pushstring(L, reason);
8704 lua_setfield(L, 1, "reason");
8705
8706 lua_pushboolean(L, 1);
8707 return 1;
8708}
8709
8710/* Add a header into the reply object. Each header name is associated to an
8711 * array of values in the "headers" table. If the header name is not found, a
8712 * new entry is created.
8713 */
8714__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8715{
8716 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8717 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8718 int ret;
8719
8720 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008721 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008722
8723 /* Push in the stack the "headers" entry. */
8724 ret = lua_getfield(L, 1, "headers");
8725 if (ret != LUA_TTABLE) {
8726 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8727 WILL_LJMP(lua_error(L));
8728 }
8729
8730 /* check if the header is already registered. If not, register it. */
8731 ret = lua_getfield(L, -1, name);
8732 if (ret == LUA_TNIL) {
8733 /* Entry not found. */
8734 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8735
8736 /* Insert the new header name in the array in the top of the stack.
8737 * It left the new array in the top of the stack.
8738 */
8739 lua_newtable(L);
8740 lua_pushstring(L, name);
8741 lua_pushvalue(L, -2);
8742 lua_settable(L, -4);
8743 }
8744 else if (ret != LUA_TTABLE) {
8745 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8746 WILL_LJMP(lua_error(L));
8747 }
8748
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008749 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008750 * the header value as new entry.
8751 */
8752 lua_pushstring(L, value);
8753 ret = lua_rawlen(L, -2);
8754 lua_rawseti(L, -2, ret + 1);
8755
8756 lua_pushboolean(L, 1);
8757 return 1;
8758}
8759
8760/* Remove all occurrences of a given header name. */
8761__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8762{
8763 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8764 int ret;
8765
8766 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008767 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008768
8769 /* Push in the stack the "headers" entry. */
8770 ret = lua_getfield(L, 1, "headers");
8771 if (ret != LUA_TTABLE) {
8772 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8773 WILL_LJMP(lua_error(L));
8774 }
8775
8776 lua_pushstring(L, name);
8777 lua_pushnil(L);
8778 lua_settable(L, -3);
8779
8780 lua_pushboolean(L, 1);
8781 return 1;
8782}
8783
8784/* Set the reply's body. Overwrite any existing entry. */
8785__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8786{
8787 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8788
8789 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008790 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008791
8792 lua_pushstring(L, payload);
8793 lua_setfield(L, 1, "body");
8794
8795 lua_pushboolean(L, 1);
8796 return 1;
8797}
8798
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008799__LJMP static int hlua_log(lua_State *L)
8800{
8801 int level;
8802 const char *msg;
8803
8804 MAY_LJMP(check_args(L, 2, "log"));
8805 level = MAY_LJMP(luaL_checkinteger(L, 1));
8806 msg = MAY_LJMP(luaL_checkstring(L, 2));
8807
8808 if (level < 0 || level >= NB_LOG_LEVELS)
8809 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8810
8811 hlua_sendlog(NULL, level, msg);
8812 return 0;
8813}
8814
8815__LJMP static int hlua_log_debug(lua_State *L)
8816{
8817 const char *msg;
8818
8819 MAY_LJMP(check_args(L, 1, "debug"));
8820 msg = MAY_LJMP(luaL_checkstring(L, 1));
8821 hlua_sendlog(NULL, LOG_DEBUG, msg);
8822 return 0;
8823}
8824
8825__LJMP static int hlua_log_info(lua_State *L)
8826{
8827 const char *msg;
8828
8829 MAY_LJMP(check_args(L, 1, "info"));
8830 msg = MAY_LJMP(luaL_checkstring(L, 1));
8831 hlua_sendlog(NULL, LOG_INFO, msg);
8832 return 0;
8833}
8834
8835__LJMP static int hlua_log_warning(lua_State *L)
8836{
8837 const char *msg;
8838
8839 MAY_LJMP(check_args(L, 1, "warning"));
8840 msg = MAY_LJMP(luaL_checkstring(L, 1));
8841 hlua_sendlog(NULL, LOG_WARNING, msg);
8842 return 0;
8843}
8844
8845__LJMP static int hlua_log_alert(lua_State *L)
8846{
8847 const char *msg;
8848
8849 MAY_LJMP(check_args(L, 1, "alert"));
8850 msg = MAY_LJMP(luaL_checkstring(L, 1));
8851 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008852 return 0;
8853}
8854
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008855__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008856{
8857 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008858 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008859 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008860 return 0;
8861}
8862
8863__LJMP static int hlua_sleep(lua_State *L)
8864{
8865 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008866 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008867
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008868 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008869
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008870 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008871 wakeup_ms = tick_add(now_ms, delay);
8872 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008873
Willy Tarreau9635e032018-10-16 17:52:55 +02008874 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008875 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008876}
8877
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008878__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008879{
8880 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008881 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008882
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008883 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008884
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008885 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008886 wakeup_ms = tick_add(now_ms, delay);
8887 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008888
Willy Tarreau9635e032018-10-16 17:52:55 +02008889 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008890 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008891}
8892
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008893/* This functionis an LUA binding. it permits to give back
8894 * the hand at the HAProxy scheduler. It is used when the
8895 * LUA processing consumes a lot of time.
8896 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008897__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008898{
8899 return 0;
8900}
8901
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008902__LJMP static int hlua_yield(lua_State *L)
8903{
Willy Tarreau9635e032018-10-16 17:52:55 +02008904 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008905 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008906}
8907
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008908/* This function change the nice of the currently executed
8909 * task. It is used set low or high priority at the current
8910 * task.
8911 */
Willy Tarreau59551662015-03-10 14:23:13 +01008912__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008913{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008914 struct hlua *hlua;
8915 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008916
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008917 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008918 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008919
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008920 /* Get hlua struct, or NULL if we execute from main lua state */
8921 hlua = hlua_gethlua(L);
8922
8923 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008924 if (!hlua || !hlua->task)
8925 return 0;
8926
8927 if (nice < -1024)
8928 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008929 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008930 nice = 1024;
8931
8932 hlua->task->nice = nice;
8933 return 0;
8934}
8935
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +02008936/* safe lua coroutine.create() function:
8937 *
8938 * This is a simple wrapper for coroutine.create() that
8939 * ensures the current hlua state ctx is available from
8940 * the new subroutine state
8941 */
8942__LJMP static int hlua_coroutine_create(lua_State *L)
8943{
8944 lua_State *new; /* new coroutine state */
8945 struct hlua **hlua_store;
8946 struct hlua *hlua = hlua_gethlua(L);
8947
8948 new = lua_newthread(L);
8949 if (!new)
8950 return 0;
8951
8952 hlua_store = lua_getextraspace(new);
8953 /* Expose current hlua ctx on new lua thread
8954 * (hlua_gethlua() will properly return the last "known"
8955 * hlua ctx instead of NULL when it is called from such coroutines)
8956 */
8957 *hlua_store = hlua;
8958
8959 /* new lua thread is on the top of the stack, we
8960 * need to duplicate first stack argument (<f> from coroutine.create(<f>))
8961 * on the top of the stack to be able to use xmove() to move it on the new
8962 * stack
8963 */
8964 lua_pushvalue(L, 1);
8965 /* move <f> function to the new stack */
8966 lua_xmove(L, new, 1);
8967 /* new lua thread is back at the top of the stack */
8968 return 1;
8969}
8970
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008971/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008972 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8973 * return an E_AGAIN signal, the emmiter of this signal must set a
8974 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008975 *
8976 * Task wrapper are longjmp safe because the only one Lua code
8977 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008978 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008979struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008980{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008981 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008982 enum hlua_exec status;
8983
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008984 if (task->tid < 0)
8985 task->tid = tid;
8986
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008987 /* If it is the first call to the task, we must initialize the
8988 * execution timeouts.
8989 */
8990 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008991 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008992
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008993 /* Execute the Lua code. */
8994 status = hlua_ctx_resume(hlua, 1);
8995
8996 switch (status) {
8997 /* finished or yield */
8998 case HLUA_E_OK:
8999 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02009000 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02009001 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009002 break;
9003
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009004 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01009005 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02009006 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009007 break;
9008
9009 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01009010 case HLUA_E_ETMOUT:
9011 SEND_ERR(NULL, "Lua task: execution timeout.\n");
9012 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009013 case HLUA_E_ERRMSG:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009014 SEND_ERR(NULL, "Lua task: %s.\n", hlua_tostring_safe(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01009015 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009016 case HLUA_E_ERR:
9017 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009018 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01009019 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009020 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02009021 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02009022 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009023 break;
9024 }
Emeric Brun253e53e2017-10-17 18:58:40 +02009025 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009026}
9027
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02009028/* Helper function to prepare the lua ctx for a given stream
9029 *
Aurelien DARRAGON02493662023-08-09 15:19:56 +02009030 * ctx will be enforced in <state_id> parent stack on initial creation.
9031 * If s->hlua->state_id differs from <state_id>, which may happen at
9032 * runtime since existing stream hlua ctx will be reused for other
9033 * "independent" (but stream-related) lua executions, hlua will be
9034 * recreated with the expected state id.
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02009035 *
9036 * Returns 1 for success and 0 for failure
9037 */
9038static int hlua_stream_ctx_prepare(struct stream *s, int state_id)
9039{
9040 /* In the execution wrappers linked with a stream, the
9041 * Lua context can be not initialized. This behavior
9042 * permits to save performances because a systematic
9043 * Lua initialization cause 5% performances loss.
9044 */
Aurelien DARRAGON02493662023-08-09 15:19:56 +02009045 ctx_renew:
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02009046 if (!s->hlua) {
9047 struct hlua *hlua;
9048
9049 hlua = pool_alloc(pool_head_hlua);
9050 if (!hlua)
9051 return 0;
9052 HLUA_INIT(hlua);
9053 if (!hlua_ctx_init(hlua, state_id, s->task)) {
9054 pool_free(pool_head_hlua, hlua);
9055 return 0;
9056 }
9057 s->hlua = hlua;
9058 }
Aurelien DARRAGON02493662023-08-09 15:19:56 +02009059 else if (s->hlua->state_id != state_id) {
9060 /* ctx already created, but not in proper state.
9061 * It should only happen after the previous execution is
9062 * finished, otherwise it's probably a bug since we don't
9063 * want to abort unfinished job..
9064 */
9065 BUG_ON(HLUA_IS_RUNNING(s->hlua));
9066 hlua_ctx_destroy(s->hlua);
9067 s->hlua = NULL;
9068 goto ctx_renew;
9069 }
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02009070 return 1;
9071}
9072
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009073/* This function is an LUA binding that register LUA function to be
9074 * executed after the HAProxy configuration parsing and before the
9075 * HAProxy scheduler starts. This function expect only one LUA
9076 * argument that is a function. This function returns nothing, but
9077 * throws if an error is encountered.
9078 */
9079__LJMP static int hlua_register_init(lua_State *L)
9080{
9081 struct hlua_init_function *init;
9082 int ref;
9083
9084 MAY_LJMP(check_args(L, 1, "register_init"));
9085
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009086 if (hlua_gethlua(L)) {
9087 /* runtime processing */
9088 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
9089 }
9090
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009091 ref = MAY_LJMP(hlua_checkfunction(L, 1));
9092
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009093 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009094 if (!init) {
9095 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009096 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009097 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009098
9099 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02009100 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009101 return 0;
9102}
9103
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05009104/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009105 * executed in parallel of the main HAroxy activity. The task is
9106 * created and it is set in the HAProxy scheduler. It can be called
9107 * from the "init" section, "post init" or during the runtime.
9108 *
9109 * Lua prototype:
9110 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009111 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
9112 *
9113 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009114 */
Aurelien DARRAGONe0b16352023-04-21 17:38:37 +02009115__LJMP static int hlua_register_task(lua_State *L)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009116{
Christopher Faulet5294ec02021-04-12 12:24:47 +02009117 struct hlua *hlua = NULL;
9118 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009119 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009120 int nb_arg;
9121 int it;
9122 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01009123 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009124
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009125 nb_arg = lua_gettop(L);
9126 if (nb_arg < 1)
9127 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
9128 else if (nb_arg > 5)
9129 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009130
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009131 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009132 ref = MAY_LJMP(hlua_checkfunction(L, 1));
9133
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009134 /* extract optional args (if any) */
9135 it = 0;
9136 while (--nb_arg) {
9137 lua_pushvalue(L, 2 + it);
9138 arg_ref[it] = hlua_ref(L); /* get arg reference */
9139 it += 1;
9140 }
9141 nb_arg = it;
9142
Thierry Fournier75fc0292020-11-28 13:18:56 +01009143 /* Get the reference state. If the reference is NULL, L is the master
9144 * state, otherwise hlua->T is.
9145 */
9146 hlua = hlua_gethlua(L);
9147 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01009148 /* we are in runtime processing */
9149 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01009150 else
Thierry Fournier021d9862020-11-28 23:42:03 +01009151 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01009152 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01009153
Willy Tarreaubafbe012017-11-24 17:34:44 +01009154 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009155 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02009156 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009157 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009158
Thierry Fournier59f11be2020-11-29 00:37:41 +01009159 /* We are in the common lua state, execute the task anywhere,
9160 * otherwise, inherit the current thread identifier
9161 */
9162 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009163 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01009164 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009165 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02009166 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02009167 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02009168
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009169 task->context = hlua;
9170 task->process = hlua_process_task;
9171
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009172 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02009173 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009174
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009175 /* Ensure there is enough space on the stack for the function
9176 * plus optional arguments
9177 */
9178 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
9179 goto alloc_error;
9180
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009181 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009182 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01009183 /* function ref not needed anymore since it was pushed to the substack */
9184 hlua_unref(L, ref);
9185
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009186 hlua->nargs = nb_arg;
9187
9188 /* push optional arguments to the function */
9189 for (it = 0; it < nb_arg; it++) {
9190 /* push arg to the stack */
9191 hlua_pushref(hlua->T, arg_ref[it]);
9192 /* arg ref not needed anymore since it was pushed to the substack */
9193 hlua_unref(L, arg_ref[it]);
9194 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009195
9196 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02009197 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009198
9199 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02009200
9201 alloc_error:
9202 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009203 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009204 for (it = 0; it < nb_arg; it++) {
9205 hlua_unref(L, arg_ref[it]);
9206 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02009207 hlua_ctx_destroy(hlua);
9208 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9209 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009210}
9211
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009212/* called from unsafe location */
9213static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
9214{
9215 /* hlua cleanup */
9216
9217 hlua_lock(hlua_sub->hlua);
9218 /* registry is shared between coroutines */
9219 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9220 hlua_unlock(hlua_sub->hlua);
9221
9222 hlua_ctx_destroy(hlua_sub->hlua);
9223
9224 /* free */
9225 pool_free(pool_head_hlua_event_sub, hlua_sub);
9226}
9227
9228/* single event handler: hlua ctx is shared between multiple events handlers
9229 * issued from the same subscription. Thus, it is not destroyed when the event
9230 * is processed: it is destroyed when no more events are expected for the
9231 * subscription (ie: when the subscription ends).
9232 *
9233 * Moreover, events are processed sequentially within the subscription:
9234 * one event must be fully processed before another one may be processed.
9235 * This ensures proper consistency for lua event handling from an ordering
9236 * point of view. This is especially useful with server events for example
9237 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
9238 * actions from lua (e.g.: sending emails or making API calls).
9239 *
9240 * Due to this design, each lua event handler is pleased to process the event
9241 * as fast as possible to prevent the event queue from growing up.
9242 * Strictly speaking, there is no runtime limit for the callback function
9243 * (timeout set to default task timeout), but if the event queue goes past
9244 * the limit of unconsumed events an error will be reported and the
9245 * susbscription will pause itself for as long as it takes for the handler to
9246 * catch up (events will be lost as a result).
9247 * If the event handler does not need the sequential ordering and wants to
9248 * process multiple events at a time, it may spawn a new side-task using
9249 * 'core.register_task' to delegate the event handling and make parallel event
9250 * processing within the same subscription set.
9251 */
9252static void hlua_event_handler(struct hlua *hlua)
9253{
9254 enum hlua_exec status;
9255
9256 /* If it is the first call to the task, we must initialize the
9257 * execution timeouts.
9258 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009259 if (!HLUA_IS_RUNNING(hlua))
9260 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009261
9262 /* make sure to reset the task expiry before each hlua_ctx_resume()
9263 * since the task is re-used for multiple cb function calls
9264 * We couldn't risk to have t->expire pointing to a past date because
9265 * it was set during last function invocation but was never reset since
9266 * (ie: E_AGAIN)
9267 */
9268 hlua->task->expire = TICK_ETERNITY;
9269
9270 /* Execute the Lua code. */
9271 status = hlua_ctx_resume(hlua, 1);
9272
9273 switch (status) {
9274 /* finished or yield */
9275 case HLUA_E_OK:
9276 break;
9277
9278 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
9279 notification_gc(&hlua->com);
9280 hlua->task->expire = hlua->wake_time;
9281 break;
9282
9283 /* finished with error. */
9284 case HLUA_E_ETMOUT:
9285 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
9286 break;
9287
9288 case HLUA_E_ERRMSG:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009289 SEND_ERR(NULL, "Lua event_hdl: %s.\n", hlua_tostring_safe(hlua->T, -1));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009290 break;
9291
9292 case HLUA_E_ERR:
9293 default:
9294 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
9295 break;
9296 }
9297}
9298
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009299__LJMP static void hlua_event_hdl_cb_push_event_checkres(lua_State *L,
9300 struct event_hdl_cb_data_server_checkres *check)
9301{
9302 lua_pushstring(L, "agent");
9303 lua_pushboolean(L, check->agent);
9304 lua_settable(L, -3);
9305 lua_pushstring(L, "result");
9306 switch (check->result) {
9307 case CHK_RES_FAILED:
9308 lua_pushstring(L, "FAILED");
9309 break;
9310 case CHK_RES_PASSED:
9311 lua_pushstring(L, "PASSED");
9312 break;
9313 case CHK_RES_CONDPASS:
9314 lua_pushstring(L, "CONDPASS");
9315 break;
9316 default:
9317 lua_pushnil(L);
9318 break;
9319 }
9320 lua_settable(L, -3);
9321
9322 lua_pushstring(L, "duration");
9323 lua_pushinteger(L, check->duration);
9324 lua_settable(L, -3);
9325
9326 lua_pushstring(L, "reason");
9327 lua_newtable(L);
9328
9329 lua_pushstring(L, "short");
9330 lua_pushstring(L, get_check_status_info(check->reason.status));
9331 lua_settable(L, -3);
9332 lua_pushstring(L, "desc");
9333 lua_pushstring(L, get_check_status_description(check->reason.status));
9334 lua_settable(L, -3);
9335 if (check->reason.status >= HCHK_STATUS_L57DATA) {
9336 /* code only available when the check reached data analysis stage */
9337 lua_pushstring(L, "code");
9338 lua_pushinteger(L, check->reason.code);
9339 lua_settable(L, -3);
9340 }
9341
9342 lua_settable(L, -3); /* reason table */
9343
9344 lua_pushstring(L, "health");
9345 lua_newtable(L);
9346
9347 lua_pushstring(L, "cur");
9348 lua_pushinteger(L, check->health.cur);
9349 lua_settable(L, -3);
9350 lua_pushstring(L, "rise");
9351 lua_pushinteger(L, check->health.rise);
9352 lua_settable(L, -3);
9353 lua_pushstring(L, "fall");
9354 lua_pushinteger(L, check->health.fall);
9355 lua_settable(L, -3);
9356
9357 lua_settable(L, -3); /* health table */
9358}
9359
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009360/* This function pushes various arguments such as event type and event data to
9361 * the lua function that will be called to consume the event.
9362 */
9363__LJMP static void hlua_event_hdl_cb_push_args(struct hlua_event_sub *hlua_sub,
9364 struct event_hdl_async_event *e)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009365{
9366 struct hlua *hlua = hlua_sub->hlua;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009367 struct event_hdl_sub_type event = e->type;
9368 void *data = e->data;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009369
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009370 /* push event type */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009371 hlua->nargs = 1;
9372 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009373
9374 /* push event data (according to event type) */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009375 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
9376 struct event_hdl_cb_data_server *e_server = data;
9377 struct proxy *px;
9378 struct server *server;
9379
9380 hlua->nargs += 1;
9381 lua_newtable(hlua->T);
9382 /* Add server name */
9383 lua_pushstring(hlua->T, "name");
9384 lua_pushstring(hlua->T, e_server->safe.name);
9385 lua_settable(hlua->T, -3);
9386 /* Add server puid */
9387 lua_pushstring(hlua->T, "puid");
9388 lua_pushinteger(hlua->T, e_server->safe.puid);
9389 lua_settable(hlua->T, -3);
9390 /* Add server rid */
9391 lua_pushstring(hlua->T, "rid");
9392 lua_pushinteger(hlua->T, e_server->safe.rid);
9393 lua_settable(hlua->T, -3);
9394 /* Add server proxy name */
9395 lua_pushstring(hlua->T, "proxy_name");
9396 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9397 lua_settable(hlua->T, -3);
Aurelien DARRAGON55f84c72023-03-22 17:49:04 +01009398 /* Add server proxy uuid */
9399 lua_pushstring(hlua->T, "proxy_uuid");
9400 lua_pushinteger(hlua->T, e_server->safe.proxy_uuid);
9401 lua_settable(hlua->T, -3);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009402
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009403 /* special events, fetch additional info with explicit type casting */
9404 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_STATE, event)) {
9405 struct event_hdl_cb_data_server_state *state = data;
9406 int it;
9407
9408 if (!lua_checkstack(hlua->T, 20))
9409 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9410
9411 /* state subclass */
9412 lua_pushstring(hlua->T, "state");
9413 lua_newtable(hlua->T);
9414
9415 lua_pushstring(hlua->T, "admin");
9416 lua_pushboolean(hlua->T, state->safe.type);
9417 lua_settable(hlua->T, -3);
9418
9419 /* is it because of a check ? */
9420 if (!state->safe.type &&
9421 (state->safe.op_st_chg.cause == SRV_OP_STCHGC_HEALTH ||
9422 state->safe.op_st_chg.cause == SRV_OP_STCHGC_AGENT)) {
9423 /* yes, provide check result */
9424 lua_pushstring(hlua->T, "check");
9425 lua_newtable(hlua->T);
9426 hlua_event_hdl_cb_push_event_checkres(hlua->T, &state->safe.op_st_chg.check);
9427 lua_settable(hlua->T, -3); /* check table */
9428 }
9429
9430 lua_pushstring(hlua->T, "cause");
9431 if (state->safe.type)
9432 lua_pushstring(hlua->T, srv_adm_st_chg_cause(state->safe.adm_st_chg.cause));
9433 else
9434 lua_pushstring(hlua->T, srv_op_st_chg_cause(state->safe.op_st_chg.cause));
9435 lua_settable(hlua->T, -3);
9436
9437 /* old_state, new_state */
9438 for (it = 0; it < 2; it++) {
9439 enum srv_state srv_state = (!it) ? state->safe.old_state : state->safe.new_state;
9440
9441 lua_pushstring(hlua->T, (!it) ? "old_state" : "new_state");
9442 switch (srv_state) {
9443 case SRV_ST_STOPPED:
9444 lua_pushstring(hlua->T, "STOPPED");
9445 break;
9446 case SRV_ST_STOPPING:
9447 lua_pushstring(hlua->T, "STOPPING");
9448 break;
9449 case SRV_ST_STARTING:
9450 lua_pushstring(hlua->T, "STARTING");
9451 break;
9452 case SRV_ST_RUNNING:
9453 lua_pushstring(hlua->T, "RUNNING");
9454 break;
9455 default:
9456 lua_pushnil(hlua->T);
9457 break;
9458 }
9459 lua_settable(hlua->T, -3);
9460 }
9461
9462 /* requeued */
9463 lua_pushstring(hlua->T, "requeued");
9464 lua_pushinteger(hlua->T, state->safe.requeued);
9465 lua_settable(hlua->T, -3);
9466
9467 lua_settable(hlua->T, -3); /* state table */
9468 }
Aurelien DARRAGON948dd3d2023-04-26 11:27:09 +02009469 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_ADMIN, event)) {
9470 struct event_hdl_cb_data_server_admin *admin = data;
9471 int it;
9472
9473 if (!lua_checkstack(hlua->T, 20))
9474 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9475
9476 /* admin subclass */
9477 lua_pushstring(hlua->T, "admin");
9478 lua_newtable(hlua->T);
9479
9480 lua_pushstring(hlua->T, "cause");
9481 lua_pushstring(hlua->T, srv_adm_st_chg_cause(admin->safe.cause));
9482 lua_settable(hlua->T, -3);
9483
9484 /* old_admin, new_admin */
9485 for (it = 0; it < 2; it++) {
9486 enum srv_admin srv_admin = (!it) ? admin->safe.old_admin : admin->safe.new_admin;
9487
9488 lua_pushstring(hlua->T, (!it) ? "old_admin" : "new_admin");
9489
9490 /* admin state matrix */
9491 lua_newtable(hlua->T);
9492
9493 lua_pushstring(hlua->T, "MAINT");
9494 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_MAINT);
9495 lua_settable(hlua->T, -3);
9496 lua_pushstring(hlua->T, "FMAINT");
9497 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FMAINT);
9498 lua_settable(hlua->T, -3);
9499 lua_pushstring(hlua->T, "IMAINT");
9500 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IMAINT);
9501 lua_settable(hlua->T, -3);
9502 lua_pushstring(hlua->T, "RMAINT");
9503 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_RMAINT);
9504 lua_settable(hlua->T, -3);
9505 lua_pushstring(hlua->T, "CMAINT");
9506 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_CMAINT);
9507 lua_settable(hlua->T, -3);
9508
9509 lua_pushstring(hlua->T, "DRAIN");
9510 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_DRAIN);
9511 lua_settable(hlua->T, -3);
9512 lua_pushstring(hlua->T, "FDRAIN");
9513 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FDRAIN);
9514 lua_settable(hlua->T, -3);
9515 lua_pushstring(hlua->T, "IDRAIN");
9516 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IDRAIN);
9517 lua_settable(hlua->T, -3);
9518
9519 lua_settable(hlua->T, -3); /* matrix table */
9520 }
9521 /* requeued */
9522 lua_pushstring(hlua->T, "requeued");
9523 lua_pushinteger(hlua->T, admin->safe.requeued);
9524 lua_settable(hlua->T, -3);
9525
9526 lua_settable(hlua->T, -3); /* admin table */
9527 }
Aurelien DARRAGON0bd53b22023-03-30 15:53:33 +02009528 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_CHECK, event)) {
9529 struct event_hdl_cb_data_server_check *check = data;
9530
9531 if (!lua_checkstack(hlua->T, 20))
9532 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9533
9534 /* check subclass */
9535 lua_pushstring(hlua->T, "check");
9536 lua_newtable(hlua->T);
9537
9538 /* check result snapshot */
9539 hlua_event_hdl_cb_push_event_checkres(hlua->T, &check->safe.res);
9540
9541 lua_settable(hlua->T, -3); /* check table */
9542 }
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009543
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009544 /* attempt to provide reference server object
9545 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9546 */
Aurelien DARRAGON3d9bf4e2023-03-22 17:46:12 +01009547 px = proxy_find_by_id(e_server->safe.proxy_uuid, PR_CAP_BE, 0);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009548 BUG_ON(!px);
9549 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9550 if (server) {
9551 lua_pushstring(hlua->T, "reference");
9552 hlua_fcn_new_server(hlua->T, server);
9553 lua_settable(hlua->T, -3);
9554 }
9555 }
9556 /* sub mgmt */
9557 hlua->nargs += 1;
9558 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
Aurelien DARRAGON096b3832023-04-20 11:32:46 +02009559
9560 /* when? */
9561 hlua->nargs += 1;
9562 lua_pushinteger(hlua->T, e->when.tv_sec);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009563}
9564
9565/* events runner: if there's an ongoing hlua event handling process, finish it
9566 * then, check if there are new events waiting to be processed
9567 * (events are processed sequentially)
9568 *
9569 * We have a safety measure to warn/guard if the event queue is growing up
9570 * too much due to many events being generated and lua handler is unable to
9571 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9572 * TODO: make it tunable
9573 */
9574static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9575{
9576 struct hlua_event_sub *hlua_sub = context;
9577 struct event_hdl_async_event *event;
9578 const char *error = NULL;
9579
9580 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009581 const char *trace = NULL;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009582
9583 /* We reached the limit of pending events in the queue: we should
9584 * warn the user, and temporarily pause the subscription to give a chance
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009585 * to the handler to catch up? (it also prevents resource shortage since
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009586 * the queue could grow indefinitely otherwise)
9587 * TODO: find a way to inform the handler that it missed some events
9588 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9589 *
9590 * Nonetheless, reaching this limit means that the handler is not fast enough
9591 * and/or that it subscribed to events that happen too frequently and did not
9592 * expect it. This could come from an inadequate design in the user's script.
9593 */
9594 event_hdl_pause(hlua_sub->sub);
9595 hlua_sub->paused = 1;
9596
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009597 if (SET_SAFE_LJMP(hlua_sub->hlua)) {
9598 /* The following Lua call may fail. */
9599 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9600 /* At this point the execution is safe. */
9601 RESET_SAFE_LJMP(hlua_sub->hlua);
9602 } else {
9603 /* Lua error was raised while fetching lua trace from current ctx */
9604 SEND_ERR(NULL, "Lua event_hdl: unexpected error (memory failure?).\n");
9605 }
9606 ha_warning("Lua event_hdl: pausing the subscription because the handler fails "
9607 "to keep up the pace (%u unconsumed events) from %s.\n",
9608 event_hdl_async_equeue_size(&hlua_sub->equeue),
9609 (trace) ? trace : "[unknown]");
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009610 }
9611
9612 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9613 /* ongoing hlua event handler, resume it */
9614 hlua_event_handler(hlua_sub->hlua);
9615 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9616 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9617 /* ending event: no more events to come */
9618 event_hdl_async_free_event(event);
9619 task_destroy(task);
9620 hlua_event_subscription_destroy(hlua_sub);
9621 return NULL;
9622 }
9623 /* new event: start processing it */
9624
9625 /* The following Lua calls can fail. */
9626 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9627 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009628 error = hlua_tostring_safe(hlua_sub->hlua->T, -1);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009629 else
9630 error = "critical error";
9631 ha_alert("Lua event_hdl: %s.\n", error);
9632 goto skip_event;
9633 }
9634
9635 /* Check stack available size. */
9636 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9637 ha_alert("Lua event_hdl: full stack.\n");
9638 RESET_SAFE_LJMP(hlua_sub->hlua);
9639 goto skip_event;
9640 }
9641
9642 /* Restore the function in the stack. */
9643 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9644
9645 /* push args */
9646 hlua_sub->hlua->nargs = 0;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009647 MAY_LJMP(hlua_event_hdl_cb_push_args(hlua_sub, event));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009648
9649 /* At this point the execution is safe. */
9650 RESET_SAFE_LJMP(hlua_sub->hlua);
9651
9652 /* At this point the event was successfully translated into hlua ctx,
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009653 * or hlua error occurred, so we can safely discard it
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009654 */
9655 event_hdl_async_free_event(event);
9656 event = NULL;
9657
9658 hlua_event_handler(hlua_sub->hlua);
9659 skip_event:
9660 if (event)
9661 event_hdl_async_free_event(event);
9662
9663 }
9664
9665 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9666 /* we just finished the processing of one event..
9667 * check for new events before becoming idle
9668 */
9669 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9670 /* more events to process, make sure the task
9671 * will be resumed ASAP to process pending events
9672 */
9673 task_wakeup(task, TASK_WOKEN_OTHER);
9674 }
9675 else if (hlua_sub->paused) {
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009676 /* empty queue, the handler caught up: resume the subscription */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009677 event_hdl_resume(hlua_sub->sub);
9678 hlua_sub->paused = 0;
9679 }
9680 }
9681
9682 return task;
9683}
9684
9685/* Must be called directly under lua protected/safe environment
9686 * (not from external callback)
9687 * <fcn_ref> should NOT be dropped after the function successfully returns:
9688 * it will be done automatically in hlua_event_subscription_destroy() when the
9689 * subscription ends.
9690 *
9691 * Returns the new subscription on success and NULL on failure (memory error)
9692 */
9693static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9694 int state_id, int fcn_ref)
9695{
9696 struct hlua_event_sub *hlua_sub;
9697 struct task *task = NULL;
9698
9699 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9700 if (!hlua_sub)
9701 goto mem_error;
9702 hlua_sub->task = NULL;
9703 hlua_sub->hlua = NULL;
9704 hlua_sub->paused = 0;
9705 if ((task = task_new_here()) == NULL) {
9706 ha_alert("out of memory while allocating hlua event task");
9707 goto mem_error;
9708 }
9709 task->process = hlua_event_runner;
9710 task->context = hlua_sub;
9711 event_hdl_async_equeue_init(&hlua_sub->equeue);
9712 hlua_sub->task = task;
9713 hlua_sub->fcn_ref = fcn_ref;
9714 hlua_sub->state_id = state_id;
9715 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9716 if (!hlua_sub->hlua)
9717 goto mem_error;
9718 HLUA_INIT(hlua_sub->hlua);
9719 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9720 goto mem_error;
9721
9722 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9723 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9724 task,
9725 hlua_sub,
9726 NULL));
9727 if (!hlua_sub->sub)
9728 goto mem_error;
9729
9730 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9731
9732 mem_error:
9733 if (hlua_sub) {
Tim Duesterhusfe83f582023-04-22 17:47:34 +02009734 task_destroy(hlua_sub->task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009735 if (hlua_sub->hlua)
9736 hlua_ctx_destroy(hlua_sub->hlua);
9737 pool_free(pool_head_hlua_event_sub, hlua_sub);
9738 }
9739
9740 return NULL;
9741}
9742
9743/* looks for an array of strings referring to a composition of event_hdl subscription
9744 * types at <index> in <L> stack
9745 */
9746__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9747{
9748 struct event_hdl_sub_type subscriptions;
9749 const char *msg;
9750
9751 if (lua_type(L, index) != LUA_TTABLE) {
9752 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9753 luaL_argerror(L, index, msg);
9754 }
9755
9756 subscriptions = EVENT_HDL_SUB_NONE;
9757
9758 /* browse the argument as an array. */
9759 lua_pushnil(L);
9760 while (lua_next(L, index) != 0) {
9761 if (lua_type(L, -1) != LUA_TSTRING) {
9762 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9763 luaL_argerror(L, index, msg);
9764 }
9765
9766 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9767 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9768 luaL_argerror(L, index, msg);
9769 }
9770
9771 /* perform subscriptions |= current sub */
9772 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9773
9774 /* pop the current value. */
9775 lua_pop(L, 1);
9776 }
9777
9778 return subscriptions;
9779}
9780
9781/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9782 * the function to prevent LJMP
9783 *
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009784 * If no error occurred, the function returns 1, else it returns 0 and
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009785 * the error message is pushed at the top of the stack
9786 */
9787__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9788{
9789 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9790
9791 /* this function may raise errors */
9792 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9793}
9794static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9795{
9796 if (!lua_checkstack(L, 2))
9797 return 0;
9798 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9799 lua_pushlightuserdata(L, sub);
9800 switch (lua_pcall(L, 1, 1, 0)) {
9801 case LUA_OK:
9802 return 1;
9803 default:
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009804 /* error was caught */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009805 return 0;
9806 }
9807}
9808
9809/* This function is a LUA helper used for registering lua event callbacks.
9810 * It expects an event subscription array and the function to be executed
9811 * when subscribed events occur (stack arguments).
9812 * It can be called from the "init" section, "post init" or during the runtime.
9813 *
9814 * <sub_list> is the subscription list where the subscription will be attempted
9815 *
9816 * Pushes the newly allocated subscription on the stack on success
9817 */
9818__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9819{
9820 struct hlua *hlua;
9821 struct event_hdl_sub *sub;
9822 struct event_hdl_sub_type subscriptions;
9823 int fcn_ref;
9824 int state_id;
9825
9826 MAY_LJMP(check_args(L, 2, "event_sub"));
9827
9828 /* Get the reference state */
9829 hlua = hlua_gethlua(L);
9830 if (hlua)
9831 /* we are in runtime processing, any thread may subscribe to events:
9832 * subscription events will be handled by the thread who performed
9833 * the registration.
9834 */
9835 state_id = hlua->state_id;
9836 else {
9837 /* we are in initialization mode, only thread 0 (actual calling thread)
9838 * may subscribe to events to prevent the same handler (from different lua
9839 * stacks) from being registered multiple times
9840 *
9841 * hlua_state_id == 0: monostack (lua-load)
9842 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9843 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9844 */
9845 if (hlua_state_id > 1)
9846 return 0; /* skip registration */
9847 state_id = hlua_state_id;
9848 }
9849
9850 /* First argument : event subscriptions. */
9851 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9852
9853 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9854 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9855 return 0; /* Never reached */
9856 }
9857
9858 /* Second argument : lua function. */
9859 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9860
9861 /* try to subscribe */
9862 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9863 if (!sub) {
9864 hlua_unref(L, fcn_ref);
9865 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9866 return 0; /* Never reached */
9867 }
9868
9869 /* push the subscription to the stack
9870 *
9871 * Here we use the safe function so that lua errors will be
9872 * handled explicitly to prevent 'sub' from being lost
9873 */
9874 if (!hlua_new_event_sub_safe(L, sub)) {
9875 /* Some events could already be pending in the handler's queue.
9876 * However it is wiser to cancel the subscription since we are unable to
9877 * provide a valid reference to it.
9878 * Pending events will be delivered (unless lua keeps raising errors).
9879 */
9880 event_hdl_unsubscribe(sub); /* cancel the subscription */
9881 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9882 return 0; /* Never reached */
9883 }
9884 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9885
9886 return 1;
9887}
9888
9889/* This function is a LUA wrapper used for registering global lua event callbacks
9890 * The new subscription is pushed onto the stack on success
9891 * Returns the number of arguments pushed to the stack (1 for success)
9892 */
9893__LJMP static int hlua_event_global_sub(lua_State *L)
9894{
9895 /* NULL <sub_list> = global subscription list */
9896 return MAY_LJMP(hlua_event_sub(L, NULL));
9897}
9898
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009899/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9900 * doesn't allow "yield" functions because the HAProxy engine cannot
9901 * resume converters.
9902 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009903static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009904{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009905 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009906 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009907 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009908
Willy Tarreaube508f12016-03-10 11:47:01 +01009909 if (!stream)
9910 return 0;
9911
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02009912 if (!hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn))) {
9913 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9914 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009915 }
9916
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009917 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009918 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009919
9920 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009921 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009922 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009923 error = hlua_tostring_safe(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009924 else
9925 error = "critical error";
9926 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009927 return 0;
9928 }
9929
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009930 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009931 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009932 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009933 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009934 return 0;
9935 }
9936
9937 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009938 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009939
9940 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009941 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009942 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009943 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009944 return 0;
9945 }
Aurelien DARRAGON41217722023-05-17 10:44:47 +02009946 MAY_LJMP(hlua_smp2lua(stream->hlua->T, smp));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009947 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009948
9949 /* push keywords in the stack. */
9950 if (arg_p) {
9951 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009952 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009953 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009954 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009955 return 0;
9956 }
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +02009957 MAY_LJMP(hlua_arg2lua(stream->hlua->T, arg_p));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009958 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009959 }
9960 }
9961
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009962 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009963 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009964
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009965 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009966 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009967 }
9968
9969 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009970 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009971 /* finished. */
9972 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009973 /* If the stack is empty, the function fails. */
9974 if (lua_gettop(stream->hlua->T) <= 0)
9975 return 0;
9976
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009977 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009978 hlua_lua2smp(stream->hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02009979 /* dup the smp before popping the related lua value and
9980 * returning it to haproxy
9981 */
9982 smp_dup(smp);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009983 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009984 return 1;
9985
9986 /* yield. */
9987 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009988 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009989 return 0;
9990
9991 /* finished with error. */
9992 case HLUA_E_ERRMSG:
9993 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009994 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +01009995 fcn->name, hlua_tostring_safe(stream->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009996 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009997 return 0;
9998
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009999 case HLUA_E_ETMOUT:
10000 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
10001 return 0;
10002
10003 case HLUA_E_NOMEM:
10004 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
10005 return 0;
10006
10007 case HLUA_E_YIELD:
10008 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
10009 return 0;
10010
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010011 case HLUA_E_ERR:
10012 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010013 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +010010014 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010015
10016 default:
10017 return 0;
10018 }
10019}
10020
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010021/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
10022 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +010010023 * resume sample-fetches. This function will be called by the sample
10024 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010025 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +020010026static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
10027 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010028{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010029 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +020010030 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010031 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010032 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010033
Willy Tarreaube508f12016-03-10 11:47:01 +010010034 if (!stream)
10035 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +010010036
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020010037 if (!hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn))) {
10038 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
10039 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010040 }
10041
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010042 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010043 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010044
10045 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010046 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010047 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010048 error = hlua_tostring_safe(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010049 else
10050 error = "critical error";
10051 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010052 return 0;
10053 }
10054
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010055 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010056 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010057 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010058 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010059 return 0;
10060 }
10061
10062 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010063 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010064
10065 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +020010066 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010067 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010068 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010069 return 0;
10070 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010071 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010072
10073 /* push keywords in the stack. */
10074 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
10075 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010076 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010077 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010078 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010079 return 0;
10080 }
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +020010081 MAY_LJMP(hlua_arg2lua(stream->hlua->T, arg_p));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010082 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010083 }
10084
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010085 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010086 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010087
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010088 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010089 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010090 }
10091
10092 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010093 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010094 /* finished. */
10095 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +020010096 /* If the stack is empty, the function fails. */
10097 if (lua_gettop(stream->hlua->T) <= 0)
10098 return 0;
10099
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010100 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010101 hlua_lua2smp(stream->hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +020010102 /* dup the smp before popping the related lua value and
10103 * returning it to haproxy
10104 */
10105 smp_dup(smp);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010106 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010107
10108 /* Set the end of execution flag. */
10109 smp->flags &= ~SMP_F_MAY_CHANGE;
10110 return 1;
10111
10112 /* yield. */
10113 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010114 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010115 return 0;
10116
10117 /* finished with error. */
10118 case HLUA_E_ERRMSG:
10119 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010120 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010121 fcn->name, hlua_tostring_safe(stream->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010122 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010123 return 0;
10124
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010125 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010126 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
10127 return 0;
10128
10129 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010130 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
10131 return 0;
10132
10133 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010134 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
10135 return 0;
10136
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010137 case HLUA_E_ERR:
10138 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010139 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +010010140 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010141
10142 default:
10143 return 0;
10144 }
10145}
10146
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010147/* This function is an LUA binding used for registering
10148 * "sample-conv" functions. It expects a converter name used
10149 * in the haproxy configuration file, and an LUA function.
10150 */
10151__LJMP static int hlua_register_converters(lua_State *L)
10152{
10153 struct sample_conv_kw_list *sck;
10154 const char *name;
10155 int ref;
10156 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +020010157 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010158 struct sample_conv *sc;
10159 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010160
10161 MAY_LJMP(check_args(L, 2, "register_converters"));
10162
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010163 if (hlua_gethlua(L)) {
10164 /* runtime processing */
10165 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
10166 }
10167
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010168 /* First argument : converter name. */
10169 name = MAY_LJMP(luaL_checkstring(L, 1));
10170
10171 /* Second argument : lua function. */
10172 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10173
Thierry Fournierf67442e2020-11-28 20:41:07 +010010174 /* Check if the converter is already registered */
10175 trash = get_trash_chunk();
10176 chunk_printf(trash, "lua.%s", name);
10177 sc = find_sample_conv(trash->area, trash->data);
10178 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010179 fcn = sc->private;
10180 if (fcn->function_ref[hlua_state_id] != -1) {
10181 ha_warning("Trying to register converter 'lua.%s' more than once. "
10182 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010183 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010184 }
10185 fcn->function_ref[hlua_state_id] = ref;
10186 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010187 }
10188
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010189 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010190 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010191 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +020010192 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010193 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010194 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +020010195 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010196
10197 /* Fill fcn. */
10198 fcn->name = strdup(name);
10199 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +020010200 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010201 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010202
10203 /* List head */
10204 sck->list.n = sck->list.p = NULL;
10205
10206 /* converter keyword. */
10207 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010208 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010209 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +020010210 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010211
10212 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
10213 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010214 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 +010010215 sck->kw[0].val_args = NULL;
10216 sck->kw[0].in_type = SMP_T_STR;
10217 sck->kw[0].out_type = SMP_T_STR;
10218 sck->kw[0].private = fcn;
10219
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010220 /* Register this new converter */
10221 sample_register_convs(sck);
10222
10223 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +020010224
10225 alloc_error:
10226 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010227 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +020010228 ha_free(&sck);
10229 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10230 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010231}
10232
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010233/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010234 * "sample-fetch" functions. It expects a converter name used
10235 * in the haproxy configuration file, and an LUA function.
10236 */
10237__LJMP static int hlua_register_fetches(lua_State *L)
10238{
10239 const char *name;
10240 int ref;
10241 int len;
10242 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +020010243 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010244 struct sample_fetch *sf;
10245 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010246
10247 MAY_LJMP(check_args(L, 2, "register_fetches"));
10248
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010249 if (hlua_gethlua(L)) {
10250 /* runtime processing */
10251 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
10252 }
10253
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010254 /* First argument : sample-fetch name. */
10255 name = MAY_LJMP(luaL_checkstring(L, 1));
10256
10257 /* Second argument : lua function. */
10258 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10259
Thierry Fournierf67442e2020-11-28 20:41:07 +010010260 /* Check if the sample-fetch is already registered */
10261 trash = get_trash_chunk();
10262 chunk_printf(trash, "lua.%s", name);
10263 sf = find_sample_fetch(trash->area, trash->data);
10264 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010265 fcn = sf->private;
10266 if (fcn->function_ref[hlua_state_id] != -1) {
10267 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
10268 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010269 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010270 }
10271 fcn->function_ref[hlua_state_id] = ref;
10272 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010273 }
10274
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010275 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010276 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010277 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +020010278 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010279 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010280 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +020010281 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010282
10283 /* Fill fcn. */
10284 fcn->name = strdup(name);
10285 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +020010286 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010287 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010288
10289 /* List head */
10290 sfk->list.n = sfk->list.p = NULL;
10291
10292 /* sample-fetch keyword. */
10293 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010294 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010295 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +020010296 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010297
10298 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
10299 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010300 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 +010010301 sfk->kw[0].val_args = NULL;
10302 sfk->kw[0].out_type = SMP_T_STR;
10303 sfk->kw[0].use = SMP_USE_HTTP_ANY;
10304 sfk->kw[0].val = 0;
10305 sfk->kw[0].private = fcn;
10306
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010307 /* Register this new fetch. */
10308 sample_register_fetches(sfk);
10309
10310 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +020010311
10312 alloc_error:
10313 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010314 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +020010315 ha_free(&sfk);
10316 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10317 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010318}
10319
Christopher Faulet501465d2020-02-26 14:54:16 +010010320/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010321 */
Christopher Faulet501465d2020-02-26 14:54:16 +010010322__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010323{
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010324 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010325 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +020010326 int wakeup_ms; // tick value
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010327
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010328 /* Get hlua struct, or NULL if we execute from main lua state */
10329 hlua = hlua_gethlua(L);
10330 if (!hlua) {
10331 return 0;
10332 }
10333
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010334 MAY_LJMP(check_args(L, 1, "wake_time"));
10335
10336 delay = MAY_LJMP(luaL_checkinteger(L, 1));
10337 wakeup_ms = tick_add(now_ms, delay);
10338 hlua->wake_time = wakeup_ms;
10339 return 0;
10340}
10341
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010342/* This function is a wrapper to execute each LUA function declared as an action
10343 * wrapper during the initialisation period. This function may return any
10344 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
10345 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
10346 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010347 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010348static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +020010349 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010350{
10351 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010352 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010353 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010354 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010355
10356 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +010010357 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
10358 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
10359 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
10360 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010361 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010362 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010363 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010364 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010365
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020010366 if (!hlua_stream_ctx_prepare(s, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn))) {
10367 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
10368 rule->arg.hlua_rule->fcn->name);
10369 goto end;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010370 }
10371
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010372 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010373 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010374
10375 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010376 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010377 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010378 error = hlua_tostring_safe(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010379 else
10380 error = "critical error";
10381 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010382 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010383 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010384 }
10385
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010386 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010387 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010388 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010389 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010390 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010391 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010392 }
10393
10394 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010395 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010396
Willy Tarreau87b09662015-04-03 00:22:06 +020010397 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +020010398 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010399 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010400 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010401 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010402 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010403 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010404 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010405
10406 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010407 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010408 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010409 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010410 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010411 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010412 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010413 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010414 lua_pushstring(s->hlua->T, *arg);
10415 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010416 }
10417
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010418 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010419 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010420
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010421 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010422 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010423 }
10424
10425 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +010010426 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010427 /* finished. */
10428 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010429 /* Catch the return value */
10430 if (lua_gettop(s->hlua->T) > 0)
10431 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010432
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010433 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +020010434 if (act_ret == ACT_RET_YIELD) {
10435 if (flags & ACT_OPT_FINAL)
10436 goto err_yield;
10437
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010438 if (dir == SMP_OPT_DIR_REQ)
10439 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10440 s->hlua->wake_time);
10441 else
10442 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10443 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010444 }
10445 goto end;
10446
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010447 /* yield. */
10448 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +010010449 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010450 if (dir == SMP_OPT_DIR_REQ)
10451 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10452 s->hlua->wake_time);
10453 else
10454 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10455 s->hlua->wake_time);
10456
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010457 /* Some actions can be wake up when a "write" event
10458 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010459 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010460 */
Christopher Faulet51fa3582019-07-26 14:54:52 +020010461 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010462 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010463 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010464 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010465 act_ret = ACT_RET_YIELD;
10466 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010467
10468 /* finished with error. */
10469 case HLUA_E_ERRMSG:
10470 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010471 SEND_ERR(px, "Lua function '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010472 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010473 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010474 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010475
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010476 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010477 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010478 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010479
10480 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010481 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010482 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010483
10484 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +020010485 err_yield:
10486 act_ret = ACT_RET_CONT;
Aurelien DARRAGONcf5b75e2023-08-31 21:45:21 +020010487 SEND_ERR(px, "Lua function '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010488 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010489 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010490
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010491 case HLUA_E_ERR:
10492 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010493 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010494 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010495
10496 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010497 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010498 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010499
10500 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010501 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010502 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010503 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010504}
10505
Willy Tarreau144f84a2021-03-02 16:09:26 +010010506struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010507{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010508 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010509
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010510 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010511 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010512 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010513}
10514
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010515static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010516{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010517 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010518 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010519 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010520 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010521 struct task *task;
10522 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010523 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010524
Willy Tarreaubafbe012017-11-24 17:34:44 +010010525 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010526 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010527 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010528 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010529 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010530 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010531 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010532 tcp_ctx->hlua = hlua;
10533 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010534
10535 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010536 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010537 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010538 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010539 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010540 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010541 }
10542 task->nice = 0;
10543 task->context = ctx;
10544 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010545 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010546
10547 /* In the execution wrappers linked with a stream, the
10548 * Lua context can be not initialized. This behavior
10549 * permits to save performances because a systematic
10550 * Lua initialization cause 5% performances loss.
10551 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010552 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010553 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010554 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010555 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010556 }
10557
10558 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010559 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010560
10561 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010562 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010563 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010564 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010565 else
10566 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010567 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010568 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010569 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010570 }
10571
10572 /* Check stack available size. */
10573 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010574 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010575 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010576 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010577 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010578 }
10579
10580 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010581 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010582
10583 /* Create and and push object stream in the stack. */
10584 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010585 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010586 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010587 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010588 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010589 }
10590 hlua->nargs = 1;
10591
10592 /* push keywords in the stack. */
10593 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10594 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010595 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010596 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010597 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010598 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010599 }
10600 lua_pushstring(hlua->T, *arg);
10601 hlua->nargs++;
10602 }
10603
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010604 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010605
10606 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010607 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010608 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010609
Christopher Fauletc9929382022-05-12 11:52:27 +020010610 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010611}
10612
Willy Tarreau60409db2019-08-21 14:14:50 +020010613void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010614{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010615 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010616 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010617 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010618 struct act_rule *rule = ctx->rule;
10619 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010620 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010621
Christopher Faulet31572222023-03-31 11:13:48 +020010622 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10623 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010624
Christopher Faulet31572222023-03-31 11:13:48 +020010625 /* The applet execution is already done. */
10626 if (tcp_ctx->flags & APPLET_DONE)
10627 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010628
10629 /* Execute the function. */
10630 switch (hlua_ctx_resume(hlua, 1)) {
10631 /* finished. */
10632 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010633 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010634 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10635 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010636
10637 /* yield. */
10638 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010639 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010640 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010641 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010642
10643 /* finished with error. */
10644 case HLUA_E_ERRMSG:
10645 /* Display log. */
10646 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010647 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010648 lua_pop(hlua->T, 1);
10649 goto error;
10650
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010651 case HLUA_E_ETMOUT:
10652 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010653 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010654 goto error;
10655
10656 case HLUA_E_NOMEM:
10657 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010658 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010659 goto error;
10660
10661 case HLUA_E_YIELD: /* unexpected */
10662 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010663 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010664 goto error;
10665
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010666 case HLUA_E_ERR:
10667 /* Display log. */
10668 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010669 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010670 goto error;
10671
10672 default:
10673 goto error;
10674 }
10675
Christopher Faulet31572222023-03-31 11:13:48 +020010676out:
10677 /* eat the whole request */
10678 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10679 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010680
Christopher Faulet31572222023-03-31 11:13:48 +020010681error:
10682 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010683 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010684 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010685}
10686
10687static void hlua_applet_tcp_release(struct appctx *ctx)
10688{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010689 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10690
10691 task_destroy(tcp_ctx->task);
10692 tcp_ctx->task = NULL;
10693 hlua_ctx_destroy(tcp_ctx->hlua);
10694 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010695}
10696
Christopher Fauletc9929382022-05-12 11:52:27 +020010697/* The function returns 0 if the initialisation is complete or -1 if
10698 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010699 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010700static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010701{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010702 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010703 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010704 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010705 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010706 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010707 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010708 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010709 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010710
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010711 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010712 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010713 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010714 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010715 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010716 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010717 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010718 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010719 http_ctx->hlua = hlua;
10720 http_ctx->left_bytes = -1;
10721 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010722
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010723 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010724 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010725
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010726 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010727 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010728 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010729 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010730 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010731 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010732 }
10733 task->nice = 0;
10734 task->context = ctx;
10735 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010736 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010737
10738 /* In the execution wrappers linked with a stream, the
10739 * Lua context can be not initialized. This behavior
10740 * permits to save performances because a systematic
10741 * Lua initialization cause 5% performances loss.
10742 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010743 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010744 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010745 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010746 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010747 }
10748
10749 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010750 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010751
10752 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010753 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010754 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010755 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010756 else
10757 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010758 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010759 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010760 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010761 }
10762
10763 /* Check stack available size. */
10764 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010765 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010766 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010767 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010768 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010769 }
10770
10771 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010772 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010773
10774 /* Create and and push object stream in the stack. */
10775 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010776 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010777 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010778 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010779 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010780 }
10781 hlua->nargs = 1;
10782
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010783 /* push keywords in the stack. */
10784 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10785 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010786 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010787 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010788 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010789 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010790 }
10791 lua_pushstring(hlua->T, *arg);
10792 hlua->nargs++;
10793 }
10794
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010795 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010796
10797 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010798 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010799
Christopher Fauletc9929382022-05-12 11:52:27 +020010800 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010801}
10802
Willy Tarreau60409db2019-08-21 14:14:50 +020010803void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010804{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010805 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010806 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010807 struct stream *strm = __sc_strm(sc);
10808 struct channel *req = sc_oc(sc);
10809 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010810 struct act_rule *rule = ctx->rule;
10811 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010812 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010813 struct htx *req_htx, *res_htx;
10814
10815 res_htx = htx_from_buf(&res->buf);
10816
Christopher Faulet31572222023-03-31 11:13:48 +020010817 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10818 goto out;
10819
10820 /* The applet execution is already done. */
10821 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010822 goto out;
10823
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010824 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010825 if (!b_size(&res->buf)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010826 sc_need_room(sc, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010827 goto out;
10828 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010829
10830 /* Set the currently running flag. */
10831 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010832 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010833 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010834 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010835 goto out;
10836 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010837 }
10838
Christopher Faulet31572222023-03-31 11:13:48 +020010839 /* Execute the function. */
10840 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010841 /* finished. */
10842 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010843 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010844 break;
10845
10846 /* yield. */
10847 case HLUA_E_AGAIN:
10848 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010849 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010850 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010851
10852 /* finished with error. */
10853 case HLUA_E_ERRMSG:
10854 /* Display log. */
10855 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010010856 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010857 lua_pop(hlua->T, 1);
10858 goto error;
10859
10860 case HLUA_E_ETMOUT:
10861 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010862 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010863 goto error;
10864
10865 case HLUA_E_NOMEM:
10866 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010867 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010868 goto error;
10869
10870 case HLUA_E_YIELD: /* unexpected */
10871 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010872 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010873 goto error;
10874
10875 case HLUA_E_ERR:
10876 /* Display log. */
10877 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010878 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010879 goto error;
10880
10881 default:
10882 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010883 }
10884
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010885 if (http_ctx->flags & APPLET_DONE) {
10886 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010887 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010888
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010889 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010890 goto error;
10891
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010892 /* no more data are expected. If the response buffer is empty
10893 * for a chunked message, be sure to add something (EOT block in
10894 * this case) to have something to send. It is important to be
10895 * sure the EOM flags will be handled by the endpoint.
10896 */
10897 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10898 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010899 sc_need_room(sc, sizeof(struct htx_blk)+1);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010900 goto out;
10901 }
10902 channel_add_input(res, 1);
10903 }
10904
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010905 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010906 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010907 strm->txn->status = http_ctx->status;
10908 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010909 }
10910
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010911 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010912 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010913 /* eat the whole request */
10914 if (co_data(req)) {
10915 req_htx = htx_from_buf(&req->buf);
10916 co_htx_skip(req, req_htx, co_data(req));
10917 htx_to_buf(req_htx, &req->buf);
10918 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010919 return;
10920
10921 error:
10922
10923 /* If we are in HTTP mode, and we are not send any
10924 * data, return a 500 server error in best effort:
10925 * if there is no room available in the buffer,
10926 * just close the connection.
10927 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010928 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010929 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010930
10931 channel_erase(res);
10932 res->buf.data = b_data(err);
10933 memcpy(res->buf.area, b_head(err), b_data(err));
10934 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010935 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010936 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010937 }
Christopher Faulet31572222023-03-31 11:13:48 +020010938 else
10939 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10940
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010941 if (!(strm->flags & SF_ERR_MASK))
10942 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010943 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010944 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010945}
10946
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010947static void hlua_applet_http_release(struct appctx *ctx)
10948{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010949 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10950
10951 task_destroy(http_ctx->task);
10952 http_ctx->task = NULL;
10953 hlua_ctx_destroy(http_ctx->hlua);
10954 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010955}
10956
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010957/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010958 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010959 *
10960 * This function can fail with an abort() due to an Lua critical error.
10961 * We are in the configuration parsing process of HAProxy, this abort() is
10962 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010963 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010964static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10965 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010966{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010967 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010968 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010969
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010970 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010971 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010972 if (!rule->arg.hlua_rule) {
10973 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010974 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010975 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010976
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010977 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010978 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10979 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010980 if (!rule->arg.hlua_rule->args) {
10981 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010982 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010983 }
10984
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010985 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010986 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010987
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010988 /* Expect some arguments */
10989 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010990 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010991 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010992 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010993 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010994 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010995 if (!rule->arg.hlua_rule->args[i]) {
10996 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010997 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010998 }
10999 (*cur_arg)++;
11000 }
11001 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011002
Thierry FOURNIER42148732015-09-02 17:17:33 +020011003 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020011004 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020011005 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020011006
11007 error:
11008 if (rule->arg.hlua_rule) {
11009 if (rule->arg.hlua_rule->args) {
11010 for (i = 0; i < fcn->nargs; i++)
11011 ha_free(&rule->arg.hlua_rule->args[i]);
11012 ha_free(&rule->arg.hlua_rule->args);
11013 }
11014 ha_free(&rule->arg.hlua_rule);
11015 }
11016 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010011017}
11018
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011019static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
11020 struct act_rule *rule, char **err)
11021{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020011022 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011023
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010011024 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011025 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010011026 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011027 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010011028 * the call of this analyzer.
11029 */
11030 if (rule->from != ACT_F_HTTP_REQ) {
11031 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
11032 return ACT_RET_PRS_ERR;
11033 }
11034
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011035 /* Memory for the rule. */
11036 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11037 if (!rule->arg.hlua_rule) {
11038 memprintf(err, "out of memory error");
11039 return ACT_RET_PRS_ERR;
11040 }
11041
11042 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011043 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011044
11045 /* TODO: later accept arguments. */
11046 rule->arg.hlua_rule->args = NULL;
11047
11048 /* Add applet pointer in the rule. */
11049 rule->applet.obj_type = OBJ_TYPE_APPLET;
11050 rule->applet.name = fcn->name;
11051 rule->applet.init = hlua_applet_http_init;
11052 rule->applet.fct = hlua_applet_http_fct;
11053 rule->applet.release = hlua_applet_http_release;
11054 rule->applet.timeout = hlua_timeout_applet;
11055
11056 return ACT_RET_PRS_OK;
11057}
11058
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011059/* This function is an LUA binding used for registering
11060 * "sample-conv" functions. It expects a converter name used
11061 * in the haproxy configuration file, and an LUA function.
11062 */
11063__LJMP static int hlua_register_action(lua_State *L)
11064{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011065 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011066 const char *name;
11067 int ref;
11068 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011069 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011070 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011071 struct buffer *trash;
11072 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011073
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011074 /* Initialise the number of expected arguments at 0. */
11075 nargs = 0;
11076
11077 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
11078 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011079
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011080 if (hlua_gethlua(L)) {
11081 /* runtime processing */
11082 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
11083 }
11084
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011085 /* First argument : converter name. */
11086 name = MAY_LJMP(luaL_checkstring(L, 1));
11087
11088 /* Second argument : environment. */
11089 if (lua_type(L, 2) != LUA_TTABLE)
11090 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
11091
11092 /* Third argument : lua function. */
11093 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11094
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011095 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011096 if (lua_gettop(L) >= 4)
11097 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
11098
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011099 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011100 lua_pushnil(L);
11101 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011102 if (lua_type(L, -1) != LUA_TSTRING) {
11103 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011104 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011105 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011106
Thierry Fournierf67442e2020-11-28 20:41:07 +010011107 /* Check if action exists */
11108 trash = get_trash_chunk();
11109 chunk_printf(trash, "lua.%s", name);
11110 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
11111 akw = tcp_req_cont_action(trash->area);
11112 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
11113 akw = tcp_res_cont_action(trash->area);
11114 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
11115 akw = action_http_req_custom(trash->area);
11116 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
11117 akw = action_http_res_custom(trash->area);
11118 } else {
11119 akw = NULL;
11120 }
11121 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011122 fcn = akw->private;
11123 if (fcn->function_ref[hlua_state_id] != -1) {
11124 ha_warning("Trying to register action 'lua.%s' more than once. "
11125 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011126 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011127 }
11128 fcn->function_ref[hlua_state_id] = ref;
11129
11130 /* pop the environment string. */
11131 lua_pop(L, 1);
11132 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011133 }
11134
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011135 /* Check required environment. Only accepted "http" or "tcp". */
11136 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020011137 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011138 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011139 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011140 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011141 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011142 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011143
11144 /* Fill fcn. */
11145 fcn->name = strdup(name);
11146 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011147 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010011148 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011149
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011150 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011151 fcn->nargs = nargs;
11152
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011153 /* List head */
11154 akl->list.n = akl->list.p = NULL;
11155
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011156 /* action keyword. */
11157 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020011158 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011159 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011160 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011161
11162 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11163
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011164 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011165 akl->kw[0].private = fcn;
11166 akl->kw[0].parse = action_register_lua;
11167
11168 /* select the action registering point. */
11169 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
11170 tcp_req_cont_keywords_register(akl);
11171 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
11172 tcp_res_cont_keywords_register(akl);
11173 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
11174 http_req_keywords_register(akl);
11175 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
11176 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011177 else {
11178 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011179 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011180 if (akl)
11181 ha_free((char **)&(akl->kw[0].kw));
11182 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011183 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011184 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
11185 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011186 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011187
11188 /* pop the environment string. */
11189 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011190
11191 /* reset for next loop */
11192 akl = NULL;
11193 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011194 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011195 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011196
11197 alloc_error:
11198 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011199 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011200 ha_free(&akl);
11201 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11202 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011203}
11204
11205static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
11206 struct act_rule *rule, char **err)
11207{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020011208 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011209
Christopher Faulet280f85b2019-07-15 15:02:04 +020011210 if (px->mode == PR_MODE_HTTP) {
11211 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010011212 return ACT_RET_PRS_ERR;
11213 }
11214
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011215 /* Memory for the rule. */
11216 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11217 if (!rule->arg.hlua_rule) {
11218 memprintf(err, "out of memory error");
11219 return ACT_RET_PRS_ERR;
11220 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011221
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011222 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011223 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011224
11225 /* TODO: later accept arguments. */
11226 rule->arg.hlua_rule->args = NULL;
11227
11228 /* Add applet pointer in the rule. */
11229 rule->applet.obj_type = OBJ_TYPE_APPLET;
11230 rule->applet.name = fcn->name;
11231 rule->applet.init = hlua_applet_tcp_init;
11232 rule->applet.fct = hlua_applet_tcp_fct;
11233 rule->applet.release = hlua_applet_tcp_release;
11234 rule->applet.timeout = hlua_timeout_applet;
11235
11236 return 0;
11237}
11238
11239/* This function is an LUA binding used for registering
11240 * "sample-conv" functions. It expects a converter name used
11241 * in the haproxy configuration file, and an LUA function.
11242 */
11243__LJMP static int hlua_register_service(lua_State *L)
11244{
11245 struct action_kw_list *akl;
11246 const char *name;
11247 const char *env;
11248 int ref;
11249 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011250 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011251 struct buffer *trash;
11252 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011253
11254 MAY_LJMP(check_args(L, 3, "register_service"));
11255
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011256 if (hlua_gethlua(L)) {
11257 /* runtime processing */
11258 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
11259 }
11260
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011261 /* First argument : converter name. */
11262 name = MAY_LJMP(luaL_checkstring(L, 1));
11263
11264 /* Second argument : environment. */
11265 env = MAY_LJMP(luaL_checkstring(L, 2));
11266
11267 /* Third argument : lua function. */
11268 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11269
Thierry Fournierf67442e2020-11-28 20:41:07 +010011270 /* Check for service already registered */
11271 trash = get_trash_chunk();
11272 chunk_printf(trash, "lua.%s", name);
11273 akw = service_find(trash->area);
11274 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011275 fcn = akw->private;
11276 if (fcn->function_ref[hlua_state_id] != -1) {
11277 ha_warning("Trying to register service 'lua.%s' more than once. "
11278 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011279 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011280 }
11281 fcn->function_ref[hlua_state_id] = ref;
11282 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011283 }
11284
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011285 /* Allocate and fill the sample fetch keyword struct. */
11286 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
11287 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011288 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011289 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011290 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011291 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011292
11293 /* Fill fcn. */
11294 len = strlen("<lua.>") + strlen(name) + 1;
11295 fcn->name = calloc(1, len);
11296 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011297 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011298 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010011299 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011300
11301 /* List head */
11302 akl->list.n = akl->list.p = NULL;
11303
11304 /* converter keyword. */
11305 len = strlen("lua.") + strlen(name) + 1;
11306 akl->kw[0].kw = calloc(1, len);
11307 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011308 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011309
11310 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11311
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010011312 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011313 if (strcmp(env, "tcp") == 0)
11314 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011315 else if (strcmp(env, "http") == 0)
11316 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011317 else {
11318 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011319 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011320 if (akl)
11321 ha_free((char **)&(akl->kw[0].kw));
11322 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011323 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010011324 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020011325 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011326
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011327 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011328 akl->kw[0].private = fcn;
11329
11330 /* End of array. */
11331 memset(&akl->kw[1], 0, sizeof(*akl->kw));
11332
11333 /* Register this new converter */
11334 service_keywords_register(akl);
11335
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011336 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011337
11338 alloc_error:
11339 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011340 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011341 ha_free(&akl);
11342 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11343 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011344}
11345
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011346/* This function initialises Lua cli handler. It copies the
11347 * arguments in the Lua stack and create channel IO objects.
11348 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020011349static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011350{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011351 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011352 struct hlua *hlua;
11353 struct hlua_function *fcn;
11354 int i;
11355 const char *error;
11356
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011357 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011358 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011359
Willy Tarreaubafbe012017-11-24 17:34:44 +010011360 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011361 if (!hlua) {
11362 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011363 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011364 }
11365 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011366 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011367
11368 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050011369 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011370 * applet_http. It is absolutely compatible.
11371 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011372 ctx->task = task_new_here();
11373 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010011374 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011375 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011376 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011377 ctx->task->nice = 0;
11378 ctx->task->context = appctx;
11379 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011380
11381 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011382 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011383 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011384 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011385 }
11386
11387 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011388 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011389 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011390 error = hlua_tostring_safe(hlua->T, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011391 else
11392 error = "critical error";
11393 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
11394 goto error;
11395 }
11396
11397 /* Check stack available size. */
11398 if (!lua_checkstack(hlua->T, 2)) {
11399 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11400 goto error;
11401 }
11402
11403 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011404 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011405
11406 /* Once the arguments parsed, the CLI is like an AppletTCP,
11407 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011408 */
11409 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
11410 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11411 goto error;
11412 }
11413 hlua->nargs = 1;
11414
11415 /* push keywords in the stack. */
11416 for (i = 0; *args[i]; i++) {
11417 /* Check stack available size. */
11418 if (!lua_checkstack(hlua->T, 1)) {
11419 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11420 goto error;
11421 }
11422 lua_pushstring(hlua->T, args[i]);
11423 hlua->nargs++;
11424 }
11425
11426 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011427 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011428
11429 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011430 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011431
11432 /* It's ok */
11433 return 0;
11434
11435 /* It's not ok. */
11436error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011437 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011438 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011439 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011440 return 1;
11441}
11442
11443static int hlua_cli_io_handler_fct(struct appctx *appctx)
11444{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011445 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011446 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020011447 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011448 struct hlua_function *fcn;
11449
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011450 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020011451 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011452 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011453
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011454 /* Execute the function. */
11455 switch (hlua_ctx_resume(hlua, 1)) {
11456
11457 /* finished. */
11458 case HLUA_E_OK:
11459 return 1;
11460
11461 /* yield. */
11462 case HLUA_E_AGAIN:
11463 /* We want write. */
11464 if (HLUA_IS_WAKERESWR(hlua))
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020011465 sc_need_room(sc, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011466 /* Set the timeout. */
11467 if (hlua->wake_time != TICK_ETERNITY)
11468 task_schedule(hlua->task, hlua->wake_time);
11469 return 0;
11470
11471 /* finished with error. */
11472 case HLUA_E_ERRMSG:
11473 /* Display log. */
11474 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011475 fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011476 lua_pop(hlua->T, 1);
11477 return 1;
11478
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011479 case HLUA_E_ETMOUT:
11480 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
11481 fcn->name);
11482 return 1;
11483
11484 case HLUA_E_NOMEM:
11485 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
11486 fcn->name);
11487 return 1;
11488
11489 case HLUA_E_YIELD: /* unexpected */
11490 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
11491 fcn->name);
11492 return 1;
11493
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011494 case HLUA_E_ERR:
11495 /* Display log. */
11496 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11497 fcn->name);
11498 return 1;
11499
11500 default:
11501 return 1;
11502 }
11503
11504 return 1;
11505}
11506
11507static void hlua_cli_io_release_fct(struct appctx *appctx)
11508{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011509 struct hlua_cli_ctx *ctx = appctx->svcctx;
11510
11511 hlua_ctx_destroy(ctx->hlua);
11512 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011513}
11514
11515/* This function is an LUA binding used for registering
11516 * new keywords in the cli. It expects a list of keywords
11517 * which are the "path". It is limited to 5 keywords. A
11518 * description of the command, a function to be executed
11519 * for the parsing and a function for io handlers.
11520 */
11521__LJMP static int hlua_register_cli(lua_State *L)
11522{
11523 struct cli_kw_list *cli_kws;
11524 const char *message;
11525 int ref_io;
11526 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011527 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011528 int index;
11529 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011530 struct buffer *trash;
11531 const char *kw[5];
11532 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011533 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011534 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011535
11536 MAY_LJMP(check_args(L, 3, "register_cli"));
11537
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011538 if (hlua_gethlua(L)) {
11539 /* runtime processing */
11540 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11541 }
11542
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011543 /* First argument : an array of maximum 5 keywords. */
11544 if (!lua_istable(L, 1))
11545 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11546
11547 /* Second argument : string with contextual message. */
11548 message = MAY_LJMP(luaL_checkstring(L, 2));
11549
11550 /* Third and fourth argument : lua function. */
11551 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11552
Thierry Fournierf67442e2020-11-28 20:41:07 +010011553 /* Check for CLI service already registered */
11554 trash = get_trash_chunk();
11555 index = 0;
11556 lua_pushnil(L);
11557 memset(kw, 0, sizeof(kw));
11558 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011559 if (index >= CLI_PREFIX_KW_NB) {
11560 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011561 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 +010011562 }
11563 if (lua_type(L, -1) != LUA_TSTRING) {
11564 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011565 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011566 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011567 kw[index] = lua_tostring(L, -1);
11568 if (index == 0)
11569 chunk_printf(trash, "%s", kw[index]);
11570 else
11571 chunk_appendf(trash, " %s", kw[index]);
11572 index++;
11573 lua_pop(L, 1);
11574 }
11575 cli_kw = cli_find_kw_exact((char **)kw);
11576 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011577 fcn = cli_kw->private;
11578 if (fcn->function_ref[hlua_state_id] != -1) {
11579 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11580 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011581 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011582 }
11583 fcn->function_ref[hlua_state_id] = ref_io;
11584 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011585 }
11586
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011587 /* Allocate and fill the sample fetch keyword struct. */
11588 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011589 if (!cli_kws) {
11590 errmsg = "Lua out of memory error.";
11591 goto error;
11592 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011593 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011594 if (!fcn) {
11595 errmsg = "Lua out of memory error.";
11596 goto error;
11597 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011598
11599 /* Fill path. */
11600 index = 0;
11601 lua_pushnil(L);
11602 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011603 if (index >= 5) {
11604 errmsg = "1st argument must be a table with a maximum of 5 entries";
11605 goto error;
11606 }
11607 if (lua_type(L, -1) != LUA_TSTRING) {
11608 errmsg = "1st argument must be a table filled with strings";
11609 goto error;
11610 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011611 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011612 if (!cli_kws->kw[0].str_kw[index]) {
11613 errmsg = "Lua out of memory error.";
11614 goto error;
11615 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011616 index++;
11617 lua_pop(L, 1);
11618 }
11619
11620 /* Copy help message. */
11621 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011622 if (!cli_kws->kw[0].usage) {
11623 errmsg = "Lua out of memory error.";
11624 goto error;
11625 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011626
11627 /* Fill fcn io handler. */
11628 len = strlen("<lua.cli>") + 1;
11629 for (i = 0; i < index; i++)
11630 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11631 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011632 if (!fcn->name) {
11633 errmsg = "Lua out of memory error.";
11634 goto error;
11635 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011636
11637 end = fcn->name;
11638 len = 8;
11639 memcpy(end, "<lua.cli", len);
11640 end += len;
11641
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011642 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011643 *(end++) = '.';
11644 len = strlen(cli_kws->kw[0].str_kw[i]);
11645 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11646 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011647 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011648 *(end++) = '>';
11649 *(end++) = 0;
11650
Thierry Fournierc7492592020-11-28 23:57:24 +010011651 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011652
11653 /* Fill last entries. */
11654 cli_kws->kw[0].private = fcn;
11655 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11656 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11657 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11658
11659 /* Register this new converter */
11660 cli_register_kw(cli_kws);
11661
11662 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011663
11664 error:
11665 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011666 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011667 if (cli_kws) {
11668 for (i = 0; i < index; i++)
11669 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11670 ha_free((char **)&(cli_kws->kw[0].usage));
11671 }
11672 ha_free(&cli_kws);
11673 WILL_LJMP(luaL_error(L, errmsg));
11674 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011675}
11676
Christopher Faulet69c581a2021-05-31 08:54:04 +020011677static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11678{
11679 struct hlua_flt_config *conf = fconf->conf;
11680 lua_State *L;
11681 int error, pos, state_id, flt_ref;
11682
11683 state_id = reg_flt_to_stack_id(conf->reg);
11684 L = hlua_states[state_id];
11685 pos = lua_gettop(L);
11686
11687 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011688 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011689
11690 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011691 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011692
11693 /* Duplicate the filter class so each filter will have its own copy */
11694 lua_newtable(L);
11695 lua_pushnil(L);
11696
11697 while (lua_next(L, pos+2)) {
11698 lua_pushvalue(L, -2);
11699 lua_insert(L, -2);
11700 lua_settable(L, -4);
11701 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011702 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011703
11704 /* Remove the original lua filter class from the stack */
11705 lua_pop(L, 1);
11706
11707 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011708 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011709
11710 /* extra args are pushed in a table */
11711 lua_newtable(L);
11712 for (pos = 0; conf->args[pos]; pos++) {
11713 /* Check stack available size. */
11714 if (!lua_checkstack(L, 1)) {
11715 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11716 goto error;
11717 }
11718 lua_pushstring(L, conf->args[pos]);
11719 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11720 }
11721
11722 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11723 switch (error) {
11724 case LUA_OK:
11725 /* replace the filter ref */
11726 conf->ref[state_id] = flt_ref;
11727 break;
11728 case LUA_ERRRUN:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011729 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011730 goto error;
11731 case LUA_ERRMEM:
11732 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11733 goto error;
11734 case LUA_ERRERR:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011735 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011736 goto error;
11737#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11738 case LUA_ERRGCMM:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011739 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011740 goto error;
11741#endif
11742 default:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011743 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, hlua_tostring_safe(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011744 goto error;
11745 }
11746
11747 lua_settop(L, 0);
11748 return 0;
11749
11750 error:
11751 lua_settop(L, 0);
11752 return -1;
11753}
11754
11755static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11756{
11757 struct hlua_flt_config *conf = fconf->conf;
11758 lua_State *L;
11759 int state_id;
11760
11761 if (!conf)
11762 return;
11763
11764 state_id = reg_flt_to_stack_id(conf->reg);
11765 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011766 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011767}
11768
11769static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11770{
11771 struct hlua_flt_config *conf = fconf->conf;
11772 int state_id = reg_flt_to_stack_id(conf->reg);
11773
11774 /* Rely on per-thread init for global scripts */
11775 if (!state_id)
11776 return hlua_filter_init_per_thread(px, fconf);
11777 return 0;
11778}
11779
11780static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11781{
11782
11783 if (fconf->conf) {
11784 struct hlua_flt_config *conf = fconf->conf;
11785 int state_id = reg_flt_to_stack_id(conf->reg);
11786 int pos;
11787
11788 /* Rely on per-thread deinit for global scripts */
11789 if (!state_id)
11790 hlua_filter_deinit_per_thread(px, fconf);
11791
11792 for (pos = 0; conf->args[pos]; pos++)
11793 free(conf->args[pos]);
11794 free(conf->args);
11795 }
11796 ha_free(&fconf->conf);
11797 ha_free((char **)&fconf->id);
11798 ha_free(&fconf->ops);
11799}
11800
11801static int hlua_filter_new(struct stream *s, struct filter *filter)
11802{
11803 struct hlua_flt_config *conf = FLT_CONF(filter);
11804 struct hlua_flt_ctx *flt_ctx = NULL;
11805 int ret = 1;
11806
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020011807 if (!hlua_stream_ctx_prepare(s, reg_flt_to_stack_id(conf->reg))) {
11808 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11809 conf->reg->name);
11810 ret = 0;
11811 goto end;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011812 }
11813
11814 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11815 if (!flt_ctx) {
11816 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11817 conf->reg->name);
11818 ret = 0;
11819 goto end;
11820 }
Aurelien DARRAGON205f1ac2024-03-04 09:39:58 +010011821
11822 if ((flt_ctx->hlua[0] = pool_alloc(pool_head_hlua)))
11823 HLUA_INIT(flt_ctx->hlua[0]);
11824 if ((flt_ctx->hlua[1] = pool_alloc(pool_head_hlua)))
11825 HLUA_INIT(flt_ctx->hlua[1]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011826 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11827 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11828 conf->reg->name);
11829 ret = 0;
11830 goto end;
11831 }
Aurelien DARRAGON205f1ac2024-03-04 09:39:58 +010011832
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011833 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11834 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011835 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11836 conf->reg->name);
11837 ret = 0;
11838 goto end;
11839 }
11840
11841 if (!HLUA_IS_RUNNING(s->hlua)) {
11842 /* The following Lua calls can fail. */
11843 if (!SET_SAFE_LJMP(s->hlua)) {
11844 const char *error;
11845
11846 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011847 error = hlua_tostring_safe(s->hlua->T, -1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011848 else
11849 error = "critical error";
11850 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11851 ret = 0;
11852 goto end;
11853 }
11854
11855 /* Check stack size. */
11856 if (!lua_checkstack(s->hlua->T, 1)) {
11857 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011858 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011859 ret = 0;
11860 goto end;
11861 }
11862
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011863 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011864 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11865 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11866 conf->reg->name);
11867 RESET_SAFE_LJMP(s->hlua);
11868 ret = 0;
11869 goto end;
11870 }
11871 lua_insert(s->hlua->T, -2);
11872
11873 /* Push the copy on the stack */
11874 s->hlua->nargs = 1;
11875
11876 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011877 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011878
11879 /* At this point the execution is safe. */
11880 RESET_SAFE_LJMP(s->hlua);
11881 }
11882
11883 switch (hlua_ctx_resume(s->hlua, 0)) {
11884 case HLUA_E_OK:
11885 /* Nothing returned or not a table, ignore the filter for current stream */
11886 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11887 ret = 0;
11888 goto end;
11889 }
11890
11891 /* Attached the filter pointer to the ctx */
11892 lua_pushstring(s->hlua->T, "__filter");
11893 lua_pushlightuserdata(s->hlua->T, filter);
11894 lua_settable(s->hlua->T, -3);
11895
11896 /* Save a ref on the filter ctx */
11897 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011898 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011899 filter->ctx = flt_ctx;
11900 break;
11901 case HLUA_E_ERRMSG:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011902 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, hlua_tostring_safe(s->hlua->T, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011903 ret = -1;
11904 goto end;
11905 case HLUA_E_ETMOUT:
11906 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11907 ret = 0;
11908 goto end;
11909 case HLUA_E_NOMEM:
11910 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11911 ret = 0;
11912 goto end;
11913 case HLUA_E_AGAIN:
11914 case HLUA_E_YIELD:
11915 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11916 " are not allowed from 'new' function.\n", conf->reg->name);
11917 ret = 0;
11918 goto end;
11919 case HLUA_E_ERR:
11920 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11921 ret = 0;
11922 goto end;
11923 default:
11924 ret = 0;
11925 goto end;
11926 }
11927
11928 end:
Aurelien DARRAGON01d1b732024-03-04 11:25:47 +010011929 if (s->hlua) {
11930 hlua_lock(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011931 lua_settop(s->hlua->T, 0);
Aurelien DARRAGON01d1b732024-03-04 11:25:47 +010011932 hlua_unlock(s->hlua);
11933 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011934 if (ret <= 0) {
11935 if (flt_ctx) {
11936 hlua_ctx_destroy(flt_ctx->hlua[0]);
11937 hlua_ctx_destroy(flt_ctx->hlua[1]);
11938 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11939 }
11940 }
11941 return ret;
11942}
11943
11944static void hlua_filter_delete(struct stream *s, struct filter *filter)
11945{
11946 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11947
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011948 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011949 hlua_ctx_destroy(flt_ctx->hlua[0]);
11950 hlua_ctx_destroy(flt_ctx->hlua[1]);
11951 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11952 filter->ctx = NULL;
11953}
11954
Christopher Faulet9f55a502020-02-25 15:21:02 +010011955static int hlua_filter_from_payload(struct filter *filter)
11956{
11957 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11958
11959 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11960}
11961
Christopher Fauletc404f112020-02-26 15:03:09 +010011962static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11963 int dir, unsigned int flags)
11964{
11965 struct hlua *flt_hlua;
11966 struct hlua_flt_config *conf = FLT_CONF(filter);
11967 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11968 unsigned int hflags = HLUA_TXN_FLT_CTX;
11969 int ret = 1;
11970
11971 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11972 if (!flt_hlua)
11973 goto end;
11974
11975 if (!HLUA_IS_RUNNING(flt_hlua)) {
Aurelien DARRAGONf8b137b2024-03-04 11:06:24 +010011976 int extra_idx;
Christopher Fauletc404f112020-02-26 15:03:09 +010011977
11978 /* The following Lua calls can fail. */
11979 if (!SET_SAFE_LJMP(flt_hlua)) {
11980 const char *error;
11981
11982 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010011983 error = hlua_tostring_safe(flt_hlua->T, -1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011984 else
11985 error = "critical error";
11986 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11987 goto end;
11988 }
11989
Aurelien DARRAGONf8b137b2024-03-04 11:06:24 +010011990 extra_idx = lua_gettop(flt_hlua->T);
11991
Christopher Fauletc404f112020-02-26 15:03:09 +010011992 /* Check stack size. */
11993 if (!lua_checkstack(flt_hlua->T, 3)) {
11994 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11995 RESET_SAFE_LJMP(flt_hlua);
11996 goto end;
11997 }
11998
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011999 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010012000 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
12001 RESET_SAFE_LJMP(flt_hlua);
12002 goto end;
12003 }
12004 lua_insert(flt_hlua->T, -2);
12005
12006 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
12007 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
12008 RESET_SAFE_LJMP(flt_hlua);
12009 goto end;
12010 }
12011 flt_hlua->nargs = 2;
12012
12013 if (flags & HLUA_FLT_CB_ARG_CHN) {
12014 if (dir == SMP_OPT_DIR_REQ)
12015 lua_getfield(flt_hlua->T, -1, "req");
12016 else
12017 lua_getfield(flt_hlua->T, -1, "res");
12018 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
12019 lua_pushstring(flt_hlua->T, "__filter");
12020 lua_pushlightuserdata(flt_hlua->T, filter);
12021 lua_settable(flt_hlua->T, -3);
12022 }
12023 flt_hlua->nargs++;
12024 }
12025 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012026 if (dir == SMP_OPT_DIR_REQ)
12027 lua_getfield(flt_hlua->T, -1, "http_req");
12028 else
12029 lua_getfield(flt_hlua->T, -1, "http_res");
12030 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
12031 lua_pushstring(flt_hlua->T, "__filter");
12032 lua_pushlightuserdata(flt_hlua->T, filter);
12033 lua_settable(flt_hlua->T, -3);
12034 }
12035 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010012036 }
12037
12038 /* Check stack size. */
12039 if (!lua_checkstack(flt_hlua->T, 1)) {
12040 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
12041 RESET_SAFE_LJMP(flt_hlua);
12042 goto end;
12043 }
12044
12045 while (extra_idx--) {
12046 lua_pushvalue(flt_hlua->T, 1);
12047 lua_remove(flt_hlua->T, 1);
12048 flt_hlua->nargs++;
12049 }
12050
12051 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010012052 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010012053
12054 /* At this point the execution is safe. */
12055 RESET_SAFE_LJMP(flt_hlua);
12056 }
12057
12058 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
12059 case HLUA_E_OK:
12060 /* Catch the return value if it required */
12061 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
12062 ret = lua_tointeger(flt_hlua->T, -1);
12063 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12064 }
12065
12066 /* Set timeout in the required channel. */
12067 if (flt_hlua->wake_time != TICK_ETERNITY) {
12068 if (dir == SMP_OPT_DIR_REQ)
12069 s->req.analyse_exp = flt_hlua->wake_time;
12070 else
12071 s->res.analyse_exp = flt_hlua->wake_time;
12072 }
12073 break;
12074 case HLUA_E_AGAIN:
12075 /* Set timeout in the required channel. */
12076 if (flt_hlua->wake_time != TICK_ETERNITY) {
12077 if (dir == SMP_OPT_DIR_REQ)
12078 s->req.analyse_exp = flt_hlua->wake_time;
12079 else
12080 s->res.analyse_exp = flt_hlua->wake_time;
12081 }
12082 /* Some actions can be wake up when a "write" event
12083 * is detected on a response channel. This is useful
12084 * only for actions targeted on the requests.
12085 */
12086 if (HLUA_IS_WAKERESWR(flt_hlua))
12087 s->res.flags |= CF_WAKE_WRITE;
12088 if (HLUA_IS_WAKEREQWR(flt_hlua))
12089 s->req.flags |= CF_WAKE_WRITE;
12090 ret = 0;
12091 goto end;
12092 case HLUA_E_ERRMSG:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012093 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, hlua_tostring_safe(flt_hlua->T, -1));
Christopher Fauletc404f112020-02-26 15:03:09 +010012094 ret = -1;
12095 goto end;
12096 case HLUA_E_ETMOUT:
12097 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
12098 goto end;
12099 case HLUA_E_NOMEM:
12100 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
12101 goto end;
12102 case HLUA_E_YIELD:
12103 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
12104 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
12105 goto end;
12106 case HLUA_E_ERR:
12107 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
12108 goto end;
12109 default:
12110 goto end;
12111 }
12112
12113
12114 end:
12115 return ret;
12116}
12117
12118static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
12119{
12120 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12121
12122 flt_ctx->flags = 0;
12123 return hlua_filter_callback(s, filter, "start_analyze",
12124 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12125 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
12126}
12127
12128static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
12129{
12130 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12131
12132 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12133 return hlua_filter_callback(s, filter, "end_analyze",
12134 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12135 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
12136}
12137
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012138static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
12139{
12140 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12141
12142 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12143 return hlua_filter_callback(s, filter, "http_headers",
12144 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12145 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12146}
12147
12148static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
12149 unsigned int offset, unsigned int len)
12150{
12151 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12152 struct hlua *flt_hlua;
12153 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12154 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12155 int ret;
12156
12157 flt_hlua = flt_ctx->hlua[idx];
12158 flt_ctx->cur_off[idx] = offset;
12159 flt_ctx->cur_len[idx] = len;
12160 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12161 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12162 if (ret != -1) {
12163 ret = flt_ctx->cur_len[idx];
12164 if (lua_gettop(flt_hlua->T) > 0) {
12165 ret = lua_tointeger(flt_hlua->T, -1);
12166 if (ret > flt_ctx->cur_len[idx])
12167 ret = flt_ctx->cur_len[idx];
12168 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12169 }
12170 }
12171 return ret;
12172}
12173
12174static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
12175{
12176 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12177
12178 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12179 return hlua_filter_callback(s, filter, "http_end",
12180 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12181 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12182}
12183
Christopher Fauletc404f112020-02-26 15:03:09 +010012184static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
12185 unsigned int offset, unsigned int len)
12186{
12187 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12188 struct hlua *flt_hlua;
12189 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12190 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12191 int ret;
12192
12193 flt_hlua = flt_ctx->hlua[idx];
12194 flt_ctx->cur_off[idx] = offset;
12195 flt_ctx->cur_len[idx] = len;
12196 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12197 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
12198 if (ret != -1) {
12199 ret = flt_ctx->cur_len[idx];
12200 if (lua_gettop(flt_hlua->T) > 0) {
12201 ret = lua_tointeger(flt_hlua->T, -1);
12202 if (ret > flt_ctx->cur_len[idx])
12203 ret = flt_ctx->cur_len[idx];
12204 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12205 }
12206 }
12207 return ret;
12208}
12209
Christopher Faulet69c581a2021-05-31 08:54:04 +020012210static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
12211 struct flt_conf *fconf, char **err, void *private)
12212{
12213 struct hlua_reg_filter *reg_flt = private;
12214 lua_State *L;
12215 struct hlua_flt_config *conf = NULL;
12216 const char *flt_id = NULL;
12217 int state_id, pos, flt_flags = 0;
12218 struct flt_ops *hlua_flt_ops = NULL;
12219
12220 state_id = reg_flt_to_stack_id(reg_flt);
12221 L = hlua_states[state_id];
12222
12223 /* Initialize the filter ops with default callbacks */
12224 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012225 if (!hlua_flt_ops)
12226 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012227 hlua_flt_ops->init = hlua_filter_init;
12228 hlua_flt_ops->deinit = hlua_filter_deinit;
12229 if (state_id) {
12230 /* Set per-thread callback if script is loaded per-thread */
12231 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
12232 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
12233 }
12234 hlua_flt_ops->attach = hlua_filter_new;
12235 hlua_flt_ops->detach = hlua_filter_delete;
12236
12237 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012238 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012239
Christopher Fauletc404f112020-02-26 15:03:09 +010012240 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
12241 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
12242 lua_pop(L, 1);
12243 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
12244 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
12245 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012246 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
12247 hlua_flt_ops->http_headers = hlua_filter_http_headers;
12248 lua_pop(L, 1);
12249 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
12250 hlua_flt_ops->http_payload = hlua_filter_http_payload;
12251 lua_pop(L, 1);
12252 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
12253 hlua_flt_ops->http_end = hlua_filter_http_end;
12254 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010012255 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
12256 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
12257 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012258
12259 /* Get id and flags of the filter class */
12260 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
12261 flt_id = lua_tostring(L, -1);
12262 lua_pop(L, 1);
12263 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
12264 flt_flags = lua_tointeger(L, -1);
12265 lua_pop(L, 1);
12266
12267 /* Create the filter config */
12268 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012269 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020012270 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012271 conf->reg = reg_flt;
12272
12273 /* duplicate args */
12274 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
12275 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012276 if (!conf->args)
12277 goto error;
12278 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012279 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012280 if (!conf->args[pos])
12281 goto error;
12282 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012283 conf->args[pos] = NULL;
12284 *cur_arg += pos + 1;
12285
Christopher Fauletc86bb872021-08-13 08:33:57 +020012286 if (flt_id) {
12287 fconf->id = strdup(flt_id);
12288 if (!fconf->id)
12289 goto error;
12290 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012291 fconf->flags = flt_flags;
12292 fconf->conf = conf;
12293 fconf->ops = hlua_flt_ops;
12294
12295 lua_settop(L, 0);
12296 return 0;
12297
12298 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020012299 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012300 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012301 if (conf && conf->args) {
12302 for (pos = 0; conf->args[pos]; pos++)
12303 free(conf->args[pos]);
12304 free(conf->args);
12305 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012306 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012307 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012308 lua_settop(L, 0);
12309 return -1;
12310}
12311
Christopher Fauletc404f112020-02-26 15:03:09 +010012312__LJMP static int hlua_register_data_filter(lua_State *L)
12313{
12314 struct filter *filter;
12315 struct channel *chn;
12316
12317 MAY_LJMP(check_args(L, 2, "register_data_filter"));
12318 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12319 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12320
12321 lua_getfield(L, 1, "__filter");
12322 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12323 filter = lua_touserdata (L, -1);
12324 lua_pop(L, 1);
12325
12326 register_data_filter(chn_strm(chn), chn, filter);
12327 return 1;
12328}
12329
12330__LJMP static int hlua_unregister_data_filter(lua_State *L)
12331{
12332 struct filter *filter;
12333 struct channel *chn;
12334
12335 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
12336 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12337 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12338
12339 lua_getfield(L, 1, "__filter");
12340 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12341 filter = lua_touserdata (L, -1);
12342 lua_pop(L, 1);
12343
12344 unregister_data_filter(chn_strm(chn), chn, filter);
12345 return 1;
12346}
12347
Christopher Faulet69c581a2021-05-31 08:54:04 +020012348/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012349 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020012350 * parse configuration arguments.
12351 */
12352__LJMP static int hlua_register_filter(lua_State *L)
12353{
12354 struct buffer *trash;
12355 struct flt_kw_list *fkl;
12356 struct flt_kw *fkw;
12357 const char *name;
12358 struct hlua_reg_filter *reg_flt= NULL;
12359 int flt_ref, fun_ref;
12360 int len;
12361
12362 MAY_LJMP(check_args(L, 3, "register_filter"));
12363
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010012364 if (hlua_gethlua(L)) {
12365 /* runtime processing */
12366 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
12367 }
12368
Christopher Faulet69c581a2021-05-31 08:54:04 +020012369 /* First argument : filter name. */
12370 name = MAY_LJMP(luaL_checkstring(L, 1));
12371
12372 /* Second argument : The filter class */
12373 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
12374
12375 /* Third argument : lua function. */
12376 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
12377
12378 trash = get_trash_chunk();
12379 chunk_printf(trash, "lua.%s", name);
12380 fkw = flt_find_kw(trash->area);
12381 if (fkw != NULL) {
12382 reg_flt = fkw->private;
12383 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
12384 ha_warning("Trying to register filter 'lua.%s' more than once. "
12385 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012386 if (reg_flt->flt_ref[hlua_state_id] != -1)
12387 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
12388 if (reg_flt->fun_ref[hlua_state_id] != -1)
12389 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012390 }
12391 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12392 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12393 return 0;
12394 }
12395
12396 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
12397 if (!fkl)
12398 goto alloc_error;
12399 fkl->scope = "HLUA";
12400
12401 reg_flt = new_hlua_reg_filter(name);
12402 if (!reg_flt)
12403 goto alloc_error;
12404
12405 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12406 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12407
12408 /* The filter keyword */
12409 len = strlen("lua.") + strlen(name) + 1;
12410 fkl->kw[0].kw = calloc(1, len);
12411 if (!fkl->kw[0].kw)
12412 goto alloc_error;
12413
12414 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
12415
12416 fkl->kw[0].parse = hlua_filter_parse_fct;
12417 fkl->kw[0].private = reg_flt;
12418 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
12419
12420 /* Register this new filter */
12421 flt_register_keywords(fkl);
12422
12423 return 0;
12424
12425 alloc_error:
12426 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012427 hlua_unref(L, flt_ref);
12428 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012429 ha_free(&fkl);
12430 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
12431 return 0; /* Never reached */
12432}
12433
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012434static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012435 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012436 char **err, unsigned int *timeout)
12437{
12438 const char *error;
12439
12440 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020012441 if (error == PARSE_TIME_OVER) {
12442 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
12443 args[1], args[0]);
12444 return -1;
12445 }
12446 else if (error == PARSE_TIME_UNDER) {
12447 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
12448 args[1], args[0]);
12449 return -1;
12450 }
12451 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012452 memprintf(err, "%s: invalid timeout", args[0]);
12453 return -1;
12454 }
12455 return 0;
12456}
12457
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012458static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
12459 const struct proxy *defpx, const char *file, int line,
12460 char **err)
12461{
12462 return hlua_read_timeout(args, section_type, curpx, defpx,
12463 file, line, err, &hlua_timeout_burst);
12464}
12465
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012466static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012467 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012468 char **err)
12469{
12470 return hlua_read_timeout(args, section_type, curpx, defpx,
12471 file, line, err, &hlua_timeout_session);
12472}
12473
12474static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012475 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012476 char **err)
12477{
12478 return hlua_read_timeout(args, section_type, curpx, defpx,
12479 file, line, err, &hlua_timeout_task);
12480}
12481
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012482static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012483 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012484 char **err)
12485{
12486 return hlua_read_timeout(args, section_type, curpx, defpx,
12487 file, line, err, &hlua_timeout_applet);
12488}
12489
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012490static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012491 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012492 char **err)
12493{
12494 char *error;
12495
12496 hlua_nb_instruction = strtoll(args[1], &error, 10);
12497 if (*error != '\0') {
12498 memprintf(err, "%s: invalid number", args[0]);
12499 return -1;
12500 }
12501 return 0;
12502}
12503
Willy Tarreau32f61e22015-03-18 17:54:59 +010012504static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012505 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012506 char **err)
12507{
12508 char *error;
12509
12510 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012511 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012512 return -1;
12513 }
12514 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12515 if (*error != '\0') {
12516 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12517 return -1;
12518 }
12519 return 0;
12520}
12521
Tristan2632d042023-10-23 13:07:39 +010012522static int hlua_cfg_parse_log_loggers(char **args, int section_type, struct proxy *curpx,
12523 const struct proxy *defpx, const char *file, int line,
12524 char **err)
12525{
12526 if (too_many_args(1, args, err, NULL))
12527 return -1;
12528
12529 if (strcmp(args[1], "on") == 0)
12530 hlua_log_opts |= HLUA_LOG_LOGGERS_ON;
12531 else if (strcmp(args[1], "off") == 0)
12532 hlua_log_opts &= ~HLUA_LOG_LOGGERS_ON;
12533 else {
12534 memprintf(err, "'%s' expects either 'on' or 'off' but got '%s'.", args[0], args[1]);
12535 return -1;
12536 }
12537 return 0;
12538}
12539
12540static int hlua_cfg_parse_log_stderr(char **args, int section_type, struct proxy *curpx,
12541 const struct proxy *defpx, const char *file, int line,
12542 char **err)
12543{
12544 if (too_many_args(1, args, err, NULL))
12545 return -1;
12546
12547 if (strcmp(args[1], "on") == 0)
12548 hlua_log_opts = (hlua_log_opts & ~HLUA_LOG_STDERR_MASK) | HLUA_LOG_STDERR_ON;
12549 else if (strcmp(args[1], "auto") == 0)
12550 hlua_log_opts = (hlua_log_opts & ~HLUA_LOG_STDERR_MASK) | HLUA_LOG_STDERR_AUTO;
12551 else if (strcmp(args[1], "off") == 0)
12552 hlua_log_opts &= ~HLUA_LOG_STDERR_MASK;
12553 else {
12554 memprintf(err, "'%s' expects either 'on', 'auto', or 'off' but got '%s'.", args[0], args[1]);
12555 return -1;
12556 }
12557 return 0;
12558}
Willy Tarreau32f61e22015-03-18 17:54:59 +010012559
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012560/* This function is called by the main configuration key "lua-load". It loads and
12561 * execute an lua file during the parsing of the HAProxy configuration file. It is
12562 * the main lua entry point.
12563 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012564 * This function runs with the HAProxy keywords API. It returns -1 if an error
12565 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012566 *
12567 * In some error case, LUA set an error message in top of the stack. This function
12568 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012569 *
12570 * This function can fail with an abort() due to an Lua critical error.
12571 * We are in the configuration parsing process of HAProxy, this abort() is
12572 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012573 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012574static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012575{
12576 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012577 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012578
12579 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012580 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012581 if (error) {
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012582 memprintf(err, "error in Lua file '%s': %s", args[0], hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012583 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012584 return -1;
12585 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012586
12587 /* Push args in the Lua stack, except the first one which is the filename */
12588 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012589 /* Check stack size. */
12590 if (!lua_checkstack(L, 1)) {
12591 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12592 return -1;
12593 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012594 lua_pushstring(L, args[nargs]);
12595 }
12596 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012597
12598 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012599 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012600 switch (error) {
12601 case LUA_OK:
12602 break;
12603 case LUA_ERRRUN:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012604 memprintf(err, "Lua runtime error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012605 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012606 return -1;
12607 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012608 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012609 return -1;
12610 case LUA_ERRERR:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012611 memprintf(err, "Lua message handler error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012612 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012613 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012614#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012615 case LUA_ERRGCMM:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012616 memprintf(err, "Lua garbage collector error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012617 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012618 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012619#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012620 default:
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012621 memprintf(err, "Lua unknown error: %s", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012622 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012623 return -1;
12624 }
12625
12626 return 0;
12627}
12628
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012629static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012630 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012631 char **err)
12632{
12633 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012634 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012635 return -1;
12636 }
12637
Thierry Fournier59f11be2020-11-29 00:37:41 +010012638 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012639 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012640 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012641 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012642}
12643
Thierry Fournier59f11be2020-11-29 00:37:41 +010012644static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012645 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012646 char **err)
12647{
12648 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012649 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012650
12651 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012652 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012653 return -1;
12654 }
12655
12656 if (per_thread_load == NULL) {
12657 /* allocate the first entry large enough to store the final NULL */
12658 per_thread_load = calloc(1, sizeof(*per_thread_load));
12659 if (per_thread_load == NULL) {
12660 memprintf(err, "out of memory error");
12661 return -1;
12662 }
12663 }
12664
12665 /* count used entries */
12666 for (len = 0; per_thread_load[len] != NULL; len++)
12667 ;
12668
12669 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12670 if (per_thread_load == NULL) {
12671 memprintf(err, "out of memory error");
12672 return -1;
12673 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012674 per_thread_load[len + 1] = NULL;
12675
Thierry Fournierae6b5682022-09-19 09:04:16 +020012676 /* count args excepting the first, allocate array and copy args */
12677 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012678 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012679 if (per_thread_load[len] == NULL) {
12680 memprintf(err, "out of memory error");
12681 return -1;
12682 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012683 for (i = 1; *(args[i]) != 0; i++) {
12684 per_thread_load[len][i - 1] = strdup(args[i]);
12685 if (per_thread_load[len][i - 1] == NULL) {
12686 memprintf(err, "out of memory error");
12687 return -1;
12688 }
12689 }
12690 per_thread_load[len][i - 1] = strdup("");
12691 if (per_thread_load[len][i - 1] == NULL) {
12692 memprintf(err, "out of memory error");
12693 return -1;
12694 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012695
12696 /* loading for thread 1 only */
12697 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012698 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012699 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012700}
12701
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012702/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12703 * in the given <ctx>.
12704 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012705static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012706{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012707 lua_getglobal(L, "package"); /* push package variable */
12708 lua_pushstring(L, path); /* push given path */
12709 lua_pushstring(L, ";"); /* push semicolon */
12710 lua_getfield(L, -3, type); /* push old path */
12711 lua_concat(L, 3); /* concatenate to new path */
12712 lua_setfield(L, -2, type); /* store new path */
12713 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012714
12715 return 0;
12716}
12717
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012718static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012719 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012720 char **err)
12721{
12722 char *path;
12723 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012724 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012725 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012726
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012727 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012728 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012729 }
12730
12731 if (!(*args[1])) {
12732 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012733 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012734 }
12735 path = args[1];
12736
12737 if (*args[2]) {
12738 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12739 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012740 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012741 }
12742 type = args[2];
12743 }
12744
Thierry Fournier59f11be2020-11-29 00:37:41 +010012745 p = calloc(1, sizeof(*p));
12746 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012747 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012748 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012749 }
12750 p->path = strdup(path);
12751 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012752 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012753 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012754 }
12755 p->type = strdup(type);
12756 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012757 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012758 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012759 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012760 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012761
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012762 /* Handle the global state and the per-thread state for the first
12763 * thread. The remaining threads will be initialized based on
12764 * prepend_path_list.
12765 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012766 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012767 lua_State *L = hlua_states[i];
12768 const char *error;
12769
12770 if (setjmp(safe_ljmp_env) != 0) {
12771 lua_atpanic(L, hlua_panic_safe);
12772 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010012773 error = hlua_tostring_safe(L, -1);
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012774 else
12775 error = "critical error";
12776 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12777 exit(1);
12778 } else {
12779 lua_atpanic(L, hlua_panic_ljmp);
12780 }
12781
12782 hlua_prepend_path(L, type, path);
12783
12784 lua_atpanic(L, hlua_panic_safe);
12785 }
12786
Thierry Fournier59f11be2020-11-29 00:37:41 +010012787 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012788
12789err2:
12790 free(p->type);
12791 free(p->path);
12792err:
12793 free(p);
12794 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012795}
12796
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012797/* configuration keywords declaration */
12798static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012799 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012800 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012801 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012802 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12803 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012804 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012805 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012806 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012807 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Tristan2632d042023-10-23 13:07:39 +010012808 { CFG_GLOBAL, "tune.lua.log.loggers", hlua_cfg_parse_log_loggers },
12809 { CFG_GLOBAL, "tune.lua.log.stderr", hlua_cfg_parse_log_stderr },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012810 { 0, NULL, NULL },
12811}};
12812
Willy Tarreau0108d902018-11-25 19:14:37 +010012813INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12814
William Lallemand52139182022-03-30 15:05:42 +020012815#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012816
William Lallemand30fcca12022-03-30 12:03:12 +020012817/*
12818 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12819 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12820 * difference is that the yield in lua and for the CLI is not handled the same
12821 * way.
12822 */
12823__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12824{
12825 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12826 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12827 struct ckch_inst *ckchi = *lua_ckchi;
12828 struct ckch_store *old_ckchs = lua_ckchs[0];
12829 struct ckch_store *new_ckchs = lua_ckchs[1];
12830 struct hlua *hlua;
12831 char *err = NULL;
12832 int y = 1;
12833
12834 hlua = hlua_gethlua(L);
12835
12836 /* get the first ckchi to copy */
12837 if (ckchi == NULL)
12838 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12839
12840 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12841 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12842 struct ckch_inst *new_inst;
12843
12844 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12845 if (y % 10 == 0) {
12846
12847 *lua_ckchi = ckchi;
12848
12849 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12850 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12851 }
12852
12853 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12854 goto error;
12855
12856 /* link the new ckch_inst to the duplicate */
12857 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12858 y++;
12859 }
12860
12861 /* The generation is finished, we can insert everything */
12862 ckch_store_replace(old_ckchs, new_ckchs);
12863
12864 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12865
12866 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12867
12868 return 0;
12869
12870error:
12871 ckch_store_free(new_ckchs);
12872 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12873 WILL_LJMP(luaL_error(L, "%s", err));
12874 free(err);
12875
12876 return 0;
12877}
12878
12879/*
12880 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12881 * from the table in parameter.
12882 *
12883 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12884 * means it does not need to have a transaction since everything is done in the
12885 * same function.
12886 *
12887 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12888 *
12889 */
12890__LJMP static int hlua_ckch_set(lua_State *L)
12891{
12892 struct hlua *hlua;
12893 struct ckch_inst **lua_ckchi;
12894 struct ckch_store **lua_ckchs;
12895 struct ckch_store *old_ckchs = NULL;
12896 struct ckch_store *new_ckchs = NULL;
12897 int errcode = 0;
12898 char *err = NULL;
12899 struct cert_exts *cert_ext = NULL;
12900 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012901 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012902 int ret;
12903
12904 if (lua_type(L, -1) != LUA_TTABLE)
12905 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12906
12907 hlua = hlua_gethlua(L);
12908
12909 /* FIXME: this should not return an error but should come back later */
12910 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12911 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12912
12913 ret = lua_getfield(L, -1, "filename");
12914 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012915 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012916 errcode |= ERR_ALERT | ERR_FATAL;
12917 goto end;
12918 }
12919 filename = (char *)lua_tostring(L, -1);
12920
12921
12922 /* look for the filename in the tree */
12923 old_ckchs = ckchs_lookup(filename);
12924 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012925 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012926 errcode |= ERR_ALERT | ERR_FATAL;
12927 goto end;
12928 }
12929 /* TODO: handle extra_files_noext */
12930
12931 new_ckchs = ckchs_dup(old_ckchs);
12932 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012933 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012934 errcode |= ERR_ALERT | ERR_FATAL;
12935 goto end;
12936 }
12937
William Lallemand52ddd992022-11-22 11:51:53 +010012938 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012939
12940 /* loop on the field in the table, which have the same name as the
12941 * possible extensions of files */
12942 lua_pushnil(L);
12943 while (lua_next(L, 1)) {
12944 int i;
12945 const char *field = lua_tostring(L, -2);
12946 char *payload = (char *)lua_tostring(L, -1);
12947
12948 if (!field || strcmp(field, "filename") == 0) {
12949 lua_pop(L, 1);
12950 continue;
12951 }
12952
12953 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12954 if (strcmp(field, cert_exts[i].ext) == 0) {
12955 cert_ext = &cert_exts[i];
12956 break;
12957 }
12958 }
12959
12960 /* this is the default type, the field is not supported */
12961 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012962 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012963 errcode |= ERR_ALERT | ERR_FATAL;
12964 goto end;
12965 }
12966
Frédéric Lécaille1409dea2023-12-06 11:42:42 +010012967 /* Reset the OCSP CID */
12968 if (cert_ext->type == CERT_TYPE_PEM || cert_ext->type == CERT_TYPE_KEY ||
12969 cert_ext->type == CERT_TYPE_ISSUER) {
12970 OCSP_CERTID_free(new_ckchs->data->ocsp_cid);
12971 new_ckchs->data->ocsp_cid = NULL;
12972 }
12973
12974 /* apply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012975 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012976 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012977 errcode |= ERR_ALERT | ERR_FATAL;
12978 goto end;
12979 }
12980 lua_pop(L, 1);
12981 }
12982
12983 /* store the pointers on the lua stack */
12984 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12985 lua_ckchs[0] = old_ckchs;
12986 lua_ckchs[1] = new_ckchs;
12987 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12988 *lua_ckchi = NULL;
12989
12990 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12991 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12992
12993end:
12994 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12995
12996 if (errcode & ERR_CODE) {
12997 ckch_store_free(new_ckchs);
12998 WILL_LJMP(luaL_error(L, "%s", err));
12999 }
13000 free(err);
13001
13002 return 0;
13003}
13004
William Lallemand52139182022-03-30 15:05:42 +020013005#else
13006
13007__LJMP static int hlua_ckch_set(lua_State *L)
13008{
13009 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
13010
13011 return 0;
13012}
13013#endif /* ! USE_OPENSSL */
13014
13015
13016
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013017/* This function can fail with an abort() due to an Lua critical error.
13018 * We are in the initialisation process of HAProxy, this abort() is
13019 * tolerated.
13020 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010013021int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013022{
13023 struct hlua_init_function *init;
13024 const char *msg;
13025 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013026 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010013027 const char *kind;
13028 const char *trace;
13029 int return_status = 1;
13030#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
13031 int nres;
13032#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013033
Willy Tarreaucdb53462020-12-02 12:12:00 +010013034 /* disable memory limit checks if limit is not set */
13035 if (!hlua_global_allocator.limit)
13036 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
13037
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050013038 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010013039 if (setjmp(safe_ljmp_env) != 0) {
13040 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010013041 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010013042 error = hlua_tostring_safe(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010013043 else
13044 error = "critical error";
13045 fprintf(stderr, "Lua post-init: %s.\n", error);
13046 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013047 } else {
13048 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010013049 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020013050
Thierry Fournierc7492592020-11-28 23:57:24 +010013051 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010013052 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010013053 /* function ref should be released right away since it was pushed
13054 * on the stack and will not be used anymore
13055 */
13056 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010013057
13058#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Aurelien DARRAGON3ddcd1b2023-09-08 19:29:08 +020013059 ret = lua_resume(L, NULL, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010013060#else
Aurelien DARRAGON3ddcd1b2023-09-08 19:29:08 +020013061 ret = lua_resume(L, NULL, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010013062#endif
13063 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013064 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010013065
13066 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010013067 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010013068 break;
Thierry Fournier670db242020-11-28 10:49:59 +010013069
13070 case LUA_ERRERR:
13071 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010013072 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010013073 case LUA_ERRRUN:
13074 if (!kind)
13075 kind = "runtime error";
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010013076 msg = hlua_tostring_safe(L, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010013077 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010013078 if (msg)
13079 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
13080 else
13081 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
Aurelien DARRAGON93361a52024-03-01 19:54:16 +010013082
13083 lua_settop(L, 0); /* Empty the stack. */
Thierry Fournier670db242020-11-28 10:49:59 +010013084 return_status = 0;
13085 break;
13086
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013087 default:
Thierry Fournier670db242020-11-28 10:49:59 +010013088 /* Unknown error */
13089 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010013090 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010013091 case LUA_YIELD:
13092 /* yield is not configured at this step, this state doesn't happen */
13093 if (!kind)
13094 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010013095 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010013096 case LUA_ERRMEM:
13097 if (!kind)
13098 kind = "out of memory error";
Aurelien DARRAGON3e81aed2023-08-09 10:11:49 +020013099 lua_settop(L, 0); /* Empty the stack. */
Christopher Fauletd09cc512021-03-24 14:48:45 +010013100 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010013101 ha_alert("Lua init: %s: %s\n", kind, trace);
13102 return_status = 0;
13103 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013104 }
Thierry Fournier670db242020-11-28 10:49:59 +010013105 if (!return_status)
13106 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013107 }
Thierry Fournier3c539322020-11-28 16:05:05 +010013108
13109 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010013110 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013111}
13112
Thierry Fournierb8cef172020-11-28 15:37:17 +010013113int hlua_post_init()
13114{
Thierry Fournier59f11be2020-11-29 00:37:41 +010013115 int ret;
13116 int i;
13117 int errors;
13118 char *err = NULL;
13119 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013120 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013121
Willy Tarreaub1310492021-08-30 09:35:18 +020013122#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010013123 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013124 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010013125 int saved_used_backed = global.ssl_used_backend;
13126 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013127 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010013128 global.ssl_used_backend = saved_used_backed;
13129 }
13130#endif
13131
Thierry Fournierc7492592020-11-28 23:57:24 +010013132 /* Perform post init of common thread */
13133 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013134 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013135 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
13136 if (ret == 0)
13137 return 0;
13138
13139 /* init remaining lua states and load files */
13140 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
13141
13142 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013143 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013144
13145 /* Init lua state */
13146 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
13147
13148 /* Load lua files */
13149 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
13150 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
13151 if (ret != 0) {
13152 ha_alert("Lua init: %s\n", err);
13153 return 0;
13154 }
13155 }
13156 }
13157
13158 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013159 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013160
13161 /* Execute post init for all states */
13162 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
13163
13164 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013165 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013166
13167 /* run post init */
13168 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
13169 if (ret == 0)
13170 return 0;
13171 }
13172
13173 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013174 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013175
13176 /* control functions registering. Each function must have:
13177 * - only the function_ref[0] set positive and all other to -1
13178 * - only the function_ref[0] set to -1 and all other positive
13179 * This ensure a same reference is not used both in shared
13180 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013181 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010013182 * complicated to found for the end user.
13183 */
13184 errors = 0;
13185 list_for_each_entry(fcn, &referenced_functions, l) {
13186 ret = 0;
13187 for (i = 1; i < global.nbthread + 1; i++) {
13188 if (fcn->function_ref[i] == -1)
13189 ret--;
13190 else
13191 ret++;
13192 }
13193 if (abs(ret) != global.nbthread) {
13194 ha_alert("Lua function '%s' is not referenced in all thread. "
13195 "Expect function in all thread or in none thread.\n", fcn->name);
13196 errors++;
13197 continue;
13198 }
13199
13200 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013201 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
13202 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010013203 "exclusive.\n", fcn->name);
13204 errors++;
13205 }
13206 }
13207
Christopher Faulet69c581a2021-05-31 08:54:04 +020013208 /* Do the same with registered filters */
13209 list_for_each_entry(reg_flt, &referenced_filters, l) {
13210 ret = 0;
13211 for (i = 1; i < global.nbthread + 1; i++) {
13212 if (reg_flt->flt_ref[i] == -1)
13213 ret--;
13214 else
13215 ret++;
13216 }
13217 if (abs(ret) != global.nbthread) {
13218 ha_alert("Lua filter '%s' is not referenced in all thread. "
13219 "Expect function in all thread or in none thread.\n", reg_flt->name);
13220 errors++;
13221 continue;
13222 }
13223
13224 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
13225 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
13226 "and per-thread Lua context (through lua-load-per-thread). these two context "
13227 "exclusive.\n", fcn->name);
13228 errors++;
13229 }
13230 }
13231
13232
Thierry Fournier59f11be2020-11-29 00:37:41 +010013233 if (errors > 0)
13234 return 0;
13235
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013236 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010013237 * -1 in order to have probably a segfault if someone use it
13238 */
13239 hlua_state_id = -1;
13240
13241 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010013242}
13243
Willy Tarreau32f61e22015-03-18 17:54:59 +010013244/* The memory allocator used by the Lua stack. <ud> is a pointer to the
13245 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
13246 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013247 * allocation. <nsize> is the requested new size. A new allocation is
13248 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010013249 * zero. This one verifies that the limits are respected but is optimized
13250 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013251 *
13252 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
13253 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
13254 * that and will simply allocate zero as if it were the result of malloc(0),
13255 * so mapping this onto realloc() will lead to memory leaks on non-glibc
13256 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010013257 */
13258static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
13259{
13260 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010013261 size_t limit, old, new;
13262
13263 /* a limit of ~0 means unlimited and boot complete, so there's no need
13264 * for accounting anymore.
13265 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013266 if (likely(~zone->limit == 0)) {
13267 if (!nsize)
13268 ha_free(&ptr);
13269 else
13270 ptr = realloc(ptr, nsize);
13271 return ptr;
13272 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010013273
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013274 if (!ptr)
13275 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010013276
Willy Tarreaucdb53462020-12-02 12:12:00 +010013277 /* enforce strict limits across all threads */
13278 limit = zone->limit;
13279 old = _HA_ATOMIC_LOAD(&zone->allocated);
13280 do {
13281 new = old + nsize - osize;
13282 if (unlikely(nsize && limit && new > limit))
13283 return NULL;
13284 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010013285
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013286 if (!nsize)
13287 ha_free(&ptr);
13288 else
13289 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010013290
13291 if (unlikely(!ptr && nsize)) // failed
13292 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
13293
13294 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010013295 return ptr;
13296}
13297
Thierry Fournierecb83c22020-11-28 15:49:44 +010013298/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013299 * We are in the initialisation process of HAProxy, this abort() is
13300 * tolerated.
13301 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010013302lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013303{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013304 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013305 int idx;
13306 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013307 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013308 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013309 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013310 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013311 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013312 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013313
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013314 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013315 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013316
firexinghe64d7afb2023-07-13 11:03:34 +080013317 if (!L) {
13318 fprintf(stderr,
13319 "Lua init: critical error: lua_newstate() returned NULL."
13320 " This may possibly be caused by a memory allocation error.\n");
13321 exit(1);
13322 }
13323
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013324 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013325 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013326 *context = NULL;
13327
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013328 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013329 * the Lua function can fail with an abort. We are in the initialisation
13330 * process of HAProxy, this abort() is tolerated.
13331 */
13332
Thierry Fournier3c539322020-11-28 16:05:05 +010013333 /* Call post initialisation function in safe environment. */
13334 if (setjmp(safe_ljmp_env) != 0) {
13335 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013336 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONcf511892024-03-01 15:55:17 +010013337 error_msg = hlua_tostring_safe(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013338 else
13339 error_msg = "critical error";
13340 fprintf(stderr, "Lua init: %s.\n", error_msg);
13341 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013342 } else {
13343 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013344 }
13345
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013346 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013347 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013348#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
13349#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
13350#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013351 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013352#endif
13353#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013354 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013355#endif
13356#undef HLUA_PREPEND_PATH_TOSTRING
13357#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013358
Thierry Fournier59f11be2020-11-29 00:37:41 +010013359 /* Apply configured prepend path */
13360 list_for_each_entry(pp, &prepend_path_list, l)
13361 hlua_prepend_path(L, pp->type, pp->path);
13362
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013363 /*
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +020013364 * Override some lua functions.
13365 *
13366 */
13367
13368 /* push our "safe" coroutine.create() function */
13369 lua_getglobal(L, "coroutine");
13370 lua_pushcclosure(L, hlua_coroutine_create, 0);
13371 lua_setfield(L, -2, "create");
13372
13373 /*
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013374 *
13375 * Create "core" object.
13376 *
13377 */
13378
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010013379 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013380 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013381
Thierry Fournierecb83c22020-11-28 15:49:44 +010013382 /* set the thread id */
13383 hlua_class_const_int(L, "thread", thread_num);
13384
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013385 /* Push the loglevel constants. */
Christopher Faulet12a5ee72024-02-29 15:41:17 +010013386 hlua_class_const_int(L, "silent", -1);
Willy Tarreau80f5fae2015-02-27 16:38:20 +010013387 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013388 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013389
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013390 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013391 hlua_class_function(L, "register_init", hlua_register_init);
13392 hlua_class_function(L, "register_task", hlua_register_task);
13393 hlua_class_function(L, "register_fetches", hlua_register_fetches);
13394 hlua_class_function(L, "register_converters", hlua_register_converters);
13395 hlua_class_function(L, "register_action", hlua_register_action);
13396 hlua_class_function(L, "register_service", hlua_register_service);
13397 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020013398 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013399 hlua_class_function(L, "yield", hlua_yield);
13400 hlua_class_function(L, "set_nice", hlua_set_nice);
13401 hlua_class_function(L, "sleep", hlua_sleep);
13402 hlua_class_function(L, "msleep", hlua_msleep);
13403 hlua_class_function(L, "add_acl", hlua_add_acl);
13404 hlua_class_function(L, "del_acl", hlua_del_acl);
13405 hlua_class_function(L, "set_map", hlua_set_map);
13406 hlua_class_function(L, "del_map", hlua_del_map);
13407 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020013408 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010013409 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013410 hlua_class_function(L, "log", hlua_log);
13411 hlua_class_function(L, "Debug", hlua_log_debug);
13412 hlua_class_function(L, "Info", hlua_log_info);
13413 hlua_class_function(L, "Warning", hlua_log_warning);
13414 hlua_class_function(L, "Alert", hlua_log_alert);
13415 hlua_class_function(L, "done", hlua_done);
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020013416 hlua_class_function(L, "disable_legacy_mailers", hlua_disable_legacy_mailers);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013417 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013418
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013419 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013420
13421 /*
13422 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013423 * Create "act" object.
13424 *
13425 */
13426
13427 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013428 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013429
13430 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013431 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
13432 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
13433 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
13434 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
13435 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
13436 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
13437 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
13438 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013439
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013440 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010013441
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013442 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013443
13444 /*
13445 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020013446 * Create "Filter" object.
13447 *
13448 */
13449
13450 /* This table entry is the object "filter" base. */
13451 lua_newtable(L);
13452
13453 /* push flags and constants */
13454 hlua_class_const_int(L, "CONTINUE", 1);
13455 hlua_class_const_int(L, "WAIT", 0);
13456 hlua_class_const_int(L, "ERROR", -1);
13457
13458 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
13459
Christopher Fauletc404f112020-02-26 15:03:09 +010013460 hlua_class_function(L, "wake_time", hlua_set_wake_time);
13461 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
13462 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
13463
Christopher Faulet69c581a2021-05-31 08:54:04 +020013464 lua_setglobal(L, "filter");
13465
13466 /*
13467 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013468 * Register class Map
13469 *
13470 */
13471
13472 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013473 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013474
13475 /* register pattern types. */
13476 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013477 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013478 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013479 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013480 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013481 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013482
13483 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013484 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013485
13486 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013487 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013488
Ilya Shipitsind4259502020-04-08 01:07:56 +050013489 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013490 lua_pushstring(L, "__index");
13491 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013492
13493 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013494 hlua_class_function(L, "lookup", hlua_map_lookup);
13495 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013496
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013497 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013498
Thierry Fournier45e78d72016-02-19 18:34:46 +010013499 /* Register previous table in the registry with reference and named entry.
13500 * The function hlua_register_metatable() pops the stack, so we
13501 * previously create a copy of the table.
13502 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013503 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
13504 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013505
13506 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013507 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013508
13509 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013510 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013511
13512 /*
13513 *
William Lallemand30fcca12022-03-30 12:03:12 +020013514 * Register "CertCache" class
13515 *
13516 */
13517
13518 /* Create and fill the metatable. */
13519 lua_newtable(L);
13520 /* Register */
13521 hlua_class_function(L, "set", hlua_ckch_set);
13522 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
13523
13524 /*
13525 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013526 * Register class Channel
13527 *
13528 */
13529
13530 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013531 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013532
Ilya Shipitsind4259502020-04-08 01:07:56 +050013533 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013534 lua_pushstring(L, "__index");
13535 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013536
13537 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013538 hlua_class_function(L, "data", hlua_channel_get_data);
13539 hlua_class_function(L, "line", hlua_channel_get_line);
13540 hlua_class_function(L, "set", hlua_channel_set_data);
13541 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013542 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013543 hlua_class_function(L, "prepend", hlua_channel_prepend);
13544 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013545 hlua_class_function(L, "send", hlua_channel_send);
13546 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013547 hlua_class_function(L, "input", hlua_channel_get_in_len);
13548 hlua_class_function(L, "output", hlua_channel_get_out_len);
13549 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013550 hlua_class_function(L, "is_full", hlua_channel_is_full);
13551 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013552
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013553 /* Deprecated API */
13554 hlua_class_function(L, "get", hlua_channel_get);
13555 hlua_class_function(L, "dup", hlua_channel_dup);
13556 hlua_class_function(L, "getline", hlua_channel_getline);
13557 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13558 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13559
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013560 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013561
13562 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013563 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013564
13565 /*
13566 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013567 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013568 *
13569 */
13570
13571 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013572 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013573
Ilya Shipitsind4259502020-04-08 01:07:56 +050013574 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013575 lua_pushstring(L, "__index");
13576 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013577
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013578 /* Browse existing fetches and create the associated
13579 * object method.
13580 */
13581 sf = NULL;
13582 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013583 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13584 * by an underscore.
13585 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013586 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013587 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013588 if (*p == '.' || *p == '-' || *p == '+')
13589 *p = '_';
13590
13591 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013592 lua_pushstring(L, trash.area);
13593 lua_pushlightuserdata(L, sf);
13594 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13595 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013596 }
13597
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013598 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013599
13600 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013601 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013602
13603 /*
13604 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013605 * Register class Converters
13606 *
13607 */
13608
13609 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013610 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013611
13612 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013613 lua_pushstring(L, "__index");
13614 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013615
13616 /* Browse existing converters and create the associated
13617 * object method.
13618 */
13619 sc = NULL;
13620 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013621 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13622 * by an underscore.
13623 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013624 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013625 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013626 if (*p == '.' || *p == '-' || *p == '+')
13627 *p = '_';
13628
13629 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013630 lua_pushstring(L, trash.area);
13631 lua_pushlightuserdata(L, sc);
13632 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13633 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013634 }
13635
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013636 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013637
13638 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013639 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013640
13641 /*
13642 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013643 * Register class HTTP
13644 *
13645 */
13646
13647 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013648 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013649
Ilya Shipitsind4259502020-04-08 01:07:56 +050013650 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013651 lua_pushstring(L, "__index");
13652 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013653
13654 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013655 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13656 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13657 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13658 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13659 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13660 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13661 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13662 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13663 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13664 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013665
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013666 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13667 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13668 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13669 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13670 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13671 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13672 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013673
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013674 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013675
13676 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013677 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013678
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013679 /*
13680 *
13681 * Register class HTTPMessage
13682 *
13683 */
13684
13685 /* Create and fill the metatable. */
13686 lua_newtable(L);
13687
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013688 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013689 lua_pushstring(L, "__index");
13690 lua_newtable(L);
13691
13692 /* Register Lua functions. */
13693 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13694 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13695 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13696 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13697 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13698 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13699 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13700 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13701 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13702 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13703 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13704 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13705 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13706 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13707 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13708 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13709 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13710 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13711
13712 hlua_class_function(L, "body", hlua_http_msg_get_body);
13713 hlua_class_function(L, "set", hlua_http_msg_set_data);
13714 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13715 hlua_class_function(L, "append", hlua_http_msg_append);
13716 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13717 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13718 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13719 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13720
13721 hlua_class_function(L, "send", hlua_http_msg_send);
13722 hlua_class_function(L, "forward", hlua_http_msg_forward);
13723
13724 lua_rawset(L, -3);
13725
13726 /* Register previous table in the registry with reference and named entry. */
13727 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013728
13729 /*
13730 *
13731 * Register class HTTPClient
13732 *
13733 */
13734
13735 /* Create and fill the metatable. */
13736 lua_newtable(L);
13737 lua_pushstring(L, "__index");
13738 lua_newtable(L);
13739 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013740 hlua_class_function(L, "head", hlua_httpclient_head);
13741 hlua_class_function(L, "put", hlua_httpclient_put);
13742 hlua_class_function(L, "post", hlua_httpclient_post);
13743 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013744 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013745 /* Register the garbage collector entry. */
13746 lua_pushstring(L, "__gc");
13747 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13748 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13749
William Lallemand3956c4e2021-09-21 16:25:15 +020013750
13751
13752 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013753 /*
13754 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013755 * Register class AppletTCP
13756 *
13757 */
13758
13759 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013760 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013761
Ilya Shipitsind4259502020-04-08 01:07:56 +050013762 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013763 lua_pushstring(L, "__index");
13764 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013765
13766 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013767 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13768 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13769 hlua_class_function(L, "send", hlua_applet_tcp_send);
13770 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13771 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13772 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13773 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13774 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013775
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013776 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013777
13778 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013779 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013780
13781 /*
13782 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013783 * Register class AppletHTTP
13784 *
13785 */
13786
13787 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013788 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013789
Ilya Shipitsind4259502020-04-08 01:07:56 +050013790 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013791 lua_pushstring(L, "__index");
13792 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013793
13794 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013795 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13796 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13797 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13798 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13799 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13800 hlua_class_function(L, "getline", hlua_applet_http_getline);
13801 hlua_class_function(L, "receive", hlua_applet_http_recv);
13802 hlua_class_function(L, "send", hlua_applet_http_send);
13803 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13804 hlua_class_function(L, "set_status", hlua_applet_http_status);
13805 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013806
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013807 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013808
13809 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013810 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013811
13812 /*
13813 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013814 * Register class TXN
13815 *
13816 */
13817
13818 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013819 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013820
Ilya Shipitsind4259502020-04-08 01:07:56 +050013821 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013822 lua_pushstring(L, "__index");
13823 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013824
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013825 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013826 hlua_class_function(L, "set_priv", hlua_set_priv);
13827 hlua_class_function(L, "get_priv", hlua_get_priv);
13828 hlua_class_function(L, "set_var", hlua_set_var);
13829 hlua_class_function(L, "unset_var", hlua_unset_var);
13830 hlua_class_function(L, "get_var", hlua_get_var);
13831 hlua_class_function(L, "done", hlua_txn_done);
13832 hlua_class_function(L, "reply", hlua_txn_reply_new);
13833 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13834 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13835 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13836 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13837 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13838 hlua_class_function(L, "deflog", hlua_txn_deflog);
13839 hlua_class_function(L, "log", hlua_txn_log);
13840 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13841 hlua_class_function(L, "Info", hlua_txn_log_info);
13842 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13843 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013844
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013845 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013846
13847 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013848 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013849
13850 /*
13851 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013852 * Register class reply
13853 *
13854 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013855 lua_newtable(L);
13856 lua_pushstring(L, "__index");
13857 lua_newtable(L);
13858 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13859 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13860 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13861 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13862 lua_settable(L, -3); /* Sets the __index entry. */
13863 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013864
13865
13866 /*
13867 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013868 * Register class Socket
13869 *
13870 */
13871
13872 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013873 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013874
Ilya Shipitsind4259502020-04-08 01:07:56 +050013875 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013876 lua_pushstring(L, "__index");
13877 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013878
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013879#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013880 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013881#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013882 hlua_class_function(L, "connect", hlua_socket_connect);
13883 hlua_class_function(L, "send", hlua_socket_send);
13884 hlua_class_function(L, "receive", hlua_socket_receive);
13885 hlua_class_function(L, "close", hlua_socket_close);
13886 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13887 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13888 hlua_class_function(L, "setoption", hlua_socket_setoption);
13889 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013890
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013891 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013892
13893 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013894 lua_pushstring(L, "__gc");
13895 lua_pushcclosure(L, hlua_socket_gc, 0);
13896 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013897
13898 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013899 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013900
Thierry Fournieraafc7772020-12-04 11:47:47 +010013901 lua_atpanic(L, hlua_panic_safe);
13902
13903 return L;
13904}
13905
13906void hlua_init(void) {
13907 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013908 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013909#ifdef USE_OPENSSL
13910 struct srv_kw *kw;
13911 int tmp_error;
13912 char *error;
13913 char *args[] = { /* SSL client configuration. */
13914 "ssl",
13915 "verify",
13916 "none",
13917 NULL
13918 };
13919#endif
13920
13921 /* Init post init function list head */
13922 for (i = 0; i < MAX_THREADS + 1; i++)
13923 LIST_INIT(&hlua_init_functions[i]);
13924
13925 /* Init state for common/shared lua parts */
13926 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013927 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013928 hlua_states[0] = hlua_init_state(0);
13929
13930 /* Init state 1 for thread 0. We have at least one thread. */
13931 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013932 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013933 hlua_states[1] = hlua_init_state(1);
13934
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013935 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013936 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013937 if (!socket_proxy) {
13938 fprintf(stderr, "Lua init: %s\n", errmsg);
13939 exit(1);
13940 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013941
13942 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013943 socket_tcp = new_server(socket_proxy);
13944 if (!socket_tcp) {
13945 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13946 exit(1);
13947 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013948
13949#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013950 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013951 socket_ssl = new_server(socket_proxy);
13952 if (!socket_ssl) {
13953 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13954 exit(1);
13955 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013956
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013957 socket_ssl->use_ssl = 1;
13958 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013959
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013960 for (i = 0; args[i] != NULL; i++) {
13961 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013962 /*
13963 *
13964 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013965 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013966 * features like client certificates and ssl_verify.
13967 *
13968 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013969 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013970 if (tmp_error != 0) {
13971 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13972 abort(); /* This must be never arrives because the command line
13973 not editable by the user. */
13974 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013975 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013976 }
13977 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013978#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013979
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013980}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013981
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013982static void hlua_deinit()
13983{
Willy Tarreau186f3762020-12-04 11:48:12 +010013984 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013985 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13986
13987 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13988 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013989
13990 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13991 if (hlua_states[thr])
13992 lua_close(hlua_states[thr]);
13993 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013994
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013995 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013996
Willy Tarreau0f143af2021-03-05 10:41:48 +010013997#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013998 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013999#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010014000
14001 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020014002}
14003
14004REGISTER_POST_DEINIT(hlua_deinit);
14005
Willy Tarreau80713382018-11-26 10:19:54 +010014006static void hlua_register_build_options(void)
14007{
Willy Tarreaubb57d942016-12-21 19:04:56 +010014008 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010014009
Willy Tarreaubb57d942016-12-21 19:04:56 +010014010 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
14011 hap_register_build_opts(ptr, 1);
14012}
Willy Tarreau80713382018-11-26 10:19:54 +010014013
14014INITCALL0(STG_REGISTER, hlua_register_build_options);