blob: f7d6c760a1eb38204791dd225de7fcccd1f6630c [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
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010072/* Lua uses longjmp to perform yield or throwing errors. This
73 * macro is used only for identifying the function that can
74 * not return because a longjmp is executed.
75 * __LJMP marks a prototype of hlua file that can use longjmp.
76 * WILL_LJMP() marks an lua function that will use longjmp.
77 * MAY_LJMP() marks an lua function that may use longjmp.
78 */
79#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020080#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010081#define MAY_LJMP(func) func
82
Thierry FOURNIERbabae282015-09-17 11:36:37 +020083/* This couple of function executes securely some Lua calls outside of
84 * the lua runtime environment. Each Lua call can return a longjmp
85 * if it encounter a memory error.
86 *
87 * Lua documentation extract:
88 *
89 * If an error happens outside any protected environment, Lua calls
90 * a panic function (see lua_atpanic) and then calls abort, thus
91 * exiting the host application. Your panic function can avoid this
92 * exit by never returning (e.g., doing a long jump to your own
93 * recovery point outside Lua).
94 *
95 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010096 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020097 * stack. However, there is no guarantee about stack space. To push
98 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010099 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200100 *
101 * We must check all the Lua entry point. This includes:
102 * - The include/proto/hlua.h exported functions
103 * - the task wrapper function
104 * - The action wrapper function
105 * - The converters wrapper function
106 * - The sample-fetch wrapper functions
107 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500108 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800109 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200110 *
111 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
112 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
113 * because they must be exists in the program stack when the longjmp
114 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200115 *
116 * Note that the Lua processing is not really thread safe. It provides
117 * heavy system which consists to add our own lock function in the Lua
118 * code and recompile the library. This system will probably not accepted
119 * by maintainers of various distribs.
120 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500121 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200122 * quick looking on the Lua sources displays a lua_lock() a the start
123 * of function and a lua_unlock() at the end of the function. So I
124 * conclude that the Lua thread safe mode just perform a mutex around
125 * all execution. So I prefer to do this in the HAProxy code, it will be
126 * easier for distro maintainers.
127 *
128 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
129 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
130 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200131 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100132__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200133THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200135static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200136
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100137/* This is the chained list of struct hlua_function referenced
138 * for haproxy action, sample-fetches, converters, cli and
139 * applet bindings. It is used for a post-initialisation control.
140 */
141static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
142
Thierry Fournierc7492592020-11-28 23:57:24 +0100143/* This variable is used only during initialization to identify the Lua state
144 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
145 * states dedicated to each thread (in this case hlua_state_id==tid+1).
146 */
147static int hlua_state_id;
148
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200150static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100151
152lua_State *hlua_init_state(int thread_id);
153
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200154/* This function takes the Lua global lock. Keep this function's visibility
155 * global so that it can appear in stack dumps and performance profiles!
156 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100157static inline void lua_take_global_lock()
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200158{
159 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
160}
161
162static inline void lua_drop_global_lock()
163{
164 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
165}
166
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100167/* lua lock helpers: only lock when required
168 *
169 * state_id == 0: we're operating on the main lua stack (shared between
170 * os threads), so we need to acquire the main lock
171 *
172 * If the thread already owns the lock (_hlua_locked != 0), skip the lock
173 * attempt. This could happen if we run under protected lua environment.
174 * Not doing this could result in deadlocks because of nested locking
175 * attempts from the same thread
176 */
177static THREAD_LOCAL int _hlua_locked = 0;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100178static inline void hlua_lock(struct hlua *hlua)
179{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100180 if (hlua->state_id != 0)
181 return;
182 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100183 lua_take_global_lock();
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100184 _hlua_locked += 1;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100185}
186static inline void hlua_unlock(struct hlua *hlua)
187{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100188 if (hlua->state_id != 0)
189 return;
190 BUG_ON(_hlua_locked <= 0);
191 _hlua_locked--;
192 /* drop the lock once the lock count reaches 0 */
193 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100194 lua_drop_global_lock();
195}
196
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100197#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200198 ({ \
199 int ret; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100200 hlua_lock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200201 if (setjmp(safe_ljmp_env) != 0) { \
202 lua_atpanic(__L, hlua_panic_safe); \
203 ret = 0; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100204 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200205 } else { \
206 lua_atpanic(__L, hlua_panic_ljmp); \
207 ret = 1; \
208 } \
209 ret; \
210 })
211
212/* If we are the last function catching Lua errors, we
213 * must reset the panic function.
214 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100215#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200216 do { \
217 lua_atpanic(__L, hlua_panic_safe); \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100218 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200219 } while(0)
220
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100221#define SET_SAFE_LJMP(__HLUA) \
222 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
223
224#define RESET_SAFE_LJMP(__HLUA) \
225 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
226
227#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100228 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100229
230#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100231 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100232
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200233/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200234#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100235/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200236#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200237/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100238#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100239#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200240
Thierry Fournierafc63e22020-11-28 17:06:51 +0100241/* The main Lua execution context. The 0 index is the
242 * common state shared by all threads.
243 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100244static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100245
Christopher Fauletc404f112020-02-26 15:03:09 +0100246#define HLUA_FLT_CB_FINAL 0x00000001
247#define HLUA_FLT_CB_RETVAL 0x00000002
248#define HLUA_FLT_CB_ARG_CHN 0x00000004
249#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
250
Christopher Faulet9f55a502020-02-25 15:21:02 +0100251#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
252
Christopher Faulet69c581a2021-05-31 08:54:04 +0200253struct hlua_reg_filter {
254 char *name;
255 int flt_ref[MAX_THREADS + 1];
256 int fun_ref[MAX_THREADS + 1];
257 struct list l;
258};
259
260struct hlua_flt_config {
261 struct hlua_reg_filter *reg;
262 int ref[MAX_THREADS + 1];
263 char **args;
264};
265
266struct hlua_flt_ctx {
267 int ref; /* ref to the filter lua object */
268 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
269 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
270 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
271 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
272};
273
Willy Tarreau5321da92022-05-06 11:57:34 +0200274/* appctx context used by the cosockets */
275struct hlua_csk_ctx {
276 int connected;
277 struct xref xref; /* cross reference with the Lua object owner. */
278 struct list wake_on_read;
279 struct list wake_on_write;
280 struct appctx *appctx;
Christopher Faulet26786572023-09-27 17:39:44 +0200281 struct server *srv;
Christopher Fauletcb068552023-09-27 17:34:24 +0200282 int timeout;
Willy Tarreau5321da92022-05-06 11:57:34 +0200283 int die;
284};
285
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200286/* appctx context used by TCP services */
287struct hlua_tcp_ctx {
288 struct hlua *hlua;
289 int flags;
290 struct task *task;
291};
292
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200293/* appctx context used by HTTP services */
294struct hlua_http_ctx {
295 struct hlua *hlua;
296 int left_bytes; /* The max amount of bytes that we can read. */
297 int flags;
298 int status;
299 const char *reason;
300 struct task *task;
301};
302
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200303/* used by registered CLI keywords */
304struct hlua_cli_ctx {
305 struct hlua *hlua;
306 struct task *task;
307 struct hlua_function *fcn;
308};
309
Christopher Faulet69c581a2021-05-31 08:54:04 +0200310DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
311
Christopher Faulet9f55a502020-02-25 15:21:02 +0100312static int hlua_filter_from_payload(struct filter *filter);
313
Christopher Faulet69c581a2021-05-31 08:54:04 +0200314/* This is the chained list of struct hlua_flt referenced
315 * for haproxy filters. It is used for a post-initialisation control.
316 */
317static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
318
319
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100320/* This is the memory pool containing struct lua for applets
321 * (including cli).
322 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100323DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100324
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100325/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100326static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100327static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100328#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100329static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100330#endif
331
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100332/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100333struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100334
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100335/* The following variables contains the reference of the different
336 * Lua classes. These references are useful for identify metadata
337 * associated with an object.
338 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100339static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100340static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100341static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100342static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100343static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100344static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100345static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200346static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200347static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200348static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200349static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100350static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100351
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100352/* Lua max execution timeouts. By default, stream-related
353 * lua coroutines (e.g.: actions) have a short timeout.
354 * On the other hand tasks coroutines don't have a timeout because
355 * a task may remain alive during all the haproxy execution.
356 *
357 * Timeouts are expressed in milliseconds, they are meant to be used
358 * with hlua timer's API exclusively.
359 * 0 means no timeout
360 */
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200361static uint32_t hlua_timeout_burst = 1000; /* burst timeout. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100362static uint32_t hlua_timeout_session = 4000; /* session timeout. */
363static uint32_t hlua_timeout_task = 0; /* task timeout. */
364static uint32_t hlua_timeout_applet = 4000; /* applet timeout. */
365
366/* hlua multipurpose timer:
367 * used to compute burst lua time (within a single hlua_ctx_resume())
368 * and cumulative lua time for a given coroutine, and to check
369 * the lua coroutine against the configured timeouts
370 */
371
372/* fetch per-thread cpu_time with ms precision (may wrap) */
373static inline uint32_t _hlua_time_ms()
374{
375 /* We're interested in the current cpu time in ms, which will be returned
376 * as a uint32_t to save some space.
377 * We must take the following into account:
378 *
379 * - now_cpu_time_fast() which returns the time in nanoseconds as a uint64_t
380 * will wrap every 585 years.
381 * - uint32_t may only contain 4294967295ms (~=49.7 days), so _hlua_time_ms()
382 * itself will also wrap every 49.7 days.
383 *
384 * While we can safely ignore the now_cpu_time_fast() wrap, we must
385 * take care of the uint32_t wrap by making sure to exclusively
386 * manipulate the time using uint32_t everywhere _hlua_time_ms()
387 * is involved.
388 */
389 return (uint32_t)(now_cpu_time_fast() / 1000000ULL);
390}
391
392/* computes time spent in a single lua execution (in ms) */
393static inline uint32_t _hlua_time_burst(const struct hlua_timer *timer)
394{
395 uint32_t burst_ms;
396
397 /* wrapping is expected and properly
398 * handled thanks to _hlua_time_ms() and burst_ms
399 * being of the same type
400 */
401 burst_ms = _hlua_time_ms() - timer->start;
402 return burst_ms;
403}
404
405static inline void hlua_timer_init(struct hlua_timer *timer, unsigned int max)
406{
407 timer->cumulative = 0;
408 timer->burst = 0;
409 timer->max = max;
410}
411
412/* reset the timer ctx between 2 yields */
413static inline void hlua_timer_reset(struct hlua_timer *timer)
414{
415 timer->cumulative += timer->burst;
416 timer->burst = 0;
417}
418
419/* start the timer right before a new execution */
420static inline void hlua_timer_start(struct hlua_timer *timer)
421{
422 timer->start = _hlua_time_ms();
423}
424
425/* update hlua timer when finishing an execution */
426static inline void hlua_timer_stop(struct hlua_timer *timer)
427{
428 timer->burst += _hlua_time_burst(timer);
429}
430
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200431/* check the timers for current hlua context:
432 * - first check for burst timeout (max execution time for the current
433 hlua resume, ie: time between effective yields)
434 * - then check for yield cumulative timeout
435 *
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100436 * Returns 1 if the check succeeded and 0 if it failed
437 * (ie: timeout exceeded)
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100438 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100439static inline int hlua_timer_check(const struct hlua_timer *timer)
440{
441 uint32_t pburst = _hlua_time_burst(timer); /* pending burst time in ms */
442
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200443 if (hlua_timeout_burst && (timer->burst + pburst) > hlua_timeout_burst)
444 return 0; /* burst timeout exceeded */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100445 if (timer->max && (timer->cumulative + timer->burst + pburst) > timer->max)
446 return 0; /* cumulative timeout exceeded */
447 return 1; /* ok */
448}
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100449
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100450/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
451 * it is used for preventing infinite loops.
452 *
453 * I test the scheer with an infinite loop containing one incrementation
454 * and one test. I run this loop between 10 seconds, I raise a ceil of
455 * 710M loops from one interrupt each 9000 instructions, so I fix the value
456 * to one interrupt each 10 000 instructions.
457 *
458 * configured | Number of
459 * instructions | loops executed
460 * between two | in milions
461 * forced yields |
462 * ---------------+---------------
463 * 10 | 160
464 * 500 | 670
465 * 1000 | 680
466 * 5000 | 700
467 * 7000 | 700
468 * 8000 | 700
469 * 9000 | 710 <- ceil
470 * 10000 | 710
471 * 100000 | 710
472 * 1000000 | 710
473 *
474 */
475static unsigned int hlua_nb_instruction = 10000;
476
Willy Tarreaucdb53462020-12-02 12:12:00 +0100477/* Descriptor for the memory allocation state. The limit is pre-initialised to
478 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
479 * is replaced with ~0 during post_init after everything was loaded. This way
480 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
481 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100482 */
483struct hlua_mem_allocator {
484 size_t allocated;
485 size_t limit;
486};
487
Willy Tarreaucdb53462020-12-02 12:12:00 +0100488static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100489
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100490/* hlua event subscription */
491struct hlua_event_sub {
492 int fcn_ref;
493 int state_id;
494 struct hlua *hlua;
495 struct task *task;
496 event_hdl_async_equeue equeue;
497 struct event_hdl_sub *sub;
498 uint8_t paused;
499};
500
501/* This is the memory pool containing struct hlua_event_sub
502 * for event subscriptions from lua
503 */
504DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
505
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100506/* These functions converts types between HAProxy internal args or
507 * sample and LUA types. Another function permits to check if the
508 * LUA stack contains arguments according with an required ARG_T
509 * format.
510 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200511__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100512static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100513__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100514 uint64_t mask, struct proxy *p);
Aurelien DARRAGON41217722023-05-17 10:44:47 +0200515__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp);
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +0200516__LJMP static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100517static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
518
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100519__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200520
Thierry Fournier59f11be2020-11-29 00:37:41 +0100521struct prepend_path {
522 struct list l;
523 char *type;
524 char *path;
525};
526
527static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
528
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200529#define SEND_ERR(__be, __fmt, __args...) \
530 do { \
531 send_log(__be, LOG_ERR, __fmt, ## __args); \
532 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100533 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200534 } while (0)
535
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100536static inline struct hlua_function *new_hlua_function()
537{
538 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100539 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100540
541 fcn = calloc(1, sizeof(*fcn));
542 if (!fcn)
543 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200544 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100545 for (i = 0; i < MAX_THREADS + 1; i++)
546 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100547 return fcn;
548}
549
Christopher Fauletdda44442021-04-12 14:05:43 +0200550static inline void release_hlua_function(struct hlua_function *fcn)
551{
552 if (!fcn)
553 return;
554 if (fcn->name)
555 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200556 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200557 ha_free(&fcn);
558}
559
Thierry Fournierc7492592020-11-28 23:57:24 +0100560/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
561static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
562{
563 if (fcn->function_ref[0] == -1)
564 return tid + 1;
565 return 0;
566}
567
Christopher Faulet69c581a2021-05-31 08:54:04 +0200568/* Create a new registered filter. Only its name is filled */
569static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
570{
571 struct hlua_reg_filter *reg_flt;
572 int i;
573
574 reg_flt = calloc(1, sizeof(*reg_flt));
575 if (!reg_flt)
576 return NULL;
577 reg_flt->name = strdup(name);
578 if (!reg_flt->name) {
579 free(reg_flt);
580 return NULL;
581 }
582 LIST_APPEND(&referenced_filters, &reg_flt->l);
583 for (i = 0; i < MAX_THREADS + 1; i++) {
584 reg_flt->flt_ref[i] = -1;
585 reg_flt->fun_ref[i] = -1;
586 }
587 return reg_flt;
588}
589
590/* Release a registered filter */
591static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
592{
593 if (!reg_flt)
594 return;
595 if (reg_flt->name)
596 ha_free(&reg_flt->name);
597 LIST_DELETE(&reg_flt->l);
598 ha_free(&reg_flt);
599}
600
601/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
602static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
603{
604 if (reg_flt->fun_ref[0] == -1)
605 return tid + 1;
606 return 0;
607}
608
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100609/* Used to check an Lua function type in the stack. It creates and
610 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100611 * error if the argument is not a "function".
612 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100613 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100614__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100615{
616 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100617 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100618 WILL_LJMP(luaL_argerror(L, argno, msg));
619 }
620 lua_pushvalue(L, argno);
621 return luaL_ref(L, LUA_REGISTRYINDEX);
622}
623
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100624/* Used to check an Lua table type in the stack. It creates and
625 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100626 * error if the argument is not a "table".
627 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100628 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100629__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100630{
631 if (!lua_istable(L, argno)) {
632 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
633 WILL_LJMP(luaL_argerror(L, argno, msg));
634 }
635 lua_pushvalue(L, argno);
636 return luaL_ref(L, LUA_REGISTRYINDEX);
637}
638
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100639/* Get a reference to the object that is at the top of the stack
640 * The referenced object will be popped from the stack
641 *
642 * The function returns the reference to the object which must
643 * be cleared using hlua_unref() when no longer used
644 */
645__LJMP int hlua_ref(lua_State *L)
646{
647 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
648}
649
650/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
651 * on <L> stack
652 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
653 *
654 * When the reference is no longer used, it should be released by calling
655 * hlua_unref()
656 *
657 * <L> can be from any co-routine as long as it belongs to the same lua
658 * parent state that the one used to get the reference.
659 */
660void hlua_pushref(lua_State *L, int ref)
661{
662 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
663}
664
665/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
666 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
667 *
668 * This will allow the reference to be reused and the referred object
669 * to be garbage collected.
670 *
671 * <L> can be from any co-routine as long as it belongs to the same lua
672 * parent state that the one used to get the reference.
673 */
674void hlua_unref(lua_State *L, int ref)
675{
676 luaL_unref(L, LUA_REGISTRYINDEX, ref);
677}
678
Christopher Fauletd09cc512021-03-24 14:48:45 +0100679__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200680{
681 lua_Debug ar;
682 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200683 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200684
685 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200686 /* Fill fields:
687 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
688 * 'l': fills in the field currentline;
689 * 'n': fills in the field name and namewhat;
690 * 't': fills in the field istailcall;
691 */
692 lua_getinfo(L, "Slnt", &ar);
693
Willy Tarreau5c143402022-06-19 17:35:53 +0200694 /* skip these empty entries, usually they come from deep C functions */
695 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
696 continue;
697
698 /* Add separator */
699 if (b_data(msg))
700 chunk_appendf(msg, "%s", sep);
701
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200702 /* Append code localisation */
703 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100704 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200705 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100706 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200707
708 /*
709 * Get function name
710 *
711 * if namewhat is no empty, name is defined.
712 * what contains "Lua" for Lua function, "C" for C function,
713 * or "main" for main code.
714 */
715 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100716 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200717
718 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100719 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200720
721 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100722 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200723
724 else /* nothing left... */
725 chunk_appendf(msg, "?");
726
727
728 /* Display tailed call */
729 if (ar.istailcall)
730 chunk_appendf(msg, " ...");
731 }
732
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200733 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200734}
735
736
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100737/* This function check the number of arguments available in the
738 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500739 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100740 */
741__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
742{
743 if (lua_gettop(L) == nb)
744 return;
745 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
746}
747
Mark Lakes22154b42018-01-29 14:38:40 -0800748/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100749 * and the line number where the error is encountered.
750 */
751static int hlua_pusherror(lua_State *L, const char *fmt, ...)
752{
753 va_list argp;
754 va_start(argp, fmt);
755 luaL_where(L, 1);
756 lua_pushvfstring(L, fmt, argp);
757 va_end(argp);
758 lua_concat(L, 2);
759 return 1;
760}
761
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100762/* This functions is used with sample fetch and converters. It
763 * converts the HAProxy configuration argument in a lua stack
764 * values.
765 *
766 * It takes an array of "arg", and each entry of the array is
767 * converted and pushed in the LUA stack.
768 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200769__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770{
771 switch (arg->type) {
772 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100773 case ARGT_TIME:
774 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100775 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200779 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 break;
781
782 case ARGT_IPV4:
783 case ARGT_IPV6:
784 case ARGT_MSK4:
785 case ARGT_MSK6:
786 case ARGT_FE:
787 case ARGT_BE:
788 case ARGT_TAB:
789 case ARGT_SRV:
790 case ARGT_USR:
791 case ARGT_MAP:
792 default:
793 lua_pushnil(L);
794 break;
795 }
796 return 1;
797}
798
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500799/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100800 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500801 * with sample fetch wrappers. The input arguments are given to the
802 * lua wrapper and converted as arg list by the function.
Aurelien DARRAGON0aaf6c42023-05-17 15:33:59 +0200803 *
804 * Note: although lua_tolstring() may raise a memory error according to
805 * lua documentation, in practise this could only happen when using to
806 * use lua_tolstring() on a number (lua will try to push the number as a
807 * string on the stack, and this may result in memory failure), so here we
808 * assume that hlua_lua2arg() will never raise an exception since it is
809 * exclusively used with lua string inputs.
810 *
811 * Note2: You should be extra careful when using <arg> argument, since
812 * string arguments rely on lua_tolstring() which returns a pointer to lua
813 * object that may be garbage collected at any time when removed from lua
814 * stack, thus you should make sure that <arg> is only used from a local
815 * scope within lua context (and not exported or stored in a lua-independent
816 * ctx) and that related lua object still exists when accessing arg data.
817 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100818 */
819static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
820{
821 switch (lua_type(L, ud)) {
822
823 case LUA_TNUMBER:
824 case LUA_TBOOLEAN:
825 arg->type = ARGT_SINT;
826 arg->data.sint = lua_tointeger(L, ud);
827 break;
828
829 case LUA_TSTRING:
830 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200831 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200832 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200833 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200834 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100835 break;
836
837 case LUA_TUSERDATA:
838 case LUA_TNIL:
839 case LUA_TTABLE:
840 case LUA_TFUNCTION:
841 case LUA_TTHREAD:
842 case LUA_TLIGHTUSERDATA:
843 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200844 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100845 break;
846 }
847 return 1;
848}
849
850/* the following functions are used to convert a struct sample
851 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500852 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100853 */
Aurelien DARRAGON41217722023-05-17 10:44:47 +0200854__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100855{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200856 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100857 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100858 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200859 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100860 break;
861
862 case SMP_T_BIN:
863 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200864 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100865 break;
866
867 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200868 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100869 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
870 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
871 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
872 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
873 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
874 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
875 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
876 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
877 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200878 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 break;
880 default:
881 lua_pushnil(L);
882 break;
883 }
884 break;
885
886 case SMP_T_IPV4:
887 case SMP_T_IPV6:
888 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200889 if (sample_casts[smp->data.type][SMP_T_STR] &&
890 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200891 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100892 else
893 lua_pushnil(L);
894 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100895 default:
896 lua_pushnil(L);
897 break;
898 }
899 return 1;
900}
901
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100902/* the following functions are used to convert a struct sample
903 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500904 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100905 */
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +0200906__LJMP static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100907{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200908 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100909
910 case SMP_T_BIN:
911 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200912 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100913 break;
914
915 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200916 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100917 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
918 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
919 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
920 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
921 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
922 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
923 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
924 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
925 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200926 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100927 break;
928 default:
929 lua_pushstring(L, "");
930 break;
931 }
932 break;
933
934 case SMP_T_SINT:
935 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100936 case SMP_T_IPV4:
937 case SMP_T_IPV6:
938 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200939 if (sample_casts[smp->data.type][SMP_T_STR] &&
940 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200941 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100942 else
943 lua_pushstring(L, "");
944 break;
945 default:
946 lua_pushstring(L, "");
947 break;
948 }
949 return 1;
950}
951
Aurelien DARRAGONa3624cb2023-05-17 15:44:45 +0200952/* The following function is used to convert a Lua type to a
953 * struct sample. This is useful to provide data from LUA code to
954 * a converter.
955 *
956 * Note: although lua_tolstring() may raise a memory error according to
957 * lua documentation, in practise this could only happen when using to
958 * use lua_tolstring() on a number (lua will try to push the number as a
959 * string on the stack, and this may result in memory failure), so here we
960 * assume that hlua_lua2arg() will never raise an exception since it is
961 * exclusively used with lua string inputs.
962 *
963 * Note2: You should be extra careful when using <smp> argument, since
964 * string arguments rely on lua_tolstring() which returns a pointer to lua
965 * object that may be garbage collected at any time when removed from lua
966 * stack, thus you should make sure that <smp> is only used from a local
967 * scope within lua context (not exported or stored in a lua-independent
968 * ctx) and that related lua object still exists when accessing arg data.
969 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
970 *
971 * If you don't comply with this usage restriction, then you should consider
972 * duplicating the smp using smp_dup() to make it portable (little overhead),
973 * as this will ensure that the smp always points to valid memory block.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100974 */
975static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
976{
977 switch (lua_type(L, ud)) {
978
979 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200980 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200981 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100982 break;
983
984
985 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200986 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200987 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100988 break;
989
990 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200991 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100992 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200993 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200994 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200995 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200996 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100997 break;
998
999 case LUA_TUSERDATA:
1000 case LUA_TNIL:
1001 case LUA_TTABLE:
1002 case LUA_TFUNCTION:
1003 case LUA_TTHREAD:
1004 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +02001005 case LUA_TNONE:
1006 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001007 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001008 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001009 break;
1010 }
1011 return 1;
1012}
1013
Ilya Shipitsind4259502020-04-08 01:07:56 +05001014/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001015 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001016 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001017 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001018 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +02001019 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001020 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001021__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +01001022 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001023{
1024 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001025 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001026 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +02001027 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001028 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001029 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001030 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001031
1032 idx = 0;
1033 min_arg = ARGM(mask);
1034 mask >>= ARGM_BITS;
1035
1036 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001037 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001038
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001039 /* Check for mandatory arguments. */
1040 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001041 if (idx < min_arg) {
1042
1043 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001044 if (idx > 0) {
1045 msg = "Mandatory argument expected";
1046 goto error;
1047 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001048
1049 /* If first argument have a certain type, some default values
1050 * may be used. See the function smp_resolve_args().
1051 */
1052 switch (mask & ARGT_MASK) {
1053
1054 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001055 if (!(p->cap & PR_CAP_FE)) {
1056 msg = "Mandatory argument expected";
1057 goto error;
1058 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001059 argp[idx].data.prx = p;
1060 argp[idx].type = ARGT_FE;
1061 argp[idx+1].type = ARGT_STOP;
1062 break;
1063
1064 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001065 if (!(p->cap & PR_CAP_BE)) {
1066 msg = "Mandatory argument expected";
1067 goto error;
1068 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001069 argp[idx].data.prx = p;
1070 argp[idx].type = ARGT_BE;
1071 argp[idx+1].type = ARGT_STOP;
1072 break;
1073
1074 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001075 if (!p->table) {
1076 msg = "Mandatory argument expected";
1077 goto error;
1078 }
1079 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001080 argp[idx].type = ARGT_TAB;
1081 argp[idx+1].type = ARGT_STOP;
1082 break;
1083
1084 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001085 msg = "Mandatory argument expected";
1086 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001087 break;
1088 }
1089 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001090 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001091 }
1092
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001093 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001094 if ((mask & ARGT_MASK) == ARGT_STOP &&
1095 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001096 msg = "Last argument expected";
1097 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001098 }
1099
1100 if ((mask & ARGT_MASK) == ARGT_STOP &&
1101 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001102 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001103 }
1104
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 /* Convert some argument types. All string in argp[] are for not
1106 * duplicated yet.
1107 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001108 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001109 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001110 if (argp[idx].type != ARGT_SINT) {
1111 msg = "integer expected";
1112 goto error;
1113 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001114 argp[idx].type = ARGT_SINT;
1115 break;
1116
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001117 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001118 if (argp[idx].type != ARGT_SINT) {
1119 msg = "integer expected";
1120 goto error;
1121 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001122 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001123 break;
1124
1125 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001126 if (argp[idx].type != ARGT_SINT) {
1127 msg = "integer expected";
1128 goto error;
1129 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001130 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001131 break;
1132
1133 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001134 if (argp[idx].type != ARGT_STR) {
1135 msg = "string expected";
1136 goto error;
1137 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001138 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001139 if (!argp[idx].data.prx) {
1140 msg = "frontend doesn't exist";
1141 goto error;
1142 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001143 argp[idx].type = ARGT_FE;
1144 break;
1145
1146 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001147 if (argp[idx].type != ARGT_STR) {
1148 msg = "string expected";
1149 goto error;
1150 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001151 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001152 if (!argp[idx].data.prx) {
1153 msg = "backend doesn't exist";
1154 goto error;
1155 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001156 argp[idx].type = ARGT_BE;
1157 break;
1158
1159 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001160 if (argp[idx].type != ARGT_STR) {
1161 msg = "string expected";
1162 goto error;
1163 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001164 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001165 if (!argp[idx].data.t) {
1166 msg = "table doesn't exist";
1167 goto error;
1168 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001169 argp[idx].type = ARGT_TAB;
1170 break;
1171
1172 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001173 if (argp[idx].type != ARGT_STR) {
1174 msg = "string expected";
1175 goto error;
1176 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001177 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001178 if (sname) {
1179 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001180 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001181 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001182 if (!px) {
1183 msg = "backend doesn't exist";
1184 goto error;
1185 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001186 }
1187 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001188 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001189 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001190 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001191 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001192 if (!argp[idx].data.srv) {
1193 msg = "server doesn't exist";
1194 goto error;
1195 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001196 argp[idx].type = ARGT_SRV;
1197 break;
1198
1199 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001200 if (argp[idx].type != ARGT_STR) {
1201 msg = "string expected";
1202 goto error;
1203 }
1204 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1205 msg = "invalid IPv4 address";
1206 goto error;
1207 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001208 argp[idx].type = ARGT_IPV4;
1209 break;
1210
1211 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001212 if (argp[idx].type == ARGT_SINT)
1213 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1214 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001215 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1216 msg = "invalid IPv4 mask";
1217 goto error;
1218 }
1219 }
1220 else {
1221 msg = "integer or string expected";
1222 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001223 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001224 argp[idx].type = ARGT_MSK4;
1225 break;
1226
1227 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001228 if (argp[idx].type != ARGT_STR) {
1229 msg = "string expected";
1230 goto error;
1231 }
1232 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1233 msg = "invalid IPv6 address";
1234 goto error;
1235 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001236 argp[idx].type = ARGT_IPV6;
1237 break;
1238
1239 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001240 if (argp[idx].type == ARGT_SINT)
1241 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1242 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001243 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1244 msg = "invalid IPv6 mask";
1245 goto error;
1246 }
1247 }
1248 else {
1249 msg = "integer or string expected";
1250 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001251 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001252 argp[idx].type = ARGT_MSK6;
1253 break;
1254
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001255 case ARGT_REG:
1256 if (argp[idx].type != ARGT_STR) {
1257 msg = "string expected";
1258 goto error;
1259 }
1260 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1261 if (!reg) {
1262 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1263 argp[idx].data.str.area, err);
1264 free(err);
1265 goto error;
1266 }
1267 argp[idx].type = ARGT_REG;
1268 argp[idx].data.reg = reg;
1269 break;
1270
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001271 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001272 if (argp[idx].type != ARGT_STR) {
1273 msg = "string expected";
1274 goto error;
1275 }
1276 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001277 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001278 ul = p->uri_auth->userlist;
1279 else
1280 ul = auth_find_userlist(argp[idx].data.str.area);
1281
1282 if (!ul) {
1283 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1284 goto error;
1285 }
1286 argp[idx].type = ARGT_USR;
1287 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001288 break;
1289
1290 case ARGT_STR:
1291 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1292 msg = "unable to duplicate string arg";
1293 goto error;
1294 }
1295 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001296 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001297
Christopher Fauletd25d9262020-08-06 11:04:46 +02001298 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001299 msg = "type not yet supported";
1300 goto error;
1301 break;
1302
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001303 }
1304
1305 /* Check for type of argument. */
1306 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001307 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1308 arg_type_names[(mask & ARGT_MASK)],
1309 arg_type_names[argp[idx].type & ARGT_MASK]);
1310 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001311 }
1312
1313 /* Next argument. */
1314 mask >>= ARGT_BITS;
1315 idx++;
1316 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001317 return 0;
1318
1319 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001320 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001321 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001322 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1323 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001324}
1325
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001326/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001327 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001328 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001329 *
1330 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001331 * - hlua_sethlua : create the association between hlua context and lua_state.
1332 */
Aurelien DARRAGON40cd44f2023-05-04 13:59:48 +02001333inline struct hlua *hlua_gethlua(lua_State *L)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001334{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001335 struct hlua **hlua = lua_getextraspace(L);
1336 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001337}
1338static inline void hlua_sethlua(struct hlua *hlua)
1339{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001340 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1341 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001342}
1343
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001344/* Will return a non-NULL string indicating the Lua call trace if the caller
1345 * currently is executing from within a Lua function. One line per entry will
1346 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1347 * Lua function is not detected, NULL is returned.
1348 */
1349const char *hlua_show_current_location(const char *pfx)
1350{
1351 lua_State *L;
1352 lua_Debug ar;
1353
1354 /* global or per-thread stack initializing ? */
1355 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1356 return hlua_traceback(L, pfx);
1357
1358 /* per-thread stack running ? */
1359 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1360 return hlua_traceback(L, pfx);
1361
1362 /* global stack running ? */
1363 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1364 return hlua_traceback(L, pfx);
1365
1366 return NULL;
1367}
1368
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001369/* This function is used to send logs. It try to send on screen (stderr)
1370 * and on the default syslog server.
1371 */
1372static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1373{
1374 struct tm tm;
1375 char *p;
1376
1377 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001378 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001379 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001380 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001381 /* Break the message if exceed the buffer size. */
1382 *(p-4) = ' ';
1383 *(p-3) = '.';
1384 *(p-2) = '.';
1385 *(p-1) = '.';
1386 break;
1387 }
Willy Tarreau90807112020-02-25 08:16:33 +01001388 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001389 *p = *msg;
1390 else
1391 *p = '.';
1392 }
1393 *p = '\0';
1394
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001395 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001396 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001397 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1398 return;
1399
Willy Tarreaua678b432015-08-28 10:14:59 +02001400 get_localtime(date.tv_sec, &tm);
1401 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001402 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001403 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001404 fflush(stderr);
1405 }
1406}
1407
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001408/* This function just ensure that the yield will be always
1409 * returned with a timeout and permit to set some flags
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02001410 * <timeout> is a tick value
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001411 */
Aurelien DARRAGONbcdf07e2023-07-13 10:18:04 +02001412__LJMP void hlua_yieldk(lua_State *L, int nresults, lua_KContext ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001413 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001414{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001415 struct hlua *hlua;
1416
1417 /* Get hlua struct, or NULL if we execute from main lua state */
1418 hlua = hlua_gethlua(L);
1419 if (!hlua) {
1420 return;
1421 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001422
1423 /* Set the wake timeout. If timeout is required, we set
1424 * the expiration time.
1425 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001426 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001427
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001428 hlua->flags |= flags;
1429
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001430 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001431 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001432}
1433
Willy Tarreau87b09662015-04-03 00:22:06 +02001434/* This function initialises the Lua environment stored in the stream.
1435 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001436 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001437 *
1438 * This function is particular. it initialises a new Lua thread. If the
1439 * initialisation fails (example: out of memory error), the lua function
1440 * throws an error (longjmp).
1441 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001442 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001443 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001444 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001445 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001446 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001447int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001448{
1449 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001450 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001451 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001452 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001453 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001454 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001455 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001456 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001457 if (!SET_SAFE_LJMP_PARENT(lua)) {
1458 lua->Tref = LUA_REFNIL;
1459 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001460 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001461 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001462 if (!lua->T) {
1463 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001464 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001465 return 0;
1466 }
1467 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001468 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001469 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001470 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001471 return 1;
1472}
1473
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001474/* kill all associated httpclient to this hlua task
1475 * We must take extra precautions as we're manipulating lua-exposed
1476 * objects without the main lua lock.
1477 */
William Lallemandbb581422022-10-20 10:57:28 +02001478static void hlua_httpclient_destroy_all(struct hlua *hlua)
1479{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001480 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001481
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001482 /* use thread-safe accessors for hc_list since GC cycle initiated by
1483 * another thread sharing the same main lua stack (lua coroutine)
1484 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1485 * in parallel: Lua GC applies on the main stack, it is not limited to
1486 * a single coroutine stack, see Github issue #2037 for reference.
1487 * Remember, coroutines created using lua_newthread() are not meant to
1488 * be thread safe in Lua. (From lua co-author:
1489 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1490 *
1491 * This security measure is superfluous when 'lua-load-per-thread' is used
1492 * since in this case coroutines exclusively run on the same thread
1493 * (main stack is not shared between OS threads).
1494 */
1495 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1496 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001497 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001498 }
1499}
1500
1501
Willy Tarreau87b09662015-04-03 00:22:06 +02001502/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001503 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001504 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001505 */
1506void hlua_ctx_destroy(struct hlua *lua)
1507{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001508 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001509 return;
1510
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001511 if (!lua->T)
1512 goto end;
1513
William Lallemandbb581422022-10-20 10:57:28 +02001514 /* clean all running httpclient */
1515 hlua_httpclient_destroy_all(lua);
1516
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001517 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001518 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001519
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001520 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001521 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001522 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001523 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001524
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001525 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001526 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001527 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001528 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001529 /* Forces a garbage collecting process. If the Lua program is finished
1530 * without error, we run the GC on the thread pointer. Its freed all
1531 * the unused memory.
1532 * If the thread is finnish with an error or is currently yielded,
1533 * it seems that the GC applied on the thread doesn't clean anything,
1534 * so e run the GC on the main thread.
1535 * NOTE: maybe this action locks all the Lua threads untiml the en of
1536 * the garbage collection.
1537 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001538 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001539 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001540 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001541 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001542 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001543 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001544
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001545 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001546
1547end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001548 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001549}
1550
1551/* This function is used to restore the Lua context when a coroutine
1552 * fails. This function copy the common memory between old coroutine
1553 * and the new coroutine. The old coroutine is destroyed, and its
1554 * replaced by the new coroutine.
1555 * If the flag "keep_msg" is set, the last entry of the old is assumed
1556 * as string error message and it is copied in the new stack.
1557 */
1558static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1559{
1560 lua_State *T;
1561 int new_ref;
1562
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001563 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001564 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001565 if (!T)
1566 return 0;
1567
1568 /* Copy last error message. */
1569 if (keep_msg)
1570 lua_xmove(lua->T, T, 1);
1571
1572 /* Copy data between the coroutines. */
1573 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1574 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001575 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001576
1577 /* Destroy old data. */
1578 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1579
1580 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001581 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001582
1583 /* Fill the struct with the new coroutine values. */
1584 lua->Mref = new_ref;
1585 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001586 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001587
1588 /* Set context. */
1589 hlua_sethlua(lua);
1590
1591 return 1;
1592}
1593
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001594void hlua_hook(lua_State *L, lua_Debug *ar)
1595{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001596 struct hlua *hlua;
1597
1598 /* Get hlua struct, or NULL if we execute from main lua state */
1599 hlua = hlua_gethlua(L);
1600 if (!hlua)
1601 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001602
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001603 if (hlua->T != L) {
1604 /* We don't want to enforce a yield on a sub coroutine, since
1605 * we have no guarantees that the yield will be handled properly.
1606 * Indeed, only the hlua->T coroutine is being handled through
1607 * hlua_ctx_resume() function.
1608 *
1609 * Instead, we simply check for timeouts and wait for the sub
1610 * coroutine to finish..
1611 */
1612 goto check_timeout;
1613 }
1614
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001615 /* Lua cannot yield when its returning from a function,
1616 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001617 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001618 */
1619 if (lua_gethookmask(L) & LUA_MASKRET) {
1620 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1621 return;
1622 }
1623
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001624 /* If we interrupt the Lua processing in yieldable state, we yield.
1625 * If the state is not yieldable, trying yield causes an error.
1626 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001627 if (lua_isyieldable(L)) {
1628 /* note: for converters/fetches.. where yielding is not allowed
1629 * hlua_ctx_resume() will simply perform a goto resume_execution
1630 * instead of rescheduling hlua->task.
1631 * also: hlua_ctx_resume() will take care of checking execution
1632 * timeout and re-applying the hook as needed.
1633 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001634 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001635 /* lua docs says that the hook should return immediately after lua_yieldk
1636 *
1637 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1638 *
1639 * Moreover, it seems that we don't want to continue after the yield
1640 * because the end of the function is about handling unyieldable function,
1641 * which is not the case here.
1642 *
1643 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1644 * in the function.
1645 */
1646 return;
1647 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001648
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001649 check_timeout:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001650 /* If we cannot yield, check the timeout. */
1651 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001652 lua_pushfstring(L, "execution timeout");
1653 WILL_LJMP(lua_error(L));
1654 }
1655
1656 /* Try to interrupt the process at the end of the current
1657 * unyieldable function.
1658 */
1659 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001660}
1661
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001662/* This function start or resumes the Lua stack execution. If the flag
1663 * "yield_allowed" if no set and the LUA stack execution returns a yield
1664 * The function return an error.
1665 *
1666 * The function can returns 4 values:
1667 * - HLUA_E_OK : The execution is terminated without any errors.
1668 * - HLUA_E_AGAIN : The execution must continue at the next associated
1669 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001670 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001671 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001672 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001673 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001674 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001675 * LUA code.
1676 */
1677static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1678{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001679#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1680 int nres;
1681#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001682 int ret;
1683 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001684 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001685
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001686 /* Lock the whole Lua execution. This lock must be before the
1687 * label "resume_execution".
1688 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001689 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001690
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001691 /* reset the timer as we might be re-entering the function to
1692 * resume the coroutine after a successful yield
1693 * (cumulative time will be updated)
1694 */
1695 hlua_timer_reset(&lua->timer);
1696
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001697resume_execution:
1698
1699 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1700 * instructions. it is used for preventing infinite loops.
1701 */
1702 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1703
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001704 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001705 HLUA_SET_RUN(lua);
1706 HLUA_CLR_CTRLYIELD(lua);
1707 HLUA_CLR_WAKERESWR(lua);
1708 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001709 HLUA_CLR_NOYIELD(lua);
1710 if (!yield_allowed)
1711 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001712
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001713 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001714 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001715
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001716 /* start the timer as we're about to start lua processing */
1717 hlua_timer_start(&lua->timer);
1718
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001719 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001720#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001721 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001722#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001723 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001724#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001725
1726 /* out of lua processing, stop the timer */
1727 hlua_timer_stop(&lua->timer);
1728
Aurelien DARRAGONfa76a102023-09-08 14:00:27 +02001729 /* reset nargs because those possibly passed to the lua_resume() call
1730 * were already consumed, and since we may call lua_resume() again
1731 * after a successful yield, we don't want to pass stale nargs hint
1732 * to the Lua API. As such, nargs should be set explicitly before each
1733 * lua_resume() (or hlua_ctx_resume()) invocation if needed.
1734 */
1735 lua->nargs = 0;
1736
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001737 switch (ret) {
1738
1739 case LUA_OK:
1740 ret = HLUA_E_OK;
1741 break;
1742
1743 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001744 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001745 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001746 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001747 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001748 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001749 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001750 break;
1751 }
1752 /* Process the forced yield. if the general yield is not allowed or
1753 * if no task were associated this the current Lua execution
1754 * coroutine, we resume the execution. Else we want to return in the
1755 * scheduler and we want to be waked up again, to continue the
1756 * current Lua execution. So we schedule our own task.
1757 */
1758 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001759 if (!yield_allowed || !lua->task)
1760 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001761 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001762 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001763 if (!yield_allowed) {
1764 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001765 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001766 break;
1767 }
1768 ret = HLUA_E_AGAIN;
1769 break;
1770
1771 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001772
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001773 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001774 * because the errors ares the only one mean to return immediately
1775 * from and lua execution.
1776 */
1777 if (lua->flags & HLUA_EXIT) {
1778 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001779 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001780 break;
1781 }
1782
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001783 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001784 if (!lua_checkstack(lua->T, 1)) {
1785 ret = HLUA_E_ERR;
1786 break;
1787 }
1788 msg = lua_tostring(lua->T, -1);
1789 lua_settop(lua->T, 0); /* Empty the stack. */
Christopher Fauletd09cc512021-03-24 14:48:45 +01001790 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001791 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001792 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001793 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001794 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001795 ret = HLUA_E_ERRMSG;
1796 break;
1797
1798 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001799 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001800 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001801 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001802 break;
1803
1804 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001805 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001806 if (!lua_checkstack(lua->T, 1)) {
1807 ret = HLUA_E_ERR;
1808 break;
1809 }
1810 msg = lua_tostring(lua->T, -1);
1811 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001812 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001813 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001814 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001815 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001816 ret = HLUA_E_ERRMSG;
1817 break;
1818
1819 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001820 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001821 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001822 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001823 break;
1824 }
1825
1826 switch (ret) {
1827 case HLUA_E_AGAIN:
1828 break;
1829
1830 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001831 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001832 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001833 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001834 break;
1835
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001836 case HLUA_E_ETMOUT:
1837 case HLUA_E_NOMEM:
1838 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001839 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001840 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001841 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001842 hlua_ctx_renew(lua, 0);
1843 break;
1844
1845 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001846 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001847 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001848 break;
1849 }
1850
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001851 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001852 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001853
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001854 return ret;
1855}
1856
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001857/* This function exit the current code. */
1858__LJMP static int hlua_done(lua_State *L)
1859{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001860 struct hlua *hlua;
1861
1862 /* Get hlua struct, or NULL if we execute from main lua state */
1863 hlua = hlua_gethlua(L);
1864 if (!hlua)
1865 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001866
1867 hlua->flags |= HLUA_EXIT;
1868 WILL_LJMP(lua_error(L));
1869
1870 return 0;
1871}
1872
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001873/* This function is an LUA binding. It provides a function
1874 * for deleting ACL from a referenced ACL file.
1875 */
1876__LJMP static int hlua_del_acl(lua_State *L)
1877{
1878 const char *name;
1879 const char *key;
1880 struct pat_ref *ref;
1881
1882 MAY_LJMP(check_args(L, 2, "del_acl"));
1883
1884 name = MAY_LJMP(luaL_checkstring(L, 1));
1885 key = MAY_LJMP(luaL_checkstring(L, 2));
1886
1887 ref = pat_ref_lookup(name);
1888 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001889 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001890
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001891 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001892 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001893 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001894 return 0;
1895}
1896
1897/* This function is an LUA binding. It provides a function
1898 * for deleting map entry from a referenced map file.
1899 */
1900static int hlua_del_map(lua_State *L)
1901{
1902 const char *name;
1903 const char *key;
1904 struct pat_ref *ref;
1905
1906 MAY_LJMP(check_args(L, 2, "del_map"));
1907
1908 name = MAY_LJMP(luaL_checkstring(L, 1));
1909 key = MAY_LJMP(luaL_checkstring(L, 2));
1910
1911 ref = pat_ref_lookup(name);
1912 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001913 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001914
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001915 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001916 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001917 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001918 return 0;
1919}
1920
1921/* This function is an LUA binding. It provides a function
1922 * for adding ACL pattern from a referenced ACL file.
1923 */
1924static int hlua_add_acl(lua_State *L)
1925{
1926 const char *name;
1927 const char *key;
1928 struct pat_ref *ref;
1929
1930 MAY_LJMP(check_args(L, 2, "add_acl"));
1931
1932 name = MAY_LJMP(luaL_checkstring(L, 1));
1933 key = MAY_LJMP(luaL_checkstring(L, 2));
1934
1935 ref = pat_ref_lookup(name);
1936 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001937 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001938
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001939 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001940 if (pat_ref_find_elt(ref, key) == NULL)
1941 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001942 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001943 return 0;
1944}
1945
1946/* This function is an LUA binding. It provides a function
1947 * for setting map pattern and sample from a referenced map
1948 * file.
1949 */
1950static int hlua_set_map(lua_State *L)
1951{
1952 const char *name;
1953 const char *key;
1954 const char *value;
1955 struct pat_ref *ref;
1956
1957 MAY_LJMP(check_args(L, 3, "set_map"));
1958
1959 name = MAY_LJMP(luaL_checkstring(L, 1));
1960 key = MAY_LJMP(luaL_checkstring(L, 2));
1961 value = MAY_LJMP(luaL_checkstring(L, 3));
1962
1963 ref = pat_ref_lookup(name);
1964 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001965 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001966
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001967 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001968 if (pat_ref_find_elt(ref, key) != NULL)
1969 pat_ref_set(ref, key, value, NULL);
1970 else
1971 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001972 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001973 return 0;
1974}
1975
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +02001976/* This function disables the sending of email through the
1977 * legacy email sending function which is implemented using
1978 * checks.
1979 *
1980 * It may not be used during runtime.
1981 */
1982__LJMP static int hlua_disable_legacy_mailers(lua_State *L)
1983{
1984 if (hlua_gethlua(L))
1985 WILL_LJMP(luaL_error(L, "disable_legacy_mailers: "
1986 "not available outside of init or body context"));
1987 send_email_disabled = 1;
1988 return 0;
1989}
1990
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001991/* A class is a lot of memory that contain data. This data can be a table,
1992 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001993 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001994 * the name of the object (_G[<name>] = <metable> ).
1995 *
1996 * A metable is a table that modify the standard behavior of a standard
1997 * access to the associated data. The entries of this new metatable are
1998 * defined as is:
1999 *
2000 * http://lua-users.org/wiki/MetatableEvents
2001 *
2002 * __index
2003 *
2004 * we access an absent field in a table, the result is nil. This is
2005 * true, but it is not the whole truth. Actually, such access triggers
2006 * the interpreter to look for an __index metamethod: If there is no
2007 * such method, as usually happens, then the access results in nil;
2008 * otherwise, the metamethod will provide the result.
2009 *
2010 * Control 'prototype' inheritance. When accessing "myTable[key]" and
2011 * the key does not appear in the table, but the metatable has an __index
2012 * property:
2013 *
2014 * - if the value is a function, the function is called, passing in the
2015 * table and the key; the return value of that function is returned as
2016 * the result.
2017 *
2018 * - if the value is another table, the value of the key in that table is
2019 * asked for and returned (and if it doesn't exist in that table, but that
2020 * table's metatable has an __index property, then it continues on up)
2021 *
2022 * - Use "rawget(myTable,key)" to skip this metamethod.
2023 *
2024 * http://www.lua.org/pil/13.4.1.html
2025 *
2026 * __newindex
2027 *
2028 * Like __index, but control property assignment.
2029 *
2030 * __mode - Control weak references. A string value with one or both
2031 * of the characters 'k' and 'v' which specifies that the the
2032 * keys and/or values in the table are weak references.
2033 *
2034 * __call - Treat a table like a function. When a table is followed by
2035 * parenthesis such as "myTable( 'foo' )" and the metatable has
2036 * a __call key pointing to a function, that function is invoked
2037 * (passing any specified arguments) and the return value is
2038 * returned.
2039 *
2040 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
2041 * called, if the metatable for myTable has a __metatable
2042 * key, the value of that key is returned instead of the
2043 * actual metatable.
2044 *
2045 * __tostring - Control string representation. When the builtin
2046 * "tostring( myTable )" function is called, if the metatable
2047 * for myTable has a __tostring property set to a function,
2048 * that function is invoked (passing myTable to it) and the
2049 * return value is used as the string representation.
2050 *
2051 * __len - Control table length. When the table length is requested using
2052 * the length operator ( '#' ), if the metatable for myTable has
2053 * a __len key pointing to a function, that function is invoked
2054 * (passing myTable to it) and the return value used as the value
2055 * of "#myTable".
2056 *
2057 * __gc - Userdata finalizer code. When userdata is set to be garbage
2058 * collected, if the metatable has a __gc field pointing to a
2059 * function, that function is first invoked, passing the userdata
2060 * to it. The __gc metamethod is not called for tables.
2061 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
2062 *
2063 * Special metamethods for redefining standard operators:
2064 * http://www.lua.org/pil/13.1.html
2065 *
2066 * __add "+"
2067 * __sub "-"
2068 * __mul "*"
2069 * __div "/"
2070 * __unm "!"
2071 * __pow "^"
2072 * __concat ".."
2073 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002074 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002075 * http://www.lua.org/pil/13.2.html
2076 *
2077 * __eq "=="
2078 * __lt "<"
2079 * __le "<="
2080 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081
2082/*
2083 *
2084 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002085 * Class Map
2086 *
2087 *
2088 */
2089
2090/* Returns a struct hlua_map if the stack entry "ud" is
2091 * a class session, otherwise it throws an error.
2092 */
2093__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2094{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002095 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002096}
2097
2098/* This function is the map constructor. It don't need
2099 * the class Map object. It creates and return a new Map
2100 * object. It must be called only during "body" or "init"
2101 * context because it process some filesystem accesses.
2102 */
2103__LJMP static int hlua_map_new(struct lua_State *L)
2104{
2105 const char *fn;
2106 int match = PAT_MATCH_STR;
2107 struct sample_conv conv;
2108 const char *file = "";
2109 int line = 0;
2110 lua_Debug ar;
2111 char *err = NULL;
2112 struct arg args[2];
2113
2114 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2115 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2116
2117 fn = MAY_LJMP(luaL_checkstring(L, 1));
2118
2119 if (lua_gettop(L) >= 2) {
2120 match = MAY_LJMP(luaL_checkinteger(L, 2));
2121 if (match < 0 || match >= PAT_MATCH_NUM)
2122 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2123 }
2124
2125 /* Get Lua filename and line number. */
2126 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2127 lua_getinfo(L, "Sl", &ar); /* get info about it */
2128 if (ar.currentline > 0) { /* is there info? */
2129 file = ar.short_src;
2130 line = ar.currentline;
2131 }
2132 }
2133
2134 /* fill fake sample_conv struct. */
2135 conv.kw = ""; /* unused. */
2136 conv.process = NULL; /* unused. */
2137 conv.arg_mask = 0; /* unused. */
2138 conv.val_args = NULL; /* unused. */
2139 conv.out_type = SMP_T_STR;
2140 conv.private = (void *)(long)match;
2141 switch (match) {
2142 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2143 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2144 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2145 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2146 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2147 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2148 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002149 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002150 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2151 default:
2152 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2153 }
2154
2155 /* fill fake args. */
2156 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002157 args[0].data.str.area = strdup(fn);
2158 args[0].data.str.data = strlen(fn);
2159 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002160 args[1].type = ARGT_STOP;
2161
2162 /* load the map. */
2163 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002164 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002165 * free the err variable.
2166 */
2167 luaL_where(L, 1);
2168 lua_pushfstring(L, "'new': %s.", err);
2169 lua_concat(L, 2);
2170 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002171 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002172 WILL_LJMP(lua_error(L));
2173 }
2174
2175 /* create the lua object. */
2176 lua_newtable(L);
2177 lua_pushlightuserdata(L, args[0].data.map);
2178 lua_rawseti(L, -2, 0);
2179
2180 /* Pop a class Map metatable and affect it to the userdata. */
2181 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2182 lua_setmetatable(L, -2);
2183
2184
2185 return 1;
2186}
2187
2188__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2189{
2190 struct map_descriptor *desc;
2191 struct pattern *pat;
2192 struct sample smp;
2193
2194 MAY_LJMP(check_args(L, 2, "lookup"));
2195 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002196 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002197 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002198 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002199 }
2200 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002201 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002202 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002203 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 +01002204 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002205 }
2206
2207 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002208 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002209 if (str)
2210 lua_pushstring(L, "");
2211 else
2212 lua_pushnil(L);
2213 return 1;
2214 }
2215
2216 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002217 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002218 return 1;
2219}
2220
2221__LJMP static int hlua_map_lookup(struct lua_State *L)
2222{
2223 return _hlua_map_lookup(L, 0);
2224}
2225
2226__LJMP static int hlua_map_slookup(struct lua_State *L)
2227{
2228 return _hlua_map_lookup(L, 1);
2229}
2230
2231/*
2232 *
2233 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002234 * Class Socket
2235 *
2236 *
2237 */
2238
2239__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2240{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002241 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242}
2243
2244/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002245 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246 * received.
2247 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002248static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249{
Willy Tarreau5321da92022-05-06 11:57:34 +02002250 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002251 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252
Christopher Faulet31572222023-03-31 11:13:48 +02002253 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 +02002254 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Christopher Faulet31572222023-03-31 11:13:48 +02002255 notification_wake(&ctx->wake_on_read);
2256 notification_wake(&ctx->wake_on_write);
2257 return;
2258 }
2259
Willy Tarreau5321da92022-05-06 11:57:34 +02002260 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002261 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002262 notification_wake(&ctx->wake_on_read);
2263 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002264 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002265 }
2266
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002267 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002268 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002269 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002270
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002271 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002272 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002273 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002274
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002275 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002276 * to be notified whenever the connection completes.
2277 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002278 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002279 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002280 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002281 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002282 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002283 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002284
2285 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002286 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002288 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002289 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002290 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291
2292 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002293 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002294 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002295
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002296 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002297 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002298 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002299 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002300 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301}
2302
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002303static int hlua_socket_init(struct appctx *appctx)
2304{
Christopher Fauletcb068552023-09-27 17:34:24 +02002305 struct hlua_csk_ctx *csk_ctx = appctx->svcctx;
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002306 struct stream *s;
2307
2308 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2309 goto error;
2310
2311 s = appctx_strm(appctx);
2312
Willy Tarreau4596fe22022-05-17 19:07:51 +02002313 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002314 * and retrieve data from the server. The connection is initialized
2315 * with the "struct server".
2316 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002317 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002318
2319 /* Force destination server. */
2320 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2321 s->target = &socket_tcp->obj_type;
2322
Christopher Fauletcb068552023-09-27 17:34:24 +02002323 if (csk_ctx->timeout) {
2324 s->sess->fe->timeout.connect = csk_ctx->timeout;
2325 s->scf->ioto = csk_ctx->timeout;
2326 s->scb->ioto = csk_ctx->timeout;
2327 }
2328
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002329 return 0;
2330
2331 error:
2332 return -1;
2333}
2334
Willy Tarreau87b09662015-04-03 00:22:06 +02002335/* This function is called when the "struct stream" is destroyed.
2336 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337 * Wake all the pending signals.
2338 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002339static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340{
Willy Tarreau5321da92022-05-06 11:57:34 +02002341 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002342 struct xref *peer;
2343
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002344 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002345 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002346 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002347 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348
2349 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002350 notification_wake(&ctx->wake_on_read);
2351 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352}
2353
2354/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002355 * uses this object. If the stream does not exists, just quit.
2356 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 * pending signal can rest in the read and write lists. destroy
2358 * it.
2359 */
2360__LJMP static int hlua_socket_gc(lua_State *L)
2361{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002362 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002363 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002364 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002366 MAY_LJMP(check_args(L, 1, "__gc"));
2367
2368 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002369 peer = xref_get_peer_and_lock(&socket->xref);
2370 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002372
2373 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002375 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002376 ctx->die = 1;
2377 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002379 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002380 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381 return 0;
2382}
2383
2384/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002385 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386 */
sada05ed3302018-05-11 11:48:18 -07002387__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002389 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002390 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002391 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002392 struct hlua *hlua;
2393
2394 /* Get hlua struct, or NULL if we execute from main lua state */
2395 hlua = hlua_gethlua(L);
2396 if (!hlua)
2397 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002398
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002399 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002400
2401 /* Check if we run on the same thread than the xreator thread.
2402 * We cannot access to the socket if the thread is different.
2403 */
2404 if (socket->tid != tid)
2405 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2406
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002407 peer = xref_get_peer_and_lock(&socket->xref);
2408 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002410
2411 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002412 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002414 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002415 ctx->die = 1;
2416 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002418 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002419 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420 return 0;
2421}
2422
sada05ed3302018-05-11 11:48:18 -07002423/* The close function calls close_helper.
2424 */
2425__LJMP static int hlua_socket_close(lua_State *L)
2426{
2427 MAY_LJMP(check_args(L, 1, "close"));
2428 return hlua_socket_close_helper(L);
2429}
2430
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431/* This Lua function assumes that the stack contain three parameters.
2432 * 1 - USERDATA containing a struct socket
2433 * 2 - INTEGER with values of the macro defined below
2434 * If the integer is -1, we must read at most one line.
2435 * If the integer is -2, we ust read all the data until the
2436 * end of the stream.
2437 * If the integer is positive value, we must read a number of
2438 * bytes corresponding to this value.
2439 */
2440#define HLSR_READ_LINE (-1)
2441#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002442__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443{
2444 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2445 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002446 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002447 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002448 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002449 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002450 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002451 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002452 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002453 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002454 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002455 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002456 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002457 struct stream *s;
2458 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002459 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002460
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002461 /* Get hlua struct, or NULL if we execute from main lua state */
2462 hlua = hlua_gethlua(L);
2463
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002464 /* Check if this lua stack is schedulable. */
2465 if (!hlua || !hlua->task)
2466 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2467 "'frontend', 'backend' or 'task'"));
2468
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002469 /* Check if we run on the same thread than the xreator thread.
2470 * We cannot access to the socket if the thread is different.
2471 */
2472 if (socket->tid != tid)
2473 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2474
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002475 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002476 peer = xref_get_peer_and_lock(&socket->xref);
2477 if (!peer)
2478 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002479
2480 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
Christopher Faulet714476c2023-09-27 17:22:41 +02002481 if (!csk_ctx->connected)
2482 goto connection_closed;
2483
Willy Tarreau5321da92022-05-06 11:57:34 +02002484 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002485 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002487 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002488 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002489 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002490 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002491 if (nblk < 0) /* Connection close. */
2492 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002493 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002494 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002495
2496 /* remove final \r\n. */
2497 if (nblk == 1) {
2498 if (blk1[len1-1] == '\n') {
2499 len1--;
2500 skip_at_end++;
2501 if (blk1[len1-1] == '\r') {
2502 len1--;
2503 skip_at_end++;
2504 }
2505 }
2506 }
2507 else {
2508 if (blk2[len2-1] == '\n') {
2509 len2--;
2510 skip_at_end++;
2511 if (blk2[len2-1] == '\r') {
2512 len2--;
2513 skip_at_end++;
2514 }
2515 }
2516 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002517 }
2518
2519 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002520 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002521 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522 if (nblk < 0) /* Connection close. */
2523 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002524 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 goto connection_empty;
2526 }
2527
2528 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002529 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002530 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002531 if (nblk < 0) /* Connection close. */
2532 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002533 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002534 goto connection_empty;
2535
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002536 missing_bytes = wanted - socket->b.n;
2537 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002538 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002539 len1 = missing_bytes;
2540 } if (nblk == 2 && len1 + len2 > missing_bytes)
2541 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542 }
2543
2544 len = len1;
2545
2546 luaL_addlstring(&socket->b, blk1, len1);
2547 if (nblk == 2) {
2548 len += len2;
2549 luaL_addlstring(&socket->b, blk2, len2);
2550 }
2551
2552 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002553 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002554
2555 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002556 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002557
2558 /* If the pattern reclaim to read all the data
2559 * in the connection, got out.
2560 */
2561 if (wanted == HLSR_READ_ALL)
2562 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002563 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002564 goto connection_empty;
2565
2566 /* Return result. */
2567 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002568 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002569 return 1;
2570
2571connection_closed:
2572
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002573 xref_unlock(&socket->xref, peer);
2574
2575no_peer:
2576
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002577 /* If the buffer containds data. */
2578 if (socket->b.n > 0) {
2579 luaL_pushresult(&socket->b);
2580 return 1;
2581 }
2582 lua_pushnil(L);
2583 lua_pushstring(L, "connection closed.");
2584 return 2;
2585
2586connection_empty:
2587
Willy Tarreau5321da92022-05-06 11:57:34 +02002588 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002589 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002590 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002591 }
2592 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002593 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594 return 0;
2595}
2596
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002597/* This Lua function gets two parameters. The first one can be string
2598 * or a number. If the string is "*l", the user requires one line. If
2599 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002600 * If the value is a number, the user require a number of bytes equal
2601 * to the value. The default value is "*l" (a line).
2602 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002603 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002604 * integer takes this values:
2605 * -1 : read a line
2606 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002607 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002608 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002609 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610 * concatenated with the read data.
2611 */
2612__LJMP static int hlua_socket_receive(struct lua_State *L)
2613{
2614 int wanted = HLSR_READ_LINE;
2615 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002616 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002617 char *error;
2618 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002619 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620
2621 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2622 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2623
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002624 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002625
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002626 /* Check if we run on the same thread than the xreator thread.
2627 * We cannot access to the socket if the thread is different.
2628 */
2629 if (socket->tid != tid)
2630 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2631
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 /* check for pattern. */
2633 if (lua_gettop(L) >= 2) {
2634 type = lua_type(L, 2);
2635 if (type == LUA_TSTRING) {
2636 pattern = lua_tostring(L, 2);
2637 if (strcmp(pattern, "*a") == 0)
2638 wanted = HLSR_READ_ALL;
2639 else if (strcmp(pattern, "*l") == 0)
2640 wanted = HLSR_READ_LINE;
2641 else {
2642 wanted = strtoll(pattern, &error, 10);
2643 if (*error != '\0')
2644 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2645 }
2646 }
2647 else if (type == LUA_TNUMBER) {
2648 wanted = lua_tointeger(L, 2);
2649 if (wanted < 0)
2650 WILL_LJMP(luaL_error(L, "Unsupported size."));
2651 }
2652 }
2653
2654 /* Set pattern. */
2655 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002656
2657 /* Check if we would replace the top by itself. */
2658 if (lua_gettop(L) != 2)
2659 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002660
Christopher Fauletc31b2002021-05-03 10:11:13 +02002661 /* Save index of the top of the stack because since buffers are used, it
2662 * may change
2663 */
2664 lastarg = lua_gettop(L);
2665
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002666 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 luaL_buffinit(L, &socket->b);
2668
2669 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002670 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002671 if (lua_type(L, 3) != LUA_TSTRING)
2672 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2673 pattern = lua_tolstring(L, 3, &len);
2674 luaL_addlstring(&socket->b, pattern, len);
2675 }
2676
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002677 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002678}
2679
2680/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002681 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002683static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684{
2685 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002686 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002687 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002688 struct appctx *appctx;
2689 size_t buf_len;
2690 const char *buf;
2691 int len;
2692 int send_len;
2693 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002694 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002695 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002696 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002697
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002698 /* Get hlua struct, or NULL if we execute from main lua state */
2699 hlua = hlua_gethlua(L);
2700
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002701 /* Check if this lua stack is schedulable. */
2702 if (!hlua || !hlua->task)
2703 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2704 "'frontend', 'backend' or 'task'"));
2705
2706 /* Get object */
2707 socket = MAY_LJMP(hlua_checksocket(L, 1));
2708 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002709 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002710
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002711 /* Check if we run on the same thread than the xreator thread.
2712 * We cannot access to the socket if the thread is different.
2713 */
2714 if (socket->tid != tid)
2715 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2716
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002717 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002718 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002719 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002720 lua_pushinteger(L, -1);
2721 return 1;
2722 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002723
2724 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
Christopher Faulet714476c2023-09-27 17:22:41 +02002725 if (!csk_ctx->connected) {
2726 xref_unlock(&socket->xref, peer);
2727 lua_pushinteger(L, -1);
2728 return 1;
2729 }
2730
Willy Tarreau5321da92022-05-06 11:57:34 +02002731 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002732 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002733 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002734
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002735 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002736 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002737 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002738 lua_pushinteger(L, -1);
2739 return 1;
2740 }
2741
2742 /* Update the input buffer data. */
2743 buf += sent;
2744 send_len = buf_len - sent;
2745
2746 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002747 if (sent >= buf_len) {
2748 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002749 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002750 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002751
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002752 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002753 * the request buffer if its not required.
2754 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002755 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002756 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002757 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002758 }
2759
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002760 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002761 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002762 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002763 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002764 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002765
2766 /* send data */
2767 if (len < send_len)
2768 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002769 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002770
2771 /* "Not enough space" (-1), "Buffer too little to contain
2772 * the data" (-2) are not expected because the available length
2773 * is tested.
2774 * Other unknown error are also not expected.
2775 */
2776 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002777 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002778 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002779
sada05ed3302018-05-11 11:48:18 -07002780 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002781 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002782 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002783 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002784 return 1;
2785 }
2786
2787 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002788 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002789
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002790 /* Update length sent. */
2791 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002792 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793
2794 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002795 if (sent + len >= buf_len) {
2796 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002797 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002798 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002799
2800hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002801 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002802 xref_unlock(&socket->xref, peer);
2803 WILL_LJMP(luaL_error(L, "out of memory"));
2804 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002805 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002806 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002807 return 0;
2808}
2809
2810/* This function initiate the send of data. It just check the input
2811 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002812 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813 * "hlua_socket_write_yield" that can yield.
2814 *
2815 * The Lua function gets between 3 and 4 parameters. The first one is
2816 * the associated object. The second is a string buffer. The third is
2817 * a facultative integer that represents where is the buffer position
2818 * of the start of the data that can send. The first byte is the
2819 * position "1". The default value is "1". The fourth argument is a
2820 * facultative integer that represents where is the buffer position
2821 * of the end of the data that can send. The default is the last byte.
2822 */
2823static int hlua_socket_send(struct lua_State *L)
2824{
2825 int i;
2826 int j;
2827 const char *buf;
2828 size_t buf_len;
2829
2830 /* Check number of arguments. */
2831 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2832 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2833
2834 /* Get the string. */
2835 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2836
2837 /* Get and check j. */
2838 if (lua_gettop(L) == 4) {
2839 j = MAY_LJMP(luaL_checkinteger(L, 4));
2840 if (j < 0)
2841 j = buf_len + j + 1;
2842 if (j > buf_len)
2843 j = buf_len + 1;
2844 lua_pop(L, 1);
2845 }
2846 else
2847 j = buf_len;
2848
2849 /* Get and check i. */
2850 if (lua_gettop(L) == 3) {
2851 i = MAY_LJMP(luaL_checkinteger(L, 3));
2852 if (i < 0)
2853 i = buf_len + i + 1;
2854 if (i > buf_len)
2855 i = buf_len + 1;
2856 lua_pop(L, 1);
2857 } else
2858 i = 1;
2859
2860 /* Check bth i and j. */
2861 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002862 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002863 return 1;
2864 }
2865 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002866 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002867 return 1;
2868 }
2869 if (i == 0)
2870 i = 1;
2871 if (j == 0)
2872 j = 1;
2873
2874 /* Pop the string. */
2875 lua_pop(L, 1);
2876
2877 /* Update the buffer length. */
2878 buf += i - 1;
2879 buf_len = j - i + 1;
2880 lua_pushlstring(L, buf, buf_len);
2881
2882 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002883 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002884
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002885 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002886}
2887
Willy Tarreau22b0a682015-06-17 19:43:49 +02002888#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002889__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002890{
2891 static char buffer[SOCKET_INFO_MAX_LEN];
2892 int ret;
2893 int len;
2894 char *p;
2895
2896 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2897 if (ret <= 0) {
2898 lua_pushnil(L);
2899 return 1;
2900 }
2901
2902 if (ret == AF_UNIX) {
2903 lua_pushstring(L, buffer+1);
2904 return 1;
2905 }
2906 else if (ret == AF_INET6) {
2907 buffer[0] = '[';
2908 len = strlen(buffer);
2909 buffer[len] = ']';
2910 len++;
2911 buffer[len] = ':';
2912 len++;
2913 p = buffer;
2914 }
2915 else if (ret == AF_INET) {
2916 p = buffer + 1;
2917 len = strlen(p);
2918 p[len] = ':';
2919 len++;
2920 }
2921 else {
2922 lua_pushnil(L);
2923 return 1;
2924 }
2925
2926 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2927 lua_pushnil(L);
2928 return 1;
2929 }
2930
2931 lua_pushstring(L, p);
2932 return 1;
2933}
2934
2935/* Returns information about the peer of the connection. */
2936__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2937{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002938 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002939 struct xref *peer;
Christopher Faulet714476c2023-09-27 17:22:41 +02002940 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002941 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002942 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002943 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002944 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002945
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002946 MAY_LJMP(check_args(L, 1, "getpeername"));
2947
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002948 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002949
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002950 /* Check if we run on the same thread than the xreator thread.
2951 * We cannot access to the socket if the thread is different.
2952 */
2953 if (socket->tid != tid)
2954 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2955
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002956 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002957 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002958 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002959 lua_pushnil(L);
2960 return 1;
2961 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002962
Christopher Faulet714476c2023-09-27 17:22:41 +02002963 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2964 if (!csk_ctx->connected) {
2965 xref_unlock(&socket->xref, peer);
2966 lua_pushnil(L);
2967 return 1;
2968 }
2969
2970 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002971 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002972 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002973 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002974 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002975 lua_pushnil(L);
2976 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977 }
2978
Christopher Faulet16f16af2021-10-27 09:34:56 +02002979 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002980 xref_unlock(&socket->xref, peer);
2981 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982}
2983
2984/* Returns information about my connection side. */
2985static int hlua_socket_getsockname(struct lua_State *L)
2986{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002987 struct hlua_socket *socket;
2988 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002989 struct appctx *appctx;
2990 struct xref *peer;
Christopher Faulet714476c2023-09-27 17:22:41 +02002991 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002992 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002993 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002994
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995 MAY_LJMP(check_args(L, 1, "getsockname"));
2996
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002997 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002999 /* Check if we run on the same thread than the xreator thread.
3000 * We cannot access to the socket if the thread is different.
3001 */
3002 if (socket->tid != tid)
3003 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3004
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003005 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003006 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003007 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003008 lua_pushnil(L);
3009 return 1;
3010 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003011
Christopher Faulet714476c2023-09-27 17:22:41 +02003012 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3013 if (!csk_ctx->connected) {
3014 xref_unlock(&socket->xref, peer);
3015 lua_pushnil(L);
3016 return 1;
3017 }
3018
3019 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003020 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021
Willy Tarreaufd9417b2022-05-18 16:23:22 +02003022 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02003023 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003024 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003025 lua_pushnil(L);
3026 return 1;
3027 }
3028
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003029 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003030 xref_unlock(&socket->xref, peer);
3031 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003032}
3033
3034/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02003035static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003036 .obj_type = OBJ_TYPE_APPLET,
3037 .name = "<LUA_TCP>",
3038 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003039 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003040 .release = hlua_socket_release,
3041};
3042
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003043__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003044{
3045 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003046 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003047 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02003048 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003049 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003050 struct stream *s;
3051
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003052 /* Get hlua struct, or NULL if we execute from main lua state */
3053 hlua = hlua_gethlua(L);
3054 if (!hlua)
3055 return 0;
3056
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003057 /* Check if we run on the same thread than the xreator thread.
3058 * We cannot access to the socket if the thread is different.
3059 */
3060 if (socket->tid != tid)
3061 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3062
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003063 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003064 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003065 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003066 lua_pushnil(L);
3067 lua_pushstring(L, "Can't connect");
3068 return 2;
3069 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003070
3071 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3072 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003073 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003074
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003075 /* Check if we run on the same thread than the xreator thread.
3076 * We cannot access to the socket if the thread is different.
3077 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003078 if (socket->tid != tid) {
3079 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003080 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003081 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003082
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003083 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003084 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003085 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003086 lua_pushnil(L);
3087 lua_pushstring(L, "Can't connect");
3088 return 2;
3089 }
3090
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02003091 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003092
3093 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003094 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003095 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003096 lua_pushinteger(L, 1);
3097 return 1;
3098 }
3099
Willy Tarreau5321da92022-05-06 11:57:34 +02003100 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003101 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003102 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003103 }
3104 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003105 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003106 return 0;
3107}
3108
3109/* This function fail or initite the connection. */
3110__LJMP static int hlua_socket_connect(struct lua_State *L)
3111{
3112 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003113 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003114 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003115 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003116 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003117 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003118 int low, high;
3119 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003120 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003121 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003122 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003123
Christopher Faulet6db178d2023-09-27 17:42:38 +02003124 /* Get hlua struct, or NULL if we execute from main lua state */
3125 hlua = hlua_gethlua(L);
3126 if (!hlua)
3127 return 0;
3128
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003129 if (lua_gettop(L) < 2)
3130 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003131
3132 /* Get args. */
3133 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003134
3135 /* Check if we run on the same thread than the xreator thread.
3136 * We cannot access to the socket if the thread is different.
3137 */
3138 if (socket->tid != tid)
3139 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3140
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003141 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003142 if (lua_gettop(L) >= 3) {
3143 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003144 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003145
Tim Duesterhus6edab862018-01-06 19:04:45 +01003146 /* Force the ip to end with a colon, to support IPv6 addresses
3147 * that are not enclosed within square brackets.
3148 */
3149 if (port > 0) {
3150 luaL_buffinit(L, &b);
3151 luaL_addstring(&b, ip);
3152 luaL_addchar(&b, ':');
3153 luaL_pushresult(&b);
3154 ip = lua_tolstring(L, lua_gettop(L), NULL);
3155 }
3156 }
3157
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003158 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003159 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003160 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003161 lua_pushnil(L);
3162 return 1;
3163 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003164
Christopher Faulet26786572023-09-27 17:39:44 +02003165 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3166 if (!csk_ctx->srv)
3167 csk_ctx->srv = socket_tcp;
3168
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003169 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003170 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 +02003171 if (!addr) {
3172 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003173 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003174 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003175
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003176 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003177 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003178 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003179 if (port == -1) {
3180 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003181 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003182 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003183 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3184 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003185 if (port == -1) {
3186 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003187 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003188 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003189 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003190 }
3191 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003192
Willy Tarreau5321da92022-05-06 11:57:34 +02003193 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3194 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003195 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003196 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003197
Willy Tarreau3e7be362022-05-27 10:35:27 +02003198 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003199 xref_unlock(&socket->xref, peer);
3200 WILL_LJMP(luaL_error(L, "connect: internal error"));
3201 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003202
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003203 /* inform the stream that we want to be notified whenever the
3204 * connection completes.
3205 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003206 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003207 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003208 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003209
Willy Tarreauf31af932020-01-14 09:59:38 +01003210 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003211
Willy Tarreau5321da92022-05-06 11:57:34 +02003212 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003213 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003214 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003215 }
3216 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003217
3218 task_wakeup(s->task, TASK_WOKEN_INIT);
3219 /* Return yield waiting for connection. */
3220
Willy Tarreau9635e032018-10-16 17:52:55 +02003221 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003222
3223 return 0;
3224}
3225
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003226#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003227__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3228{
3229 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003230 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003231 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003232
3233 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3234 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003235
3236 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003237 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003238 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003239 lua_pushnil(L);
3240 return 1;
3241 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003242
Willy Tarreau0698c802022-05-11 14:09:57 +02003243 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Christopher Faulet26786572023-09-27 17:39:44 +02003244 container_of(peer, struct hlua_csk_ctx, xref)->srv = socket_ssl;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003245
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003246 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003247 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003248 return MAY_LJMP(hlua_socket_connect(L));
3249}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003250#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003251
3252__LJMP static int hlua_socket_setoption(struct lua_State *L)
3253{
3254 return 0;
3255}
3256
3257__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3258{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003259 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003260 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003261 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003262 struct xref *peer;
Christopher Fauletcb068552023-09-27 17:34:24 +02003263 struct hlua_csk_ctx *csk_ctx;
3264 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003265 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003266
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003267 MAY_LJMP(check_args(L, 2, "settimeout"));
3268
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003269 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003270
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003271 /* convert the timeout to millis */
3272 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003273
Thierry Fournier17a921b2018-03-08 09:59:02 +01003274 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003275 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003276 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3277
Mark Lakes56cc1252018-03-27 09:48:06 +02003278 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003279 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003280
3281 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003282 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003283 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003284
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003285 /* Check if we run on the same thread than the xreator thread.
3286 * We cannot access to the socket if the thread is different.
3287 */
3288 if (socket->tid != tid)
3289 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3290
Mark Lakes56cc1252018-03-27 09:48:06 +02003291 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003292 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003293 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003294 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3295 WILL_LJMP(lua_error(L));
3296 return 0;
3297 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003298
Christopher Fauletcb068552023-09-27 17:34:24 +02003299 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3300 csk_ctx->timeout = tmout;
3301
3302 appctx = csk_ctx->appctx;
3303 if (!appctx_sc(appctx))
3304 goto end;
3305
3306 s = appctx_strm(csk_ctx->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003307
Cyril Bonté7bb63452018-08-17 23:51:02 +02003308 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003309 s->scf->ioto = tmout;
3310 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003311
Christopher Fauletcb068552023-09-27 17:34:24 +02003312 s->task->expire = (tick_is_expired(s->task->expire, now_ms) ? 0 : s->task->expire);
3313 s->task->expire = tick_first(s->task->expire, tick_add_ifset(now_ms, tmout));
Cyril Bonté7bb63452018-08-17 23:51:02 +02003314 task_queue(s->task);
3315
Christopher Fauletcb068552023-09-27 17:34:24 +02003316 end:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003317 xref_unlock(&socket->xref, peer);
Thierry Fourniere9636f12018-03-08 09:54:32 +01003318 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003319 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003320}
3321
3322__LJMP static int hlua_socket_new(lua_State *L)
3323{
3324 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003325 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003326 struct appctx *appctx;
3327
3328 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003329 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003330 hlua_pusherror(L, "socket: full stack");
3331 goto out_fail_conf;
3332 }
3333
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003334 /* Create the object: obj[0] = userdata. */
3335 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003336 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003337 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003338 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003339 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003340
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003341 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003342 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003343 hlua_pusherror(L, "socket: uninitialized pools.");
3344 goto out_fail_conf;
3345 }
3346
Willy Tarreau87b09662015-04-03 00:22:06 +02003347 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003348 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3349 lua_setmetatable(L, -2);
3350
Willy Tarreaud420a972015-04-06 00:39:18 +02003351 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003352 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003353 if (!appctx) {
3354 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003355 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003356 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003357 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3358 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003359 ctx->die = 0;
Christopher Faulet26786572023-09-27 17:39:44 +02003360 ctx->srv = NULL;
Christopher Fauletcb068552023-09-27 17:34:24 +02003361 ctx->timeout = 0;
Christopher Faulet75d1bfb2023-09-27 17:17:48 +02003362 ctx->appctx = appctx;
Willy Tarreau5321da92022-05-06 11:57:34 +02003363 LIST_INIT(&ctx->wake_on_write);
3364 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003365
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003366 if (appctx_init(appctx) == -1) {
3367 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003368 goto out_fail_appctx;
3369 }
3370
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003371 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003372 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003373 return 1;
3374
Christopher Faulet13a35e52021-12-20 15:34:16 +01003375 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003376 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003377 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003378 WILL_LJMP(lua_error(L));
3379 return 0;
3380}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003381
3382/*
3383 *
3384 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003385 * Class Channel
3386 *
3387 *
3388 */
3389
3390/* Returns the struct hlua_channel join to the class channel in the
3391 * stack entry "ud" or throws an argument error.
3392 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003393__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003394{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003395 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003396}
3397
Willy Tarreau47860ed2015-03-10 14:07:50 +01003398/* Pushes the channel onto the top of the stack. If the stask does not have a
3399 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003400 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003401static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003402{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003403 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003404 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003405 return 0;
3406
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003407 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003408 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003409 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003410
3411 /* Pop a class sesison metatable and affect it to the userdata. */
3412 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3413 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003414 return 1;
3415}
3416
Christopher Faulet9f55a502020-02-25 15:21:02 +01003417/* Helper function returning a filter attached to a channel at the position <ud>
3418 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003419 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003420 * initialized.
3421 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003422static 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 +01003423{
3424 struct filter *filter = NULL;
3425
3426 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3427 struct hlua_flt_ctx *flt_ctx;
3428
3429 filter = lua_touserdata (L, -1);
3430 flt_ctx = filter->ctx;
3431 if (hlua_filter_from_payload(filter)) {
3432 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3433 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3434 }
3435 }
3436
3437 lua_pop(L, 1);
3438 return filter;
3439}
3440
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003441/* Copies <len> bytes of data present in the channel's buffer, starting at the
3442* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003443* responsibility to ensure <len> and <offset> are valid. It always return the
3444* length of the built string. <len> may be 0, in this case, an empty string is
3445* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003446*/
3447static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003448{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003449 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003450 luaL_Buffer b;
3451
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003452 block1 = len;
3453 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3454 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3455 block2 = len - block1;
3456
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003457 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003458 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3459 if (block2)
3460 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003461 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003462 return len;
3463}
3464
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003465/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3466 * function returns -1 if data cannot be copied. Otherwise, it returns the
3467 * number of bytes copied.
3468 */
3469static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3470{
3471 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003472
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003473 /* Nothing to do, just return */
3474 if (unlikely(istlen(str) == 0))
3475 goto end;
3476
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003477 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003478 ret = -1;
3479 goto end;
3480 }
3481 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3482
3483 end:
3484 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003485}
3486
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003487/* Removes <len> bytes of data at the absolute position <offset>.
3488 */
3489static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3490{
3491 size_t end = offset + len;
3492
3493 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3494 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3495 b_data(&chn->buf) - end, -len);
3496 b_sub(&chn->buf, len);
3497}
3498
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003499/* Copies input data in the channel's buffer. It is possible to set a specific
3500 * offset (0 by default) and a length (all remaining input data starting for the
3501 * offset by default). If there is not enough input data and more data can be
3502 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003503 *
3504 * From an action, All input data are considered. For a filter, the offset and
3505 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003506 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003507__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003508{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003509 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510 struct filter *filter;
3511 size_t input, output;
3512 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003513
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003514 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003515
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003516 output = co_data(chn);
3517 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003518
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003519 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3520 if (filter && !hlua_filter_from_payload(filter))
3521 WILL_LJMP(lua_error(L));
3522
3523 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003524 if (lua_gettop(L) > 1) {
3525 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3526 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003527 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003528 offset += output;
3529 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003530 lua_pushfstring(L, "offset out of range.");
3531 WILL_LJMP(lua_error(L));
3532 }
3533 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003534 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535 if (lua_gettop(L) == 3) {
3536 len = MAY_LJMP(luaL_checkinteger(L, 3));
3537 if (!len)
3538 goto dup;
3539 if (len == -1)
3540 len = global.tune.bufsize;
3541 if (len < 0) {
3542 lua_pushfstring(L, "length out of range.");
3543 WILL_LJMP(lua_error(L));
3544 }
3545 }
3546
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003547 /* Wait for more data if possible if no length was specified and there
3548 * is no data or not enough data was received.
3549 */
3550 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003551 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3552 /* Yield waiting for more data, as requested */
3553 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3554 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003555
3556 /* Return 'nil' if there is no data and the channel can't receive more data */
3557 if (!len) {
3558 lua_pushnil(L);
3559 return -1;
3560 }
3561
3562 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003563 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003564 }
3565
3566 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003567 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003568 return 1;
3569}
3570
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571/* Copies the first line (including the trailing LF) of input data in the
3572 * channel's buffer. It is possible to set a specific offset (0 by default) and
3573 * a length (all remaining input data starting for the offset by default). If
3574 * there is not enough input data and more data can be received, the function
3575 * yields. If a length is explicitly specified, no more data are
3576 * copied. Otherwise, if no LF is found and more data can be received, this
3577 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003578 *
3579 * From an action, All input data are considered. For a filter, the offset and
3580 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 */
3582__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003583{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003584 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 struct filter *filter;
3586 size_t l, input, output;
3587 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003588
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003589 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003590 output = co_data(chn);
3591 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003593 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3594 if (filter && !hlua_filter_from_payload(filter))
3595 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003596
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003598 if (lua_gettop(L) > 1) {
3599 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3600 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003601 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 offset += output;
3603 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 lua_pushfstring(L, "offset out of range.");
3605 WILL_LJMP(lua_error(L));
3606 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003607 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003608
3609 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003610 if (lua_gettop(L) == 3) {
3611 len = MAY_LJMP(luaL_checkinteger(L, 3));
3612 if (!len)
3613 goto dup;
3614 if (len == -1)
3615 len = global.tune.bufsize;
3616 if (len < 0) {
3617 lua_pushfstring(L, "length out of range.");
3618 WILL_LJMP(lua_error(L));
3619 }
3620 }
3621
3622 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003626 len = l+1;
3627 goto dup;
3628 }
3629 }
3630
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003631 /* Wait for more data if possible if no line is found and no length was
3632 * specified or not enough data was received.
3633 */
3634 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3636 /* Yield waiting for more data */
3637 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3638 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003639
3640 /* Return 'nil' if there is no data and the channel can't receive more data */
3641 if (!len) {
3642 lua_pushnil(L);
3643 return -1;
3644 }
3645
3646 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003647 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003648 }
3649
3650 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003651 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003652 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003653}
3654
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003655/* [ DEPRECATED ]
3656 *
3657 * Duplicate all input data foud in the channel's buffer. The data are not
3658 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003659 *
3660 * From an action, All input data are considered. For a filter, the offset and
3661 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003662 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003663__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003664{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003665 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666 struct filter *filter;
3667 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003668
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003669 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003670 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003671 if (IS_HTX_STRM(chn_strm(chn))) {
3672 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3673 WILL_LJMP(lua_error(L));
3674 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003675
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003676 offset = co_data(chn);
3677 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003678
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003679 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3680 if (filter && !hlua_filter_from_payload(filter))
3681 WILL_LJMP(lua_error(L));
3682
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003683 if (!ci_data(chn) && channel_input_closed(chn)) {
3684 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003685 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003686 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003687
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003689 return 1;
3690}
3691
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003692/* [ DEPRECATED ]
3693 *
3694 * Get all input data foud in the channel's buffer. The data are removed from
3695 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3696 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003697 *
3698 * From an action, All input data are considered. For a filter, the offset and
3699 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003701__LJMP static int hlua_channel_get(lua_State *L)
3702{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003703 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704 struct filter *filter;
3705 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003707
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003708 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003709 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3710 if (IS_HTX_STRM(chn_strm(chn))) {
3711 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3712 WILL_LJMP(lua_error(L));
3713 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003714
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003715 offset = co_data(chn);
3716 len = ci_data(chn);
3717
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003718 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3719 if (filter && !hlua_filter_from_payload(filter))
3720 WILL_LJMP(lua_error(L));
3721
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003722 if (!ci_data(chn) && channel_input_closed(chn)) {
3723 lua_pushnil(L);
3724 return 1;
3725 }
3726
3727 ret = _hlua_channel_dup(chn, L, offset, len);
3728 _hlua_channel_delete(chn, offset, ret);
3729 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003730}
3731
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003732/* This functions consumes and returns one line. If the channel is closed,
3733 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003734 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003735 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003736 *
3737 * From an action, All input data are considered. For a filter, the offset and
3738 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003739 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003740__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003741{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003742 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003743 struct filter *filter;
3744 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003745 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003746
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003747 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003748
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003749 offset = co_data(chn);
3750 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003751
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003752 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3753 if (filter && !hlua_filter_from_payload(filter))
3754 WILL_LJMP(lua_error(L));
3755
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003756 if (!ci_data(chn) && channel_input_closed(chn)) {
3757 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003758 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003759 }
3760
3761 for (l = 0; l < len; l++) {
3762 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3763 len = l+1;
3764 goto dup;
3765 }
3766 }
3767
3768 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3769 /* Yield waiting for more data */
3770 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3771 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003772
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003773 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003774 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003775 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003776 return 1;
3777}
3778
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003779/* [ DEPRECATED ]
3780 *
3781 * Check arguments for the function "hlua_channel_getline_yield".
3782 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003783__LJMP static int hlua_channel_getline(lua_State *L)
3784{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003785 struct channel *chn;
3786
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003787 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003788 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3789 if (IS_HTX_STRM(chn_strm(chn))) {
3790 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3791 WILL_LJMP(lua_error(L));
3792 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003793 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3794}
3795
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003796/* Retrieves a given amount of input data at the given offset. By default all
3797 * available input data are returned. The offset may be negactive to start from
3798 * the end of input data. The length may be -1 to set it to the maximum buffer
3799 * size.
3800 */
3801__LJMP static int hlua_channel_get_data(lua_State *L)
3802{
3803 struct channel *chn;
3804
3805 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3806 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3807 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3808 if (IS_HTX_STRM(chn_strm(chn))) {
3809 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3810 WILL_LJMP(lua_error(L));
3811 }
3812 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3813}
3814
3815/* Retrieves a given amount of input data at the given offset. By default all
3816 * available input data are returned. The offset may be negactive to start from
3817 * the end of input data. The length may be -1 to set it to the maximum buffer
3818 * size.
3819 */
3820__LJMP static int hlua_channel_get_line(lua_State *L)
3821{
3822 struct channel *chn;
3823
3824 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3825 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3826 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3827 if (IS_HTX_STRM(chn_strm(chn))) {
3828 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3829 WILL_LJMP(lua_error(L));
3830 }
3831 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3832}
3833
3834/* Appends a string into the input side of channel. It returns the length of the
3835 * written string, or -1 if the channel is closed or if the buffer size is too
3836 * little for the data. 0 may be returned if nothing is copied. This function
3837 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 *
3839 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003840 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003841__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003842{
Christopher Faulet23976d92021-08-06 09:59:49 +02003843 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003844 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003845 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003846 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003847 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003848
3849 MAY_LJMP(check_args(L, 2, "append"));
3850 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003851 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003852 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003853 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003854 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003855 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003856
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003857 offset = co_data(chn);
3858 len = ci_data(chn);
3859
3860 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3861 if (filter && !hlua_filter_from_payload(filter))
3862 WILL_LJMP(lua_error(L));
3863
3864 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3865 if (ret > 0 && filter) {
3866 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3867
3868 flt_update_offsets(filter, chn, ret);
3869 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3870 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003871 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003872 return 1;
3873}
3874
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003875/* Prepends a string into the input side of channel. It returns the length of the
3876 * written string, or -1 if the channel is closed or if the buffer size is too
3877 * little for the data. 0 may be returned if nothing is copied. This function
3878 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003879 *
3880 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003881 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003882__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003883{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003884 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003885 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003886 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003887 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003888 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003889
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003890 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003891 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003892 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3893 if (IS_HTX_STRM(chn_strm(chn))) {
3894 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3895 WILL_LJMP(lua_error(L));
3896 }
3897
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003898 offset = co_data(chn);
3899 len = ci_data(chn);
3900
3901 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3902 if (filter && !hlua_filter_from_payload(filter))
3903 WILL_LJMP(lua_error(L));
3904
3905 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3906 if (ret > 0 && filter) {
3907 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3908
3909 flt_update_offsets(filter, chn, ret);
3910 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3911 }
3912
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003913 lua_pushinteger(L, ret);
3914 return 1;
3915}
3916
3917/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003918 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003919 * returns the length of the written string, or -1 if the channel is closed or
3920 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003921 *
3922 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003923 */
3924__LJMP static int hlua_channel_insert_data(lua_State *L)
3925{
3926 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003928 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003929 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003930 int ret, offset;
3931
3932 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3933 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3934 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3935 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003936
3937 output = co_data(chn);
3938 input = ci_data(chn);
3939
3940 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3941 if (filter && !hlua_filter_from_payload(filter))
3942 WILL_LJMP(lua_error(L));
3943
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003944 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003945 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003946 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003947 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003948 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003949 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003950 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003951 lua_pushfstring(L, "offset out of range.");
3952 WILL_LJMP(lua_error(L));
3953 }
3954 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003955 if (IS_HTX_STRM(chn_strm(chn))) {
3956 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3957 WILL_LJMP(lua_error(L));
3958 }
3959
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3961 if (ret > 0 && filter) {
3962 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003963
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003964 flt_update_offsets(filter, chn, ret);
3965 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003966 }
3967
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003968 lua_pushinteger(L, ret);
3969 return 1;
3970}
3971/* Replaces a given amount of input data at the given offset by a string
3972 * content. By default all remaining data are removed (offset = 0 and len =
3973 * -1). It returns the length of the written string, or -1 if the channel is
3974 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003975 *
3976 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003977 */
3978__LJMP static int hlua_channel_set_data(lua_State *L)
3979{
3980 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003981 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003982 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003983 size_t sz, input, output;
3984 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003985
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003986 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3987 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3988 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3989 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003990
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003991 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003992 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003993 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003994 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003995
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003996 output = co_data(chn);
3997 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003998
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003999 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4000 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004001 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004002
4003 offset = output;
4004 if (lua_gettop(L) > 2) {
4005 offset = MAY_LJMP(luaL_checkinteger(L, 3));
4006 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004007 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004008 offset += output;
4009 if (offset < output || offset > input + output) {
4010 lua_pushfstring(L, "offset out of range.");
4011 WILL_LJMP(lua_error(L));
4012 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004013 }
4014
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004015 len = output + input - offset;
4016 if (lua_gettop(L) == 4) {
4017 len = MAY_LJMP(luaL_checkinteger(L, 4));
4018 if (!len)
4019 goto set;
4020 if (len == -1)
4021 len = output + input - offset;
4022 if (len < 0 || offset + len > output + input) {
4023 lua_pushfstring(L, "length out of range.");
4024 WILL_LJMP(lua_error(L));
4025 }
4026 }
4027
4028 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02004029 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004030 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02004031 lua_pushinteger(L, -1);
4032 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004033 _hlua_channel_delete(chn, offset, len);
4034 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
4035 if (filter) {
4036 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4037
4038 len -= (ret > 0 ? ret : 0);
4039 flt_update_offsets(filter, chn, -len);
4040 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4041 }
4042
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004043 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02004044 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004045 return 1;
4046}
4047
4048/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004049 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004050 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004051 *
4052 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004053 */
4054__LJMP static int hlua_channel_del_data(lua_State *L)
4055{
4056 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004057 struct filter *filter;
4058 size_t input, output;
4059 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004060
4061 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
4062 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
4063 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004064
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004065 if (IS_HTX_STRM(chn_strm(chn))) {
4066 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4067 WILL_LJMP(lua_error(L));
4068 }
4069
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004070 output = co_data(chn);
4071 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004072
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004073 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4074 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004075 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004076
4077 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00004078 if (lua_gettop(L) > 1) {
4079 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004080 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004081 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004082 offset += output;
4083 if (offset < output || offset > input + output) {
4084 lua_pushfstring(L, "offset out of range.");
4085 WILL_LJMP(lua_error(L));
4086 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004087 }
4088
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004089 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00004090 if (lua_gettop(L) == 3) {
4091 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004092 if (!len)
4093 goto end;
4094 if (len == -1)
4095 len = output + input - offset;
4096 if (len < 0 || offset + len > output + input) {
4097 lua_pushfstring(L, "length out of range.");
4098 WILL_LJMP(lua_error(L));
4099 }
4100 }
4101
4102 _hlua_channel_delete(chn, offset, len);
4103 if (filter) {
4104 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4105
4106 flt_update_offsets(filter, chn, -len);
4107 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4108 }
4109
4110 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004111 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02004112 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004113}
4114
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004115/* Append data in the output side of the buffer. This data is immediately
4116 * sent. The function returns the amount of data written. If the buffer
4117 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004118 * if the channel is closed.
4119 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004120__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004121{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004122 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004123 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004124 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004125 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004126 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004127 struct hlua *hlua;
4128
4129 /* Get hlua struct, or NULL if we execute from main lua state */
4130 hlua = hlua_gethlua(L);
4131 if (!hlua) {
4132 lua_pushnil(L);
4133 return 1;
4134 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004135
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004136 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4137 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4138 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004139
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004140 offset = co_data(chn);
4141 len = ci_data(chn);
4142
4143 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4144 if (filter && !hlua_filter_from_payload(filter))
4145 WILL_LJMP(lua_error(L));
4146
4147
Willy Tarreau47860ed2015-03-10 14:07:50 +01004148 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004149 lua_pushinteger(L, -1);
4150 return 1;
4151 }
4152
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004153 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004154 if (len > sz -l) {
4155 if (filter) {
4156 lua_pushinteger(L, -1);
4157 return 1;
4158 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004159 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004160 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004161
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004162 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004163 if (ret == -1) {
4164 lua_pop(L, 1);
4165 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004166 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004167 }
4168 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004169 if (filter) {
4170 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4171
4172
4173 flt_update_offsets(filter, chn, ret);
4174 FLT_OFF(filter, chn) += ret;
4175 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4176 }
4177 else
4178 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004179
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004180 l += ret;
4181 lua_pop(L, 1);
4182 lua_pushinteger(L, l);
4183 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004184
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004185 if (l < sz) {
4186 /* Yield only if the channel's output is not empty.
4187 * Otherwise it means we cannot add more data. */
4188 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004189 return 1;
4190
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004191 /* If we are waiting for space in the response buffer, we
4192 * must set the flag WAKERESWR. This flag required the task
4193 * wake up if any activity is detected on the response buffer.
4194 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004195 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004196 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004197 else
4198 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004199 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004200 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004201
4202 return 1;
4203}
4204
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004205/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004206 * yield the LUA process, and resume it without checking the
4207 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004208 *
4209 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004210 */
4211__LJMP static int hlua_channel_send(lua_State *L)
4212{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004213 struct channel *chn;
4214
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004215 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004216 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4217 if (IS_HTX_STRM(chn_strm(chn))) {
4218 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4219 WILL_LJMP(lua_error(L));
4220 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004221 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004222 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004223}
4224
4225/* This function forward and amount of butes. The data pass from
4226 * the input side of the buffer to the output side, and can be
4227 * forwarded. This function never fails.
4228 *
4229 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004230 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004231 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004232__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004233{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004234 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004235 struct filter *filter;
4236 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004237 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004238 struct hlua *hlua;
4239
4240 /* Get hlua struct, or NULL if we execute from main lua state */
4241 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004242 if (!hlua) {
4243 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004244 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004245 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004246
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004247 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004248 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004249 l = MAY_LJMP(luaL_checkinteger(L, -1));
4250
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004251 offset = co_data(chn);
4252 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004253
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004254 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4255 if (filter && !hlua_filter_from_payload(filter))
4256 WILL_LJMP(lua_error(L));
4257
4258 max = fwd - l;
4259 if (max > len)
4260 max = len;
4261
4262 if (filter) {
4263 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4264
4265 FLT_OFF(filter, chn) += max;
4266 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4267 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4268 }
4269 else
4270 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004271
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004272 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004273 lua_pop(L, 1);
4274 lua_pushinteger(L, l);
4275
4276 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004277 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004278 /* The the input channel or the output channel are closed, we
4279 * must return the amount of data forwarded.
4280 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004281 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004282 return 1;
4283
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004284 /* If we are waiting for space data in the response buffer, we
4285 * must set the flag WAKERESWR. This flag required the task
4286 * wake up if any activity is detected on the response buffer.
4287 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004288 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004289 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004290 else
4291 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004292
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004293 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004294 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004295 }
4296
4297 return 1;
4298}
4299
4300/* Just check the input and prepare the stack for the previous
4301 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004302 *
4303 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004304 */
4305__LJMP static int hlua_channel_forward(lua_State *L)
4306{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004307 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004308
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004309 MAY_LJMP(check_args(L, 2, "forward"));
4310 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4311 if (IS_HTX_STRM(chn_strm(chn))) {
4312 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4313 WILL_LJMP(lua_error(L));
4314 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004315 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004316 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004317}
4318
4319/* Just returns the number of bytes available in the input
4320 * side of the buffer. This function never fails.
4321 */
4322__LJMP static int hlua_channel_get_in_len(lua_State *L)
4323{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004324 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004325 struct filter *filter;
4326 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004327
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004328 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004329 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004330
4331 output = co_data(chn);
4332 input = ci_data(chn);
4333 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4334 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4335 lua_pushinteger(L, input);
4336 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004337 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004338
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004339 lua_pushinteger(L, htx->data - co_data(chn));
4340 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004341 return 1;
4342}
4343
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004344/* Returns true if the channel is full. */
4345__LJMP static int hlua_channel_is_full(lua_State *L)
4346{
4347 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004348
4349 MAY_LJMP(check_args(L, 1, "is_full"));
4350 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004351 /* ignore the reserve, we are not on a producer side (ie in an
4352 * applet).
4353 */
4354 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004355 return 1;
4356}
4357
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004358/* Returns true if the channel may still receive data. */
4359__LJMP static int hlua_channel_may_recv(lua_State *L)
4360{
4361 struct channel *chn;
4362
4363 MAY_LJMP(check_args(L, 1, "may_recv"));
4364 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4365 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4366 return 1;
4367}
4368
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004369/* Returns true if the channel is the response channel. */
4370__LJMP static int hlua_channel_is_resp(lua_State *L)
4371{
4372 struct channel *chn;
4373
4374 MAY_LJMP(check_args(L, 1, "is_resp"));
4375 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4376
4377 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4378 return 1;
4379}
4380
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004381/* Just returns the number of bytes available in the output
4382 * side of the buffer. This function never fails.
4383 */
4384__LJMP static int hlua_channel_get_out_len(lua_State *L)
4385{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004386 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004387 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004388
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004389 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004390 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004391
4392 output = co_data(chn);
4393 input = ci_data(chn);
4394 hlua_channel_filter(L, 1, chn, &output, &input);
4395
4396 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004397 return 1;
4398}
4399
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004400/*
4401 *
4402 *
4403 * Class Fetches
4404 *
4405 *
4406 */
4407
4408/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004409 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004410 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004411__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004412{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004413 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004414}
4415
4416/* This function creates and push in the stack a fetch object according
4417 * with a current TXN.
4418 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004419static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004420{
Willy Tarreau7073c472015-04-06 11:15:40 +02004421 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004422
4423 /* Check stack size. */
4424 if (!lua_checkstack(L, 3))
4425 return 0;
4426
4427 /* Create the object: obj[0] = userdata.
4428 * Note that the base of the Fetches object is the
4429 * transaction object.
4430 */
4431 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004432 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004433 lua_rawseti(L, -2, 0);
4434
Willy Tarreau7073c472015-04-06 11:15:40 +02004435 hsmp->s = txn->s;
4436 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004437 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004438 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004439
4440 /* Pop a class sesison metatable and affect it to the userdata. */
4441 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4442 lua_setmetatable(L, -2);
4443
4444 return 1;
4445}
4446
4447/* This function is an LUA binding. It is called with each sample-fetch.
4448 * It uses closure argument to store the associated sample-fetch. It
4449 * returns only one argument or throws an error. An error is thrown
4450 * only if an error is encountered during the argument parsing. If
4451 * the "sample-fetch" function fails, nil is returned.
4452 */
4453__LJMP static int hlua_run_sample_fetch(lua_State *L)
4454{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004455 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004456 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004457 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004458 int i;
4459 struct sample smp;
4460
4461 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004462 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004463
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004464 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004465 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004466
Thierry FOURNIERca988662015-12-20 18:43:03 +01004467 /* Check execution authorization. */
4468 if (f->use & SMP_USE_HTTP_ANY &&
4469 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4470 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4471 "is not available in Lua services", f->kw);
4472 WILL_LJMP(lua_error(L));
4473 }
4474
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004475 /* Get extra arguments. */
4476 for (i = 0; i < lua_gettop(L) - 1; i++) {
4477 if (i >= ARGM_NBARGS)
4478 break;
4479 hlua_lua2arg(L, i + 2, &args[i]);
4480 }
4481 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004482 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004483
4484 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004485 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004486
4487 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004488 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004489 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004490 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004491 }
4492
4493 /* Initialise the sample. */
4494 memset(&smp, 0, sizeof(smp));
4495
4496 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004497 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004498 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004499 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004500 lua_pushstring(L, "");
4501 else
4502 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004503 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004504 }
4505
4506 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004507 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004508 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004509 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004510 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004511
4512 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004513 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004514 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004515
4516 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004517 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004518 WILL_LJMP(lua_error(L));
4519 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004520}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004521
4522/*
4523 *
4524 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004525 * Class Converters
4526 *
4527 *
4528 */
4529
4530/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004531 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004532 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004533__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004534{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004535 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004536}
4537
4538/* This function creates and push in the stack a Converters object
4539 * according with a current TXN.
4540 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004541static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004542{
Willy Tarreau7073c472015-04-06 11:15:40 +02004543 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004544
4545 /* Check stack size. */
4546 if (!lua_checkstack(L, 3))
4547 return 0;
4548
4549 /* Create the object: obj[0] = userdata.
4550 * Note that the base of the Converters object is the
4551 * same than the TXN object.
4552 */
4553 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004554 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004555 lua_rawseti(L, -2, 0);
4556
Willy Tarreau7073c472015-04-06 11:15:40 +02004557 hsmp->s = txn->s;
4558 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004559 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004560 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004561
Willy Tarreau87b09662015-04-03 00:22:06 +02004562 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004563 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4564 lua_setmetatable(L, -2);
4565
4566 return 1;
4567}
4568
4569/* This function is an LUA binding. It is called with each converter.
4570 * It uses closure argument to store the associated converter. It
4571 * returns only one argument or throws an error. An error is thrown
4572 * only if an error is encountered during the argument parsing. If
4573 * the converter function function fails, nil is returned.
4574 */
4575__LJMP static int hlua_run_sample_conv(lua_State *L)
4576{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004577 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004578 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004579 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004580 int i;
4581 struct sample smp;
4582
4583 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004584 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004585
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004586 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004587 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004588
4589 /* Get extra arguments. */
4590 for (i = 0; i < lua_gettop(L) - 2; i++) {
4591 if (i >= ARGM_NBARGS)
4592 break;
4593 hlua_lua2arg(L, i + 3, &args[i]);
4594 }
4595 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004596 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004597
4598 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004599 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004600
4601 /* Run the special args checker. */
4602 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4603 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004604 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004605 }
4606
4607 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004608 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004609 if (!hlua_lua2smp(L, 2, &smp)) {
4610 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004611 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004612 }
4613
Willy Tarreau1777ea62016-03-10 16:15:46 +01004614 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4615
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004616 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004617 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004618 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004619 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004620 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004621 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004622 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4623 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004624 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004625 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004626 }
4627
4628 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004629 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004630 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004631 lua_pushstring(L, "");
4632 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004633 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004634 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004635 }
4636
4637 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004638 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004639 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004640 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004641 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004642 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004643 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004644 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004645
4646 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004647 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004648 WILL_LJMP(lua_error(L));
4649 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004650}
4651
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004652/*
4653 *
4654 *
4655 * Class AppletTCP
4656 *
4657 *
4658 */
4659
4660/* Returns a struct hlua_txn if the stack entry "ud" is
4661 * a class stream, otherwise it throws an error.
4662 */
4663__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4664{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004665 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004666}
4667
4668/* This function creates and push in the stack an Applet object
4669 * according with a current TXN.
4670 */
4671static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4672{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004673 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004674 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004675 struct proxy *p;
4676
4677 ALREADY_CHECKED(s);
4678 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004679
4680 /* Check stack size. */
4681 if (!lua_checkstack(L, 3))
4682 return 0;
4683
4684 /* Create the object: obj[0] = userdata.
4685 * Note that the base of the Converters object is the
4686 * same than the TXN object.
4687 */
4688 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004689 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004690 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004691 luactx->appctx = ctx;
4692 luactx->htxn.s = s;
4693 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004694
4695 /* Create the "f" field that contains a list of fetches. */
4696 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004697 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004698 return 0;
4699 lua_settable(L, -3);
4700
4701 /* Create the "sf" field that contains a list of stringsafe fetches. */
4702 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004703 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004704 return 0;
4705 lua_settable(L, -3);
4706
4707 /* Create the "c" field that contains a list of converters. */
4708 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004709 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004710 return 0;
4711 lua_settable(L, -3);
4712
4713 /* Create the "sc" field that contains a list of stringsafe converters. */
4714 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004715 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004716 return 0;
4717 lua_settable(L, -3);
4718
4719 /* Pop a class stream metatable and affect it to the table. */
4720 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4721 lua_setmetatable(L, -2);
4722
4723 return 1;
4724}
4725
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004726__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4727{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004728 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004729 struct stream *s;
4730 const char *name;
4731 size_t len;
4732 struct sample smp;
4733
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004734 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4735 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004736
4737 /* It is useles to retrieve the stream, but this function
4738 * runs only in a stream context.
4739 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004740 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004741 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004742 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004743
4744 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004745 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004746 hlua_lua2smp(L, 3, &smp);
4747
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02004748 /* Store the sample in a variable. We don't need to dup the smp, vars API
4749 * already takes care of duplicating dynamic var data.
4750 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004751 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004752
4753 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4754 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4755 else
4756 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4757
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004758 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004759}
4760
4761__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4762{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004763 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004764 struct stream *s;
4765 const char *name;
4766 size_t len;
4767 struct sample smp;
4768
4769 MAY_LJMP(check_args(L, 2, "unset_var"));
4770
4771 /* It is useles to retrieve the stream, but this function
4772 * runs only in a stream context.
4773 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004774 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004775 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004776 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004777
4778 /* Unset the variable. */
4779 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004780 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4781 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004782}
4783
4784__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4785{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004786 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004787 struct stream *s;
4788 const char *name;
4789 size_t len;
4790 struct sample smp;
4791
4792 MAY_LJMP(check_args(L, 2, "get_var"));
4793
4794 /* It is useles to retrieve the stream, but this function
4795 * runs only in a stream context.
4796 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004797 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004798 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004799 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004800
4801 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004802 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004803 lua_pushnil(L);
4804 return 1;
4805 }
4806
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004807 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004808}
4809
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004810__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4811{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004812 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4813 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004814 struct hlua *hlua;
4815
4816 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004817 if (!s->hlua)
4818 return 0;
4819 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004820
4821 MAY_LJMP(check_args(L, 2, "set_priv"));
4822
4823 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004824 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004825
4826 /* Get and store new value. */
4827 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4828 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4829
4830 return 0;
4831}
4832
4833__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4834{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004835 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4836 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004837 struct hlua *hlua;
4838
4839 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004840 if (!s->hlua) {
4841 lua_pushnil(L);
4842 return 1;
4843 }
4844 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004845
4846 /* Push configuration index in the stack. */
4847 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4848
4849 return 1;
4850}
4851
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004852/* If expected data not yet available, it returns a yield. This function
4853 * consumes the data in the buffer. It returns a string containing the
4854 * data. This string can be empty.
4855 */
4856__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4857{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004858 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004859 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004860 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004861 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004862 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004863 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004864 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004865
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004866 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004867 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004868
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004869 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004870 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004871 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004872 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004873 }
4874
4875 /* End of data: commit the total strings and return. */
4876 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004877 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004878 return 1;
4879 }
4880
4881 /* Ensure that the block 2 length is usable. */
4882 if (ret == 1)
4883 len2 = 0;
4884
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004885 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004886 luaL_addlstring(&luactx->b, blk1, len1);
4887 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004888
4889 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004890 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004891 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004892 return 1;
4893}
4894
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004895/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004896__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4897{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004898 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004899
4900 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004901 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004902
4903 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4904}
4905
4906/* If expected data not yet available, it returns a yield. This function
4907 * consumes the data in the buffer. It returns a string containing the
4908 * data. This string can be empty.
4909 */
4910__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4911{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004912 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004913 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004914 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004915 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004916 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004917 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004918 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004919 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004920
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004921 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004922 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004923
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004924 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004925 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004926 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004927 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004928 }
4929
4930 /* End of data: commit the total strings and return. */
4931 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004932 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004933 return 1;
4934 }
4935
4936 /* Ensure that the block 2 length is usable. */
4937 if (ret == 1)
4938 len2 = 0;
4939
4940 if (len == -1) {
4941
4942 /* If len == -1, catenate all the data avalaile and
4943 * yield because we want to get all the data until
4944 * the end of data stream.
4945 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004946 luaL_addlstring(&luactx->b, blk1, len1);
4947 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004948 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004949 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004950 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004951
4952 } else {
4953
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004954 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004955 if (len1 > len)
4956 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004957 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004958 len -= len1;
4959
4960 /* Copy the second block. */
4961 if (len2 > len)
4962 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004963 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004964 len -= len2;
4965
4966 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004967 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004968
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004969 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004970 if (len > 0) {
4971 lua_pushinteger(L, len);
4972 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004973 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004974 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004975 }
4976
4977 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004978 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004979 return 1;
4980 }
4981
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004982 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004983 hlua_pusherror(L, "Lua: internal error");
4984 WILL_LJMP(lua_error(L));
4985 return 0;
4986}
4987
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004988/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004989__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4990{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004991 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004992 int len = -1;
4993
4994 if (lua_gettop(L) > 2)
4995 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4996 if (lua_gettop(L) >= 2) {
4997 len = MAY_LJMP(luaL_checkinteger(L, 2));
4998 lua_pop(L, 1);
4999 }
5000
5001 /* Confirm or set the required length */
5002 lua_pushinteger(L, len);
5003
5004 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005005 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005006
5007 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
5008}
5009
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005010/* Append data in the output side of the buffer. This data is immediately
5011 * sent. The function returns the amount of data written. If the buffer
5012 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005013 * if the channel is closed.
5014 */
5015__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
5016{
5017 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005019 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
5020 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005021 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005022 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005023 int max;
5024
5025 /* Get the max amount of data which can write as input in the channel. */
5026 max = channel_recv_max(chn);
5027 if (max > (len - l))
5028 max = len - l;
5029
5030 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005031 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005032
5033 /* update counters. */
5034 l += max;
5035 lua_pop(L, 1);
5036 lua_pushinteger(L, l);
5037
5038 /* If some data is not send, declares the situation to the
5039 * applet, and returns a yield.
5040 */
5041 if (l < len) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005042 sc_need_room(sc, channel_recv_max(chn) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005043 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005044 }
5045
5046 return 1;
5047}
5048
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005049/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005050 * yield the LUA process, and resume it without checking the
5051 * input arguments.
5052 */
5053__LJMP static int hlua_applet_tcp_send(lua_State *L)
5054{
5055 MAY_LJMP(check_args(L, 2, "send"));
5056 lua_pushinteger(L, 0);
5057
5058 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
5059}
5060
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005061/*
5062 *
5063 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005064 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005065 *
5066 *
5067 */
5068
5069/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005070 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005071 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005072__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005073{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005074 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005075}
5076
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005077/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005078 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005079 * It relies on the caller to have already reserved the room in ctx->svcctx
5080 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005081 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005082static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005083{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005084 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005085 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01005086 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02005087 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005088 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02005089 struct htx *htx;
5090 struct htx_blk *blk;
5091 struct htx_sl *sl;
5092 struct ist path;
5093 unsigned long long len = 0;
5094 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02005095 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005096
5097 /* Check stack size. */
5098 if (!lua_checkstack(L, 3))
5099 return 0;
5100
5101 /* Create the object: obj[0] = userdata.
5102 * Note that the base of the Converters object is the
5103 * same than the TXN object.
5104 */
5105 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005106 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005107 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005108 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005109 http_ctx->status = 200; /* Default status code returned. */
5110 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005111 luactx->htxn.s = s;
5112 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005113
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005114 /* Create the "f" field that contains a list of fetches. */
5115 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005116 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005117 return 0;
5118 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005119
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005120 /* Create the "sf" field that contains a list of stringsafe fetches. */
5121 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005122 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005123 return 0;
5124 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005125
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005126 /* Create the "c" field that contains a list of converters. */
5127 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005128 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005129 return 0;
5130 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005131
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005132 /* Create the "sc" field that contains a list of stringsafe converters. */
5133 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005134 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005135 return 0;
5136 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005137
Christopher Fauleta2097962019-07-15 16:25:33 +02005138 htx = htxbuf(&s->req.buf);
5139 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005140 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005141 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005142
Christopher Fauleta2097962019-07-15 16:25:33 +02005143 /* Stores the request method. */
5144 lua_pushstring(L, "method");
5145 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5146 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005147
Christopher Fauleta2097962019-07-15 16:25:33 +02005148 /* Stores the http version. */
5149 lua_pushstring(L, "version");
5150 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5151 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005152
Christopher Fauleta2097962019-07-15 16:25:33 +02005153 /* creates an array of headers. hlua_http_get_headers() crates and push
5154 * the array on the top of the stack.
5155 */
5156 lua_pushstring(L, "headers");
5157 htxn.s = s;
5158 htxn.p = px;
5159 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005160 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005161 return 0;
5162 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005163
Amaury Denoyellec453f952021-07-06 11:40:12 +02005164 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5165 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005166 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005167 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005168
Christopher Fauleta2097962019-07-15 16:25:33 +02005169 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005170 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005171 q = p;
5172 while (q < end && *q != '?')
5173 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005174
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005175 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005176 lua_pushstring(L, "path");
5177 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005178 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005179
Christopher Fauleta2097962019-07-15 16:25:33 +02005180 /* Stores the query string. */
5181 lua_pushstring(L, "qs");
5182 if (*q == '?')
5183 q++;
5184 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005185 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005186 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005187
Christopher Fauleta2097962019-07-15 16:25:33 +02005188 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5189 struct htx_blk *blk = htx_get_blk(htx, pos);
5190 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005191
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005192 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005193 break;
5194 if (type == HTX_BLK_DATA)
5195 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005196 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005197 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005198 len += htx->extra;
5199
5200 /* Stores the request path. */
5201 lua_pushstring(L, "length");
5202 lua_pushinteger(L, len);
5203 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005204
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005205 /* Create an empty array of HTTP request headers. */
5206 lua_pushstring(L, "response");
5207 lua_newtable(L);
5208 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005209
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005210 /* Pop a class stream metatable and affect it to the table. */
5211 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5212 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005213
5214 return 1;
5215}
5216
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005217__LJMP static int hlua_applet_http_set_var(lua_State *L)
5218{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005219 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005220 struct stream *s;
5221 const char *name;
5222 size_t len;
5223 struct sample smp;
5224
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005225 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5226 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005227
5228 /* It is useles to retrieve the stream, but this function
5229 * runs only in a stream context.
5230 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005231 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005232 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005233 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005234
5235 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005236 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005237 hlua_lua2smp(L, 3, &smp);
5238
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02005239 /* Store the sample in a variable. We don't need to dup the smp, vars API
5240 * already takes care of duplicating dynamic var data.
5241 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005242 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005243
5244 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5245 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5246 else
5247 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5248
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005249 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005250}
5251
5252__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5253{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005254 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005255 struct stream *s;
5256 const char *name;
5257 size_t len;
5258 struct sample smp;
5259
5260 MAY_LJMP(check_args(L, 2, "unset_var"));
5261
5262 /* It is useles to retrieve the stream, but this function
5263 * runs only in a stream context.
5264 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005265 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005266 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005267 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005268
5269 /* Unset the variable. */
5270 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005271 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5272 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005273}
5274
5275__LJMP static int hlua_applet_http_get_var(lua_State *L)
5276{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005277 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005278 struct stream *s;
5279 const char *name;
5280 size_t len;
5281 struct sample smp;
5282
5283 MAY_LJMP(check_args(L, 2, "get_var"));
5284
5285 /* It is useles to retrieve the stream, but this function
5286 * runs only in a stream context.
5287 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005288 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005289 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005290 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005291
5292 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005293 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005294 lua_pushnil(L);
5295 return 1;
5296 }
5297
Aurelien DARRAGON41217722023-05-17 10:44:47 +02005298 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005299}
5300
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005301__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5302{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005303 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5304 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005305 struct hlua *hlua;
5306
5307 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005308 if (!s->hlua)
5309 return 0;
5310 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005311
5312 MAY_LJMP(check_args(L, 2, "set_priv"));
5313
5314 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005315 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005316
5317 /* Get and store new value. */
5318 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5319 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5320
5321 return 0;
5322}
5323
5324__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5325{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005326 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5327 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005328 struct hlua *hlua;
5329
5330 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005331 if (!s->hlua) {
5332 lua_pushnil(L);
5333 return 1;
5334 }
5335 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005336
5337 /* Push configuration index in the stack. */
5338 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5339
5340 return 1;
5341}
5342
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005343/* If expected data not yet available, it returns a yield. This function
5344 * consumes the data in the buffer. It returns a string containing the
5345 * data. This string can be empty.
5346 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005347__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005348{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005349 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005350 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005351 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005352 struct htx *htx;
5353 struct htx_blk *blk;
5354 size_t count;
5355 int stop = 0;
5356
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005357 htx = htx_from_buf(&req->buf);
5358 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005359 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005360
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005361 while (count && !stop && blk) {
5362 enum htx_blk_type type = htx_get_blk_type(blk);
5363 uint32_t sz = htx_get_blksz(blk);
5364 struct ist v;
5365 uint32_t vlen;
5366 char *nl;
5367
5368 vlen = sz;
5369 if (vlen > count) {
5370 if (type != HTX_BLK_DATA)
5371 break;
5372 vlen = count;
5373 }
5374
5375 switch (type) {
5376 case HTX_BLK_UNUSED:
5377 break;
5378
5379 case HTX_BLK_DATA:
5380 v = htx_get_blk_value(htx, blk);
5381 v.len = vlen;
5382 nl = istchr(v, '\n');
5383 if (nl != NULL) {
5384 stop = 1;
5385 vlen = nl - v.ptr + 1;
5386 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005387 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005388 break;
5389
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005390 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005391 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005392 stop = 1;
5393 break;
5394
5395 default:
5396 break;
5397 }
5398
Willy Tarreau84240042022-02-28 16:51:23 +01005399 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005400 count -= vlen;
5401 if (sz == vlen)
5402 blk = htx_remove_blk(htx, blk);
5403 else {
5404 htx_cut_data_blk(htx, blk, vlen);
5405 break;
5406 }
5407 }
5408
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005409 /* The message was fully consumed and no more data are expected
5410 * (EOM flag set).
5411 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005412 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005413 stop = 1;
5414
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005415 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005416 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005417 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005418 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005419 }
5420
5421 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005422 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005423 return 1;
5424}
5425
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005426
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005427/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005428__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005429{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005430 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005431
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005432 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005433 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005434
Christopher Fauleta2097962019-07-15 16:25:33 +02005435 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005436}
5437
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005438/* If expected data not yet available, it returns a yield. This function
5439 * consumes the data in the buffer. It returns a string containing the
5440 * data. This string can be empty.
5441 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005442__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005443{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005444 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005445 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005446 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005447 struct htx *htx;
5448 struct htx_blk *blk;
5449 size_t count;
5450 int len;
5451
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005452 htx = htx_from_buf(&req->buf);
5453 len = MAY_LJMP(luaL_checkinteger(L, 2));
5454 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005455 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005456 while (count && len && blk) {
5457 enum htx_blk_type type = htx_get_blk_type(blk);
5458 uint32_t sz = htx_get_blksz(blk);
5459 struct ist v;
5460 uint32_t vlen;
5461
5462 vlen = sz;
5463 if (len > 0 && vlen > len)
5464 vlen = len;
5465 if (vlen > count) {
5466 if (type != HTX_BLK_DATA)
5467 break;
5468 vlen = count;
5469 }
5470
5471 switch (type) {
5472 case HTX_BLK_UNUSED:
5473 break;
5474
5475 case HTX_BLK_DATA:
5476 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005477 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005478 break;
5479
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005480 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005481 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005482 len = 0;
5483 break;
5484
5485 default:
5486 break;
5487 }
5488
Willy Tarreau84240042022-02-28 16:51:23 +01005489 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005490 count -= vlen;
5491 if (len > 0)
5492 len -= vlen;
5493 if (sz == vlen)
5494 blk = htx_remove_blk(htx, blk);
5495 else {
5496 htx_cut_data_blk(htx, blk, vlen);
5497 break;
5498 }
5499 }
5500
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005501 /* The message was fully consumed and no more data are expected
5502 * (EOM flag set).
5503 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005504 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005505 len = 0;
5506
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005507 htx_to_buf(htx, &req->buf);
5508
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005509 /* If we are no other data available, yield waiting for new data. */
5510 if (len) {
5511 if (len > 0) {
5512 lua_pushinteger(L, len);
5513 lua_replace(L, 2);
5514 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005515 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005516 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005517 }
5518
5519 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005520 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005521 return 1;
5522}
5523
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005524/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005525__LJMP static int hlua_applet_http_recv(lua_State *L)
5526{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005527 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005528 int len = -1;
5529
5530 /* Check arguments. */
5531 if (lua_gettop(L) > 2)
5532 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5533 if (lua_gettop(L) >= 2) {
5534 len = MAY_LJMP(luaL_checkinteger(L, 2));
5535 lua_pop(L, 1);
5536 }
5537
Christopher Fauleta2097962019-07-15 16:25:33 +02005538 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005539
Christopher Fauleta2097962019-07-15 16:25:33 +02005540 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005541 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005542
Christopher Fauleta2097962019-07-15 16:25:33 +02005543 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005544}
5545
5546/* Append data in the output side of the buffer. This data is immediately
5547 * sent. The function returns the amount of data written. If the buffer
5548 * cannot contain the data, the function yields. The function returns -1
5549 * if the channel is closed.
5550 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005551__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005552{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005553 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005554 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005555 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005556 struct htx *htx = htx_from_buf(&res->buf);
5557 const char *data;
5558 size_t len;
5559 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5560 int max;
5561
Christopher Faulet9060fc02019-07-03 11:39:30 +02005562 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005563 if (!max)
5564 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005565
5566 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5567
5568 /* Get the max amount of data which can write as input in the channel. */
5569 if (max > (len - l))
5570 max = len - l;
5571
5572 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005573 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005574 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005575
5576 /* update counters. */
5577 l += max;
5578 lua_pop(L, 1);
5579 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005580
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005581 /* If some data is not send, declares the situation to the
5582 * applet, and returns a yield.
5583 */
5584 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005585 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005586 htx_to_buf(htx, &res->buf);
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005587 sc_need_room(sc, channel_recv_max(res) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005588 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005589 }
5590
Christopher Fauleta2097962019-07-15 16:25:33 +02005591 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005592 return 1;
5593}
5594
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005595/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005596 * yield the LUA process, and resume it without checking the
5597 * input arguments.
5598 */
5599__LJMP static int hlua_applet_http_send(lua_State *L)
5600{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005601 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005602 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005603
5604 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005605 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005606 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5607 WILL_LJMP(lua_error(L));
5608 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005609
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005610 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005611 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005612
Christopher Fauleta2097962019-07-15 16:25:33 +02005613 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005614}
5615
5616__LJMP static int hlua_applet_http_addheader(lua_State *L)
5617{
5618 const char *name;
5619 int ret;
5620
5621 MAY_LJMP(hlua_checkapplet_http(L, 1));
5622 name = MAY_LJMP(luaL_checkstring(L, 2));
5623 MAY_LJMP(luaL_checkstring(L, 3));
5624
5625 /* Push in the stack the "response" entry. */
5626 ret = lua_getfield(L, 1, "response");
5627 if (ret != LUA_TTABLE) {
5628 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5629 "is expected as an array. %s found", lua_typename(L, ret));
5630 WILL_LJMP(lua_error(L));
5631 }
5632
5633 /* check if the header is already registered if it is not
5634 * the case, register it.
5635 */
5636 ret = lua_getfield(L, -1, name);
5637 if (ret == LUA_TNIL) {
5638
5639 /* Entry not found. */
5640 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5641
5642 /* Insert the new header name in the array in the top of the stack.
5643 * It left the new array in the top of the stack.
5644 */
5645 lua_newtable(L);
5646 lua_pushvalue(L, 2);
5647 lua_pushvalue(L, -2);
5648 lua_settable(L, -4);
5649
5650 } else if (ret != LUA_TTABLE) {
5651
5652 /* corruption error. */
5653 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5654 "is expected as an array. %s found", name, lua_typename(L, ret));
5655 WILL_LJMP(lua_error(L));
5656 }
5657
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005658 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005659 * the header value as new entry.
5660 */
5661 lua_pushvalue(L, 3);
5662 ret = lua_rawlen(L, -2);
5663 lua_rawseti(L, -2, ret + 1);
5664 lua_pushboolean(L, 1);
5665 return 1;
5666}
5667
5668__LJMP static int hlua_applet_http_status(lua_State *L)
5669{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005670 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005671 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005672 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005673 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005674
5675 if (status < 100 || status > 599) {
5676 lua_pushboolean(L, 0);
5677 return 1;
5678 }
5679
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005680 http_ctx->status = status;
5681 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005682 lua_pushboolean(L, 1);
5683 return 1;
5684}
5685
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005686
Christopher Fauleta2097962019-07-15 16:25:33 +02005687__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005688{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005689 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005690 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005691 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005692 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005693 struct htx *htx;
5694 struct htx_sl *sl;
5695 struct h1m h1m;
5696 const char *status, *reason;
5697 const char *name, *value;
5698 size_t nlen, vlen;
5699 unsigned int flags;
5700
5701 /* Send the message at once. */
5702 htx = htx_from_buf(&res->buf);
5703 h1m_init_res(&h1m);
5704
5705 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005706 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5707 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005708 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005709 reason = http_get_reason(http_ctx->status);
5710 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005711 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5712 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5713 }
5714 else {
5715 flags = HTX_SL_F_IS_RESP;
5716 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5717 }
5718 if (!sl) {
5719 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005720 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005721 WILL_LJMP(lua_error(L));
5722 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005723 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005724
5725 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005726 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5727 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005728 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005729 WILL_LJMP(lua_error(L));
5730 }
5731
5732 /* Browse the list of headers. */
5733 lua_pushnil(L);
5734 while(lua_next(L, -2) != 0) {
5735 /* We expect a string as -2. */
5736 if (lua_type(L, -2) != LUA_TSTRING) {
5737 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005738 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005739 lua_typename(L, lua_type(L, -2)));
5740 WILL_LJMP(lua_error(L));
5741 }
5742 name = lua_tolstring(L, -2, &nlen);
5743
5744 /* We expect an array as -1. */
5745 if (lua_type(L, -1) != LUA_TTABLE) {
5746 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 +02005747 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005748 name,
5749 lua_typename(L, lua_type(L, -1)));
5750 WILL_LJMP(lua_error(L));
5751 }
5752
5753 /* Browse the table who is on the top of the stack. */
5754 lua_pushnil(L);
5755 while(lua_next(L, -2) != 0) {
5756 int id;
5757
5758 /* We expect a number as -2. */
5759 if (lua_type(L, -2) != LUA_TNUMBER) {
5760 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 +02005761 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005762 name,
5763 lua_typename(L, lua_type(L, -2)));
5764 WILL_LJMP(lua_error(L));
5765 }
5766 id = lua_tointeger(L, -2);
5767
5768 /* We expect a string as -2. */
5769 if (lua_type(L, -1) != LUA_TSTRING) {
5770 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 +02005771 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005772 name, id,
5773 lua_typename(L, lua_type(L, -1)));
5774 WILL_LJMP(lua_error(L));
5775 }
5776 value = lua_tolstring(L, -1, &vlen);
5777
5778 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005779 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5780 int ret;
5781
5782 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5783 if (ret < 0) {
5784 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5785 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5786 name);
5787 WILL_LJMP(lua_error(L));
5788 }
5789 else if (ret == 0)
5790 goto next; /* Skip it */
5791 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005792 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5793 struct ist v = ist2(value, vlen);
5794 int ret;
5795
5796 ret = h1_parse_cont_len_header(&h1m, &v);
5797 if (ret < 0) {
5798 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005799 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005800 name);
5801 WILL_LJMP(lua_error(L));
5802 }
5803 else if (ret == 0)
5804 goto next; /* Skip it */
5805 }
5806
5807 /* Add a new header */
5808 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5809 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005810 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005811 name);
5812 WILL_LJMP(lua_error(L));
5813 }
5814 next:
5815 /* Remove the array from the stack, and get next element with a remaining string. */
5816 lua_pop(L, 1);
5817 }
5818
5819 /* Remove the array from the stack, and get next element with a remaining string. */
5820 lua_pop(L, 1);
5821 }
5822
5823 if (h1m.flags & H1_MF_CHNK)
5824 h1m.flags &= ~H1_MF_CLEN;
5825 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5826 h1m.flags |= H1_MF_XFER_LEN;
5827
5828 /* Uset HTX start-line flags */
5829 if (h1m.flags & H1_MF_XFER_ENC)
5830 flags |= HTX_SL_F_XFER_ENC;
5831 if (h1m.flags & H1_MF_XFER_LEN) {
5832 flags |= HTX_SL_F_XFER_LEN;
5833 if (h1m.flags & H1_MF_CHNK)
5834 flags |= HTX_SL_F_CHNK;
5835 else if (h1m.flags & H1_MF_CLEN)
5836 flags |= HTX_SL_F_CLEN;
5837 if (h1m.body_len == 0)
5838 flags |= HTX_SL_F_BODYLESS;
5839 }
5840 sl->flags |= flags;
5841
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005842 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005843 * and the status code implies the presence of a message body, we must
5844 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005845 * for the keepalive compliance. If the applet announces a transfer-encoding
5846 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005847 */
5848 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005849 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005850 /* Add a new header */
5851 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5852 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5853 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005854 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005855 WILL_LJMP(lua_error(L));
5856 }
5857 }
5858
5859 /* Finalize headers. */
5860 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5861 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005862 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005863 WILL_LJMP(lua_error(L));
5864 }
5865
5866 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5867 b_reset(&res->buf);
5868 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5869 WILL_LJMP(lua_error(L));
5870 }
5871
5872 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005873 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005874
5875 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005876 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005877 return 0;
5878
5879}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005880/* We will build the status line and the headers of the HTTP response.
5881 * We will try send at once if its not possible, we give back the hand
5882 * waiting for more room.
5883 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005884__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005885{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005886 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005887 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005888 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005889
5890 if (co_data(res)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005891 sc_need_room(sc, -1);
Christopher Fauleta2097962019-07-15 16:25:33 +02005892 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005893 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005894 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005895}
5896
5897
Christopher Fauleta2097962019-07-15 16:25:33 +02005898__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005899{
Christopher Fauleta2097962019-07-15 16:25:33 +02005900 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005901}
5902
Christopher Fauleta2097962019-07-15 16:25:33 +02005903/*
5904 *
5905 *
5906 * Class HTTP
5907 *
5908 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005909 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005910
5911/* Returns a struct hlua_txn if the stack entry "ud" is
5912 * a class stream, otherwise it throws an error.
5913 */
5914__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005915{
Christopher Fauleta2097962019-07-15 16:25:33 +02005916 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5917}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005918
Christopher Fauleta2097962019-07-15 16:25:33 +02005919/* This function creates and push in the stack a HTTP object
5920 * according with a current TXN.
5921 */
5922static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5923{
5924 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005925
Christopher Fauleta2097962019-07-15 16:25:33 +02005926 /* Check stack size. */
5927 if (!lua_checkstack(L, 3))
5928 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005929
Christopher Fauleta2097962019-07-15 16:25:33 +02005930 /* Create the object: obj[0] = userdata.
5931 * Note that the base of the Converters object is the
5932 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005933 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005934 lua_newtable(L);
5935 htxn = lua_newuserdata(L, sizeof(*htxn));
5936 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005937
5938 htxn->s = txn->s;
5939 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005940 htxn->dir = txn->dir;
5941 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005942
5943 /* Pop a class stream metatable and affect it to the table. */
5944 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5945 lua_setmetatable(L, -2);
5946
5947 return 1;
5948}
5949
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005950/* This function creates and returns an array containing the status-line
5951 * elements. This function does not fails.
5952 */
5953__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5954{
5955 /* Create the table. */
5956 lua_newtable(L);
5957
5958 if (sl->flags & HTX_SL_F_IS_RESP) {
5959 lua_pushstring(L, "version");
5960 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5961 lua_settable(L, -3);
5962 lua_pushstring(L, "code");
5963 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5964 lua_settable(L, -3);
5965 lua_pushstring(L, "reason");
5966 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5967 lua_settable(L, -3);
5968 }
5969 else {
5970 lua_pushstring(L, "method");
5971 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5972 lua_settable(L, -3);
5973 lua_pushstring(L, "uri");
5974 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5975 lua_settable(L, -3);
5976 lua_pushstring(L, "version");
5977 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5978 lua_settable(L, -3);
5979 }
5980 return 1;
5981}
5982
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005983/* This function creates ans returns an array of HTTP headers.
5984 * This function does not fails. It is used as wrapper with the
5985 * 2 following functions.
5986 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005987__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005988{
Christopher Fauleta2097962019-07-15 16:25:33 +02005989 struct htx *htx;
5990 int32_t pos;
5991
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005992 /* Create the table. */
5993 lua_newtable(L);
5994
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005995
Christopher Fauleta2097962019-07-15 16:25:33 +02005996 htx = htxbuf(&msg->chn->buf);
5997 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5998 struct htx_blk *blk = htx_get_blk(htx, pos);
5999 enum htx_blk_type type = htx_get_blk_type(blk);
6000 struct ist n, v;
6001 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006002
Christopher Fauleta2097962019-07-15 16:25:33 +02006003 if (type == HTX_BLK_HDR) {
6004 n = htx_get_blk_name(htx,blk);
6005 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01006006 }
Christopher Fauleta2097962019-07-15 16:25:33 +02006007 else if (type == HTX_BLK_EOH)
6008 break;
6009 else
6010 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006011
Christopher Fauleta2097962019-07-15 16:25:33 +02006012 /* Check for existing entry:
6013 * assume that the table is on the top of the stack, and
6014 * push the key in the stack, the function lua_gettable()
6015 * perform the lookup.
6016 */
6017 lua_pushlstring(L, n.ptr, n.len);
6018 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01006019
Christopher Fauleta2097962019-07-15 16:25:33 +02006020 switch (lua_type(L, -1)) {
6021 case LUA_TNIL:
6022 /* Table not found, create it. */
6023 lua_pop(L, 1); /* remove the nil value. */
6024 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
6025 lua_newtable(L); /* create and push empty table. */
6026 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
6027 lua_rawseti(L, -2, 0); /* index header value (pop it). */
6028 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01006029 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01006030
Christopher Fauleta2097962019-07-15 16:25:33 +02006031 case LUA_TTABLE:
6032 /* Entry found: push the value in the table. */
6033 len = lua_rawlen(L, -1);
6034 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
6035 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
6036 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
6037 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006038
Christopher Fauleta2097962019-07-15 16:25:33 +02006039 default:
6040 /* Other cases are errors. */
6041 hlua_pusherror(L, "internal error during the parsing of headers.");
6042 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006043 }
6044 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006045 return 1;
6046}
6047
6048__LJMP static int hlua_http_req_get_headers(lua_State *L)
6049{
6050 struct hlua_txn *htxn;
6051
6052 MAY_LJMP(check_args(L, 1, "req_get_headers"));
6053 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6054
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006055 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006056 WILL_LJMP(lua_error(L));
6057
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006058 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006059}
6060
6061__LJMP static int hlua_http_res_get_headers(lua_State *L)
6062{
6063 struct hlua_txn *htxn;
6064
6065 MAY_LJMP(check_args(L, 1, "res_get_headers"));
6066 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6067
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006068 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006069 WILL_LJMP(lua_error(L));
6070
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006071 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006072}
6073
6074/* This function replace full header, or just a value in
6075 * the request or in the response. It is a wrapper fir the
6076 * 4 following functions.
6077 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006078__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006079{
6080 size_t name_len;
6081 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6082 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
6083 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02006084 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02006085 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006086
Dragan Dosen26743032019-04-30 15:54:36 +02006087 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006088 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
6089
Christopher Fauleta2097962019-07-15 16:25:33 +02006090 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006091 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02006092 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006093 return 0;
6094}
6095
6096__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
6097{
6098 struct hlua_txn *htxn;
6099
6100 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6101 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6102
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006103 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006104 WILL_LJMP(lua_error(L));
6105
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006106 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006107}
6108
6109__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
6110{
6111 struct hlua_txn *htxn;
6112
6113 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
6114 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6115
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006116 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006117 WILL_LJMP(lua_error(L));
6118
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006119 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006120}
6121
6122__LJMP static int hlua_http_req_rep_val(lua_State *L)
6123{
6124 struct hlua_txn *htxn;
6125
6126 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6127 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6128
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006129 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006130 WILL_LJMP(lua_error(L));
6131
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006132 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006133}
6134
6135__LJMP static int hlua_http_res_rep_val(lua_State *L)
6136{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006137 struct hlua_txn *htxn;
6138
6139 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6140 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6141
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006142 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006143 WILL_LJMP(lua_error(L));
6144
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006145 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006146}
6147
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006148/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006149 * It is a wrapper for the 2 following functions.
6150 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006151__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006152{
6153 size_t len;
6154 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006155 struct htx *htx = htxbuf(&msg->chn->buf);
6156 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006157
Christopher Fauleta2097962019-07-15 16:25:33 +02006158 ctx.blk = NULL;
6159 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6160 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006161 return 0;
6162}
6163
6164__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6165{
6166 struct hlua_txn *htxn;
6167
6168 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6169 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6170
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006171 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006172 WILL_LJMP(lua_error(L));
6173
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006174 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006175}
6176
6177__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6178{
6179 struct hlua_txn *htxn;
6180
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006181 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006182 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6183
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006184 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006185 WILL_LJMP(lua_error(L));
6186
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006187 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006188}
6189
6190/* This function adds an header. It is a wrapper used by
6191 * the 2 following functions.
6192 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006193__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006194{
6195 size_t name_len;
6196 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6197 size_t value_len;
6198 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006199 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006200
Christopher Fauleta2097962019-07-15 16:25:33 +02006201 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6202 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006203 return 0;
6204}
6205
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006206__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6207{
6208 struct hlua_txn *htxn;
6209
6210 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6211 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6212
6213 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6214 WILL_LJMP(lua_error(L));
6215
6216 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6217}
6218
6219__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6220{
6221 struct hlua_txn *htxn;
6222
6223 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6224 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6225
6226 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6227 WILL_LJMP(lua_error(L));
6228
6229 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6230}
6231
6232static int hlua_http_req_set_hdr(lua_State *L)
6233{
6234 struct hlua_txn *htxn;
6235
6236 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6237 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6238
6239 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6240 WILL_LJMP(lua_error(L));
6241
6242 hlua_http_del_hdr(L, &htxn->s->txn->req);
6243 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6244}
6245
6246static int hlua_http_res_set_hdr(lua_State *L)
6247{
6248 struct hlua_txn *htxn;
6249
6250 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6251 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6252
6253 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6254 WILL_LJMP(lua_error(L));
6255
6256 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6257 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6258}
6259
6260/* This function set the method. */
6261static int hlua_http_req_set_meth(lua_State *L)
6262{
6263 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6264 size_t name_len;
6265 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6266
6267 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6268 WILL_LJMP(lua_error(L));
6269
6270 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6271 return 1;
6272}
6273
6274/* This function set the method. */
6275static int hlua_http_req_set_path(lua_State *L)
6276{
6277 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6278 size_t name_len;
6279 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6280
6281 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6282 WILL_LJMP(lua_error(L));
6283
6284 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6285 return 1;
6286}
6287
6288/* This function set the query-string. */
6289static int hlua_http_req_set_query(lua_State *L)
6290{
6291 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6292 size_t name_len;
6293 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6294
6295 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6296 WILL_LJMP(lua_error(L));
6297
6298 /* Check length. */
6299 if (name_len > trash.size - 1) {
6300 lua_pushboolean(L, 0);
6301 return 1;
6302 }
6303
6304 /* Add the mark question as prefix. */
6305 chunk_reset(&trash);
6306 trash.area[trash.data++] = '?';
6307 memcpy(trash.area + trash.data, name, name_len);
6308 trash.data += name_len;
6309
6310 lua_pushboolean(L,
6311 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6312 return 1;
6313}
6314
6315/* This function set the uri. */
6316static int hlua_http_req_set_uri(lua_State *L)
6317{
6318 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6319 size_t name_len;
6320 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6321
6322 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6323 WILL_LJMP(lua_error(L));
6324
6325 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6326 return 1;
6327}
6328
6329/* This function set the response code & optionally reason. */
6330static int hlua_http_res_set_status(lua_State *L)
6331{
6332 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6333 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6334 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6335 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6336
6337 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6338 WILL_LJMP(lua_error(L));
6339
6340 http_res_set_status(code, reason, htxn->s);
6341 return 0;
6342}
6343
6344/*
6345 *
6346 *
6347 * Class HTTPMessage
6348 *
6349 *
6350 */
6351
6352/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6353 * otherwise it throws an error.
6354 */
6355__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6356{
6357 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6358}
6359
6360/* Creates and pushes on the stack a HTTP object according with a current TXN.
6361 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006362static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006363{
6364 /* Check stack size. */
6365 if (!lua_checkstack(L, 3))
6366 return 0;
6367
6368 lua_newtable(L);
6369 lua_pushlightuserdata(L, msg);
6370 lua_rawseti(L, -2, 0);
6371
6372 /* Create the "channel" field that contains the request channel object. */
6373 lua_pushstring(L, "channel");
6374 if (!hlua_channel_new(L, msg->chn))
6375 return 0;
6376 lua_rawset(L, -3);
6377
6378 /* Pop a class stream metatable and affect it to the table. */
6379 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6380 lua_setmetatable(L, -2);
6381
6382 return 1;
6383}
6384
6385/* Helper function returning a filter attached to the HTTP message at the
6386 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006387 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006388 * filled with output and input length respectively.
6389 */
6390static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6391{
6392 struct channel *chn = msg->chn;
6393 struct htx *htx = htxbuf(&chn->buf);
6394 struct filter *filter = NULL;
6395
6396 *offset = co_data(msg->chn);
6397 *len = htx->data - co_data(msg->chn);
6398
6399 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6400 filter = lua_touserdata (L, -1);
6401 if (msg->msg_state >= HTTP_MSG_DATA) {
6402 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6403
6404 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6405 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6406 }
6407 }
6408
6409 lua_pop(L, 1);
6410 return filter;
6411}
6412
6413/* Returns true if the channel attached to the HTTP message is the response
6414 * channel.
6415 */
6416__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6417{
6418 struct http_msg *msg;
6419
6420 MAY_LJMP(check_args(L, 1, "is_resp"));
6421 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6422
6423 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6424 return 1;
6425}
6426
6427/* Returns an array containing the elements status-line of the HTTP message. It relies
6428 * on hlua_http_get_stline().
6429 */
6430__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6431{
6432 struct http_msg *msg;
6433 struct htx *htx;
6434 struct htx_sl *sl;
6435
6436 MAY_LJMP(check_args(L, 1, "get_stline"));
6437 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6438
6439 if (msg->msg_state > HTTP_MSG_BODY)
6440 WILL_LJMP(lua_error(L));
6441
6442 htx = htxbuf(&msg->chn->buf);
6443 sl = http_get_stline(htx);
6444 if (!sl)
6445 return 0;
6446 return hlua_http_get_stline(L, sl);
6447}
6448
6449/* Returns an array containing all headers of the HTTP message. it relies on
6450 * hlua_http_get_headers().
6451 */
6452__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6453{
6454 struct http_msg *msg;
6455
6456 MAY_LJMP(check_args(L, 1, "get_headers"));
6457 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6458
6459 if (msg->msg_state > HTTP_MSG_BODY)
6460 WILL_LJMP(lua_error(L));
6461
6462 return hlua_http_get_headers(L, msg);
6463}
6464
6465/* Deletes all occurrences of an header in the HTTP message matching on its
6466 * name. It relies on hlua_http_del_hdr().
6467 */
6468__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6469{
6470 struct http_msg *msg;
6471
6472 MAY_LJMP(check_args(L, 2, "del_header"));
6473 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6474
6475 if (msg->msg_state > HTTP_MSG_BODY)
6476 WILL_LJMP(lua_error(L));
6477
6478 return hlua_http_del_hdr(L, msg);
6479}
6480
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006481/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006482 * message given its name against a regex and replaces it if it matches. It
6483 * relies on hlua_http_rep_hdr().
6484 */
6485__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6486{
6487 struct http_msg *msg;
6488
6489 MAY_LJMP(check_args(L, 4, "rep_header"));
6490 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6491
6492 if (msg->msg_state > HTTP_MSG_BODY)
6493 WILL_LJMP(lua_error(L));
6494
6495 return hlua_http_rep_hdr(L, msg, 1);
6496}
6497
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006498/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006499 * message given its name against a regex and replaces it if it matches. It
6500 * relies on hlua_http_rep_hdr().
6501 */
6502__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6503{
6504 struct http_msg *msg;
6505
6506 MAY_LJMP(check_args(L, 4, "rep_value"));
6507 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6508
6509 if (msg->msg_state > HTTP_MSG_BODY)
6510 WILL_LJMP(lua_error(L));
6511
6512 return hlua_http_rep_hdr(L, msg, 0);
6513}
6514
6515/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6516__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6517{
6518 struct http_msg *msg;
6519
6520 MAY_LJMP(check_args(L, 3, "add_header"));
6521 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6522
6523 if (msg->msg_state > HTTP_MSG_BODY)
6524 WILL_LJMP(lua_error(L));
6525
6526 return hlua_http_add_hdr(L, msg);
6527}
6528
6529/* Add an header in the HTTP message removing existing headers with the same
6530 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6531 */
6532__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6533{
6534 struct http_msg *msg;
6535
6536 MAY_LJMP(check_args(L, 3, "set_header"));
6537 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6538
6539 if (msg->msg_state > HTTP_MSG_BODY)
6540 WILL_LJMP(lua_error(L));
6541
6542 hlua_http_del_hdr(L, msg);
6543 return hlua_http_add_hdr(L, msg);
6544}
6545
6546/* Rewrites the request method. It relies on http_req_replace_stline(). */
6547__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6548{
6549 struct stream *s;
6550 struct http_msg *msg;
6551 const char *name;
6552 size_t name_len;
6553
6554 MAY_LJMP(check_args(L, 2, "set_method"));
6555 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6556 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6557
6558 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6559 WILL_LJMP(lua_error(L));
6560
6561 s = chn_strm(msg->chn);
6562 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6563 return 1;
6564}
6565
6566/* Rewrites the request path. It relies on http_req_replace_stline(). */
6567__LJMP static int hlua_http_msg_set_path(lua_State *L)
6568{
6569 struct stream *s;
6570 struct http_msg *msg;
6571 const char *name;
6572 size_t name_len;
6573
6574 MAY_LJMP(check_args(L, 2, "set_path"));
6575 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6576 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6577
6578 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6579 WILL_LJMP(lua_error(L));
6580
6581 s = chn_strm(msg->chn);
6582 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6583 return 1;
6584}
6585
6586/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6587__LJMP static int hlua_http_msg_set_query(lua_State *L)
6588{
6589 struct stream *s;
6590 struct http_msg *msg;
6591 const char *name;
6592 size_t name_len;
6593
6594 MAY_LJMP(check_args(L, 2, "set_query"));
6595 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6596 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6597
6598 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6599 WILL_LJMP(lua_error(L));
6600
6601 /* Check length. */
6602 if (name_len > trash.size - 1) {
6603 lua_pushboolean(L, 0);
6604 return 1;
6605 }
6606
6607 /* Add the mark question as prefix. */
6608 chunk_reset(&trash);
6609 trash.area[trash.data++] = '?';
6610 memcpy(trash.area + trash.data, name, name_len);
6611 trash.data += name_len;
6612
6613 s = chn_strm(msg->chn);
6614 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6615 return 1;
6616}
6617
6618/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6619__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6620{
6621 struct stream *s;
6622 struct http_msg *msg;
6623 const char *name;
6624 size_t name_len;
6625
6626 MAY_LJMP(check_args(L, 2, "set_uri"));
6627 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6628 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6629
6630 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6631 WILL_LJMP(lua_error(L));
6632
6633 s = chn_strm(msg->chn);
6634 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6635 return 1;
6636}
6637
6638/* Rewrites the response status code. It relies on http_res_set_status(). */
6639__LJMP static int hlua_http_msg_set_status(lua_State *L)
6640{
6641 struct http_msg *msg;
6642 unsigned int code;
6643 const char *reason;
6644 size_t reason_len;
6645
6646 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6647 code = MAY_LJMP(luaL_checkinteger(L, 2));
6648 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6649
6650 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6651 WILL_LJMP(lua_error(L));
6652
6653 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6654 return 1;
6655}
6656
6657/* Returns true if the HTTP message is full. */
6658__LJMP static int hlua_http_msg_is_full(lua_State *L)
6659{
6660 struct http_msg *msg;
6661
6662 MAY_LJMP(check_args(L, 1, "is_full"));
6663 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6664 lua_pushboolean(L, channel_full(msg->chn, 0));
6665 return 1;
6666}
6667
6668/* Returns true if the HTTP message may still receive data. */
6669__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6670{
6671 struct http_msg *msg;
6672 struct htx *htx;
6673
6674 MAY_LJMP(check_args(L, 1, "may_recv"));
6675 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6676 htx = htxbuf(&msg->chn->buf);
6677 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6678 return 1;
6679}
6680
6681/* Returns true if the HTTP message EOM was received */
6682__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6683{
6684 struct http_msg *msg;
6685 struct htx *htx;
6686
6687 MAY_LJMP(check_args(L, 1, "may_recv"));
6688 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6689 htx = htxbuf(&msg->chn->buf);
6690 lua_pushboolean(L, !htx_expect_more(htx));
6691 return 1;
6692}
6693
6694/* Returns the number of bytes available in the input side of the HTTP
6695 * message. This function never fails.
6696 */
6697__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6698{
6699 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006700 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006701
6702 MAY_LJMP(check_args(L, 1, "input"));
6703 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006704 hlua_http_msg_filter(L, 1, msg, &output, &input);
6705 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706 return 1;
6707}
6708
6709/* Returns the number of bytes available in the output side of the HTTP
6710 * message. This function never fails.
6711 */
6712__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6713{
6714 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006715 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006716
6717 MAY_LJMP(check_args(L, 1, "output"));
6718 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006719 hlua_http_msg_filter(L, 1, msg, &output, &input);
6720 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006721 return 1;
6722}
6723
6724/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6725 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006726 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006727 * block. This function is called during the payload filtering, so the headers
6728 * are already scheduled for output (from the filter point of view).
6729 */
6730static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6731{
6732 struct htx *htx = htxbuf(&msg->chn->buf);
6733 struct htx_blk *blk;
6734 struct htx_ret htxret;
6735 luaL_Buffer b;
6736 int ret = 0;
6737
6738 luaL_buffinit(L, &b);
6739 htxret = htx_find_offset(htx, offset);
6740 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6741 enum htx_blk_type type = htx_get_blk_type(blk);
6742 struct ist v;
6743
6744 switch (type) {
6745 case HTX_BLK_UNUSED:
6746 break;
6747
6748 case HTX_BLK_DATA:
6749 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006750 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006751 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006752
6753 luaL_addlstring(&b, v.ptr, v.len);
6754 ret += v.len;
6755 break;
6756
6757 default:
vishnu0af4bd72021-10-24 06:46:24 +05306758 if (!ret)
6759 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006760 goto end;
6761 }
6762 offset = 0;
6763 }
6764
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006765end:
vishnu0af4bd72021-10-24 06:46:24 +05306766 if (!ret && (htx->flags & HTX_FL_EOM))
6767 goto no_data;
6768 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006769 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306770
6771 no_data:
6772 /* Remove the empty string and push nil on the stack */
6773 lua_pop(L, 1);
6774 lua_pushnil(L);
6775 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006776}
6777
6778/* Copies the string <str> to the HTTP message <msg> at the offset
6779 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006780 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006781 * the filter context.
6782 */
6783static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6784{
6785 struct htx *htx = htx_from_buf(&msg->chn->buf);
6786 struct htx_ret htxret;
6787 int /*max, */ret = 0;
6788
6789 /* Nothing to do, just return */
6790 if (unlikely(istlen(str) == 0))
6791 goto end;
6792
6793 if (istlen(str) > htx_free_data_space(htx)) {
6794 ret = -1;
6795 goto end;
6796 }
6797
6798 htxret = htx_find_offset(htx, offset);
6799 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6800 if (!htx_add_last_data(htx, str))
6801 goto end;
6802 }
6803 else {
6804 struct ist v = htx_get_blk_value(htx, htxret.blk);
6805 v.ptr += htxret.ret;
6806 v.len = 0;
6807 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6808 goto end;
6809 }
6810 ret = str.len;
6811 if (ret) {
6812 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6813 flt_update_offsets(filter, msg->chn, ret);
6814 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6815 }
6816
6817 end:
6818 htx_to_buf(htx, &msg->chn->buf);
6819 return ret;
6820}
6821
6822/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6823 * position <offset>. It stops on the first non-DATA HTX block. This function is
6824 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006825 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006826 * update the filter context.
6827 */
6828static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6829{
6830 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6831 struct htx *htx = htx_from_buf(&msg->chn->buf);
6832 struct htx_blk *blk;
6833 struct htx_ret htxret;
6834 size_t ret = 0;
6835
6836 /* Be sure <len> is always the amount of DATA to remove */
6837 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006838 /* When htx tail type == HTX_BLK_DATA, no need to take care
6839 * of special blocks like HTX_BLK_EOT.
6840 * We simply truncate after offset
6841 * (truncate targeted blk and discard the following ones)
6842 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006843 htx_truncate(htx, offset);
6844 ret = len;
6845 goto end;
6846 }
6847
6848 htxret = htx_find_offset(htx, offset);
6849 blk = htxret.blk;
6850 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006851 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006852 struct ist v;
6853
6854 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6855 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006856
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006857 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006858 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006859
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006860 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006861 /* trimming data in blk: discard everything after the offset
6862 * (replace 'v' with 'IST_NULL')
6863 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006864 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006865 if (blk && v.len < len) {
6866 /* In this case, caller wants to keep removing data,
6867 * but we need to spare current blk
6868 * because it was already trimmed
6869 */
6870 blk = htx_get_next_blk(htx, blk);
6871 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006872 len -= v.len;
6873 ret += v.len;
6874 }
6875
6876
6877 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006878 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006879 enum htx_blk_type type = htx_get_blk_type(blk);
6880 uint32_t sz = htx_get_blksz(blk);
6881
6882 switch (type) {
6883 case HTX_BLK_UNUSED:
6884 break;
6885
6886 case HTX_BLK_DATA:
6887 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006888 /* don't discard whole blk, only part of it
6889 * (from the beginning)
6890 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006891 htx_cut_data_blk(htx, blk, len);
6892 ret += len;
6893 goto end;
6894 }
6895 break;
6896
6897 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006898 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006899 goto end;
6900 }
6901
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006902 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006903 len -= sz;
6904 ret += sz;
6905 blk = htx_remove_blk(htx, blk);
6906 }
6907
6908end:
6909 flt_update_offsets(filter, msg->chn, -ret);
6910 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6911 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6912 * to loose the EOM flag if the message is empty.
6913 */
6914}
6915
6916/* Copies input data found in an HTTP message. Unlike the channel function used
6917 * to duplicate raw data, this one can only be called inside a filter, from
6918 * http_payload callback. So it cannot yield. An exception is returned if it is
6919 * called from another callback. If nothing was copied, a nil value is pushed on
6920 * the stack.
6921 */
6922__LJMP static int hlua_http_msg_get_body(lua_State *L)
6923{
6924 struct http_msg *msg;
6925 struct filter *filter;
6926 size_t output, input;
6927 int offset, len;
6928
6929 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6930 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6931 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6932
6933 if (msg->msg_state < HTTP_MSG_DATA)
6934 WILL_LJMP(lua_error(L));
6935
6936 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6937 if (!filter || !hlua_filter_from_payload(filter))
6938 WILL_LJMP(lua_error(L));
6939
6940 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6941 lua_pushnil(L);
6942 return 1;
6943 }
6944
6945 offset = output;
6946 if (lua_gettop(L) > 1) {
6947 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6948 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006949 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006950 offset += output;
6951 if (offset < output || offset > input + output) {
6952 lua_pushfstring(L, "offset out of range.");
6953 WILL_LJMP(lua_error(L));
6954 }
6955 }
6956 len = output + input - offset;
6957 if (lua_gettop(L) == 3) {
6958 len = MAY_LJMP(luaL_checkinteger(L, 3));
6959 if (!len)
6960 goto dup;
6961 if (len == -1)
6962 len = global.tune.bufsize;
6963 if (len < 0) {
6964 lua_pushfstring(L, "length out of range.");
6965 WILL_LJMP(lua_error(L));
6966 }
6967 }
6968
6969 dup:
6970 _hlua_http_msg_dup(msg, L, offset, len);
6971 return 1;
6972}
6973
6974/* Appends a string to the HTTP message, after all existing DATA blocks but
6975 * before the trailers, if any. It returns the amount of data written or -1 if
6976 * nothing was copied. Unlike the channel function used to append data, this one
6977 * can only be called inside a filter, from http_payload callback. So it cannot
6978 * yield. An exception is returned if it is called from another callback.
6979 */
6980__LJMP static int hlua_http_msg_append(lua_State *L)
6981{
6982 struct http_msg *msg;
6983 struct filter *filter;
6984 const char *str;
6985 size_t offset, len, sz;
6986 int ret;
6987
6988 MAY_LJMP(check_args(L, 2, "append"));
6989 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6990
6991 if (msg->msg_state < HTTP_MSG_DATA)
6992 WILL_LJMP(lua_error(L));
6993
6994 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6995 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6996 if (!filter || !hlua_filter_from_payload(filter))
6997 WILL_LJMP(lua_error(L));
6998
6999 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
7000 lua_pushinteger(L, ret);
7001 return 1;
7002}
7003
7004/* Prepends a string to the HTTP message, before all existing DATA blocks. It
7005 * returns the amount of data written or -1 if nothing was copied. Unlike the
7006 * channel function used to prepend data, this one can only be called inside a
7007 * filter, from http_payload callback. So it cannot yield. An exception is
7008 * returned if it is called from another callback.
7009 */
7010__LJMP static int hlua_http_msg_prepend(lua_State *L)
7011{
7012 struct http_msg *msg;
7013 struct filter *filter;
7014 const char *str;
7015 size_t offset, len, sz;
7016 int ret;
7017
7018 MAY_LJMP(check_args(L, 2, "prepend"));
7019 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007020
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007021 if (msg->msg_state < HTTP_MSG_DATA)
7022 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007023
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007024 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7025 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7026 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007027 WILL_LJMP(lua_error(L));
7028
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007029 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7030 lua_pushinteger(L, ret);
7031 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007032}
7033
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007034/* Inserts a string to the HTTP message at a given offset. By default the string
7035 * is appended at the end of DATA blocks. It returns the amount of data written
7036 * or -1 if nothing was copied. Unlike the channel function used to insert data,
7037 * this one can only be called inside a filter, from http_payload callback. So
7038 * it cannot yield. An exception is returned if it is called from another
7039 * callback.
7040 */
7041__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007042{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007043 struct http_msg *msg;
7044 struct filter *filter;
7045 const char *str;
7046 size_t input, output, sz;
7047 int offset;
7048 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007049
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007050 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
7051 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007052 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007053
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007054 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007055 WILL_LJMP(lua_error(L));
7056
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007057 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007058 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007059 if (!filter || !hlua_filter_from_payload(filter))
7060 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007061
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007062 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007063 if (lua_gettop(L) > 2) {
7064 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7065 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007066 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007067 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007068 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007069 lua_pushfstring(L, "offset out of range.");
7070 WILL_LJMP(lua_error(L));
7071 }
7072 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007073
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007074 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7075 lua_pushinteger(L, ret);
7076 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007077}
7078
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007079/* Removes a given amount of data from the HTTP message at a given offset. By
7080 * default all DATA blocks are removed. It returns the amount of data
7081 * removed. Unlike the channel function used to remove data, this one can only
7082 * be called inside a filter, from http_payload callback. So it cannot yield. An
7083 * exception is returned if it is called from another callback.
7084 */
7085__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007086{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007087 struct http_msg *msg;
7088 struct filter *filter;
7089 size_t input, output;
7090 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007091
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007092 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00007093 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007094 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007095
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007096 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007097 WILL_LJMP(lua_error(L));
7098
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007099 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007100 if (!filter || !hlua_filter_from_payload(filter))
7101 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007102
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007103 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00007104 if (lua_gettop(L) > 1) {
7105 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007106 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007107 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007108 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007109 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007110 lua_pushfstring(L, "offset out of range.");
7111 WILL_LJMP(lua_error(L));
7112 }
7113 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007114
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007115 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00007116 if (lua_gettop(L) == 3) {
7117 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007118 if (!len)
7119 goto end;
7120 if (len == -1)
7121 len = output + input - offset;
7122 if (len < 0 || offset + len > output + input) {
7123 lua_pushfstring(L, "length out of range.");
7124 WILL_LJMP(lua_error(L));
7125 }
7126 }
7127
7128 _hlua_http_msg_delete(msg, filter, offset, len);
7129
7130 end:
7131 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007132 return 1;
7133}
7134
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007135/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007136 * all remaining data are removed, accordingly to the filter context. It returns
7137 * the amount of data written or -1 if nothing was copied. Unlike the channel
7138 * function used to replace data, this one can only be called inside a filter,
7139 * from http_payload callback. So it cannot yield. An exception is returned if
7140 * it is called from another callback.
7141 */
7142__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007143{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007144 struct http_msg *msg;
7145 struct filter *filter;
7146 struct htx *htx;
7147 const char *str;
7148 size_t input, output, sz;
7149 int offset, len;
7150 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007151
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007152 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7153 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7154 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7155
7156 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007157 WILL_LJMP(lua_error(L));
7158
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007159 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7160 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7161 if (!filter || !hlua_filter_from_payload(filter))
7162 WILL_LJMP(lua_error(L));
7163
7164 offset = output;
7165 if (lua_gettop(L) > 2) {
7166 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7167 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007168 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007169 offset += output;
7170 if (offset < output || offset > input + output) {
7171 lua_pushfstring(L, "offset out of range.");
7172 WILL_LJMP(lua_error(L));
7173 }
7174 }
7175
7176 len = output + input - offset;
7177 if (lua_gettop(L) == 4) {
7178 len = MAY_LJMP(luaL_checkinteger(L, 4));
7179 if (!len)
7180 goto set;
7181 if (len == -1)
7182 len = output + input - offset;
7183 if (len < 0 || offset + len > output + input) {
7184 lua_pushfstring(L, "length out of range.");
7185 WILL_LJMP(lua_error(L));
7186 }
7187 }
7188
7189 set:
7190 /* Be sure we can copied the string once input data will be removed. */
7191 htx = htx_from_buf(&msg->chn->buf);
7192 if (sz > htx_free_data_space(htx) + len)
7193 lua_pushinteger(L, -1);
7194 else {
7195 _hlua_http_msg_delete(msg, filter, offset, len);
7196 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7197 lua_pushinteger(L, ret);
7198 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007199 return 1;
7200}
7201
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007202/* Prepends data into an HTTP message and forward it, from the filter point of
7203 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7204 * the channel function used to send data, this one can only be called inside a
7205 * filter, from http_payload callback. So it cannot yield. An exception is
7206 * returned if it is called from another callback.
7207 */
7208__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007209{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007210 struct http_msg *msg;
7211 struct filter *filter;
7212 struct htx *htx;
7213 const char *str;
7214 size_t offset, len, sz;
7215 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007216
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007217 MAY_LJMP(check_args(L, 2, "send"));
7218 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7219
7220 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007221 WILL_LJMP(lua_error(L));
7222
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007223 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7224 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7225 if (!filter || !hlua_filter_from_payload(filter))
7226 WILL_LJMP(lua_error(L));
7227
7228 /* Return an error if the channel's output is closed */
7229 if (unlikely(channel_output_closed(msg->chn))) {
7230 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007231 return 1;
7232 }
7233
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007234 htx = htx_from_buf(&msg->chn->buf);
7235 if (sz > htx_free_data_space(htx)) {
7236 lua_pushinteger(L, -1);
7237 return 1;
7238 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007239
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007240 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7241 if (ret > 0) {
7242 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7243
7244 FLT_OFF(filter, msg->chn) += ret;
7245 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7246 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7247 }
7248
7249 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007250 return 1;
7251}
7252
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007253/* Forwards a given amount of bytes. It return -1 if the channel's output is
7254 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7255 * channel function used to forward data, this one can only be called inside a
7256 * filter, from http_payload callback. So it cannot yield. An exception is
7257 * returned if it is called from another callback. All other functions deal with
7258 * DATA block, this one not.
7259*/
7260__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007261{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007262 struct http_msg *msg;
7263 struct filter *filter;
7264 size_t offset, len;
7265 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007266
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007267 MAY_LJMP(check_args(L, 2, "forward"));
7268 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7269
7270 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007271 WILL_LJMP(lua_error(L));
7272
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007273 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7274 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7275 if (!filter || !hlua_filter_from_payload(filter))
7276 WILL_LJMP(lua_error(L));
7277
7278 /* Nothing to do, just return */
7279 if (!fwd)
7280 goto end;
7281
7282 /* Return an error if the channel's output is closed */
7283 if (unlikely(channel_output_closed(msg->chn))) {
7284 ret = -1;
7285 goto end;
7286 }
7287
7288 ret = fwd;
7289 if (ret > len)
7290 ret = len;
7291
7292 if (ret) {
7293 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7294
7295 FLT_OFF(filter, msg->chn) += ret;
7296 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7297 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7298 }
7299
7300 end:
7301 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007302 return 1;
7303}
7304
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007305/* Set EOM flag on the HTX message.
7306 *
7307 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7308 * really know how to do without this feature.
7309 */
7310__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007311{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007312 struct http_msg *msg;
7313 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007314
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007315 MAY_LJMP(check_args(L, 1, "set_eom"));
7316 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7317 htx = htxbuf(&msg->chn->buf);
7318 htx->flags |= HTX_FL_EOM;
7319 return 0;
7320}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007321
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007322/* Unset EOM flag on the HTX message.
7323 *
7324 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7325 * really know how to do without this feature.
7326 */
7327__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7328{
7329 struct http_msg *msg;
7330 struct htx *htx;
7331
7332 MAY_LJMP(check_args(L, 1, "set_eom"));
7333 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7334 htx = htxbuf(&msg->chn->buf);
7335 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007336 return 0;
7337}
7338
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007339/*
7340 *
7341 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007342 * Class HTTPClient
7343 *
7344 *
7345 */
7346__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7347{
7348 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7349}
7350
William Lallemandf77f1de2021-09-28 19:10:38 +02007351
7352/* stops the httpclient and ask it to kill itself */
7353__LJMP static int hlua_httpclient_gc(lua_State *L)
7354{
7355 struct hlua_httpclient *hlua_hc;
7356
7357 MAY_LJMP(check_args(L, 1, "__gc"));
7358
7359 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7360
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007361 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7362 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007363 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007364 hlua_hc->hc = NULL;
7365 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007366
7367 return 0;
7368}
7369
7370
William Lallemand3956c4e2021-09-21 16:25:15 +02007371__LJMP static int hlua_httpclient_new(lua_State *L)
7372{
7373 struct hlua_httpclient *hlua_hc;
7374 struct hlua *hlua;
7375
7376 /* Get hlua struct, or NULL if we execute from main lua state */
7377 hlua = hlua_gethlua(L);
7378 if (!hlua)
7379 return 0;
7380
7381 /* Check stack size. */
7382 if (!lua_checkstack(L, 3)) {
7383 hlua_pusherror(L, "httpclient: full stack");
7384 goto err;
7385 }
7386 /* Create the object: obj[0] = userdata. */
7387 lua_newtable(L);
7388 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7389 lua_rawseti(L, -2, 0);
7390 memset(hlua_hc, 0, sizeof(*hlua_hc));
7391
7392 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7393 if (!hlua_hc->hc)
7394 goto err;
7395
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007396 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007397
William Lallemand3956c4e2021-09-21 16:25:15 +02007398 /* Pop a class stream metatable and affect it to the userdata. */
7399 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7400 lua_setmetatable(L, -2);
7401
7402 return 1;
7403
7404 err:
7405 WILL_LJMP(lua_error(L));
7406 return 0;
7407}
7408
7409
7410/*
7411 * Callback of the httpclient, this callback wakes the lua task up, once the
7412 * httpclient receives some data
7413 *
7414 */
7415
William Lallemandbd5739e2021-10-28 15:41:38 +02007416static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007417{
7418 struct hlua *hlua = hc->caller;
7419
7420 if (!hlua || !hlua->task)
7421 return;
7422
7423 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7424}
7425
7426/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007427 * Fill the lua stack with headers from the httpclient response
7428 * This works the same way as the hlua_http_get_headers() function
7429 */
7430__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7431{
7432 struct http_hdr *hdr;
7433
7434 lua_newtable(L);
7435
William Lallemandef574b22021-10-05 16:19:31 +02007436 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007437 struct ist n, v;
7438 int len;
7439
7440 n = hdr->n;
7441 v = hdr->v;
7442
7443 /* Check for existing entry:
7444 * assume that the table is on the top of the stack, and
7445 * push the key in the stack, the function lua_gettable()
7446 * perform the lookup.
7447 */
7448
7449 lua_pushlstring(L, n.ptr, n.len);
7450 lua_gettable(L, -2);
7451
7452 switch (lua_type(L, -1)) {
7453 case LUA_TNIL:
7454 /* Table not found, create it. */
7455 lua_pop(L, 1); /* remove the nil value. */
7456 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7457 lua_newtable(L); /* create and push empty table. */
7458 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7459 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7460 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7461 break;
7462
7463 case LUA_TTABLE:
7464 /* Entry found: push the value in the table. */
7465 len = lua_rawlen(L, -1);
7466 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7467 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7468 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7469 break;
7470
7471 default:
7472 /* Other cases are errors. */
7473 hlua_pusherror(L, "internal error during the parsing of headers.");
7474 WILL_LJMP(lua_error(L));
7475 }
7476 }
7477 return 1;
7478}
7479
7480/*
William Lallemand746e6f32021-10-06 10:57:44 +02007481 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7482 *
7483 * Caller must free the result
7484 */
7485struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7486{
7487 struct http_hdr hdrs[global.tune.max_http_hdr];
7488 struct http_hdr *result = NULL;
7489 uint32_t hdr_num = 0;
7490
7491 lua_pushnil(L);
7492 while (lua_next(L, -2) != 0) {
7493 struct ist name, value;
7494 const char *n, *v;
7495 size_t nlen, vlen;
7496
7497 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7498 /* Skip element if the key is not a string or if the value is not a table */
7499 goto next_hdr;
7500 }
7501
7502 n = lua_tolstring(L, -2, &nlen);
7503 name = ist2(n, nlen);
7504
7505 /* Loop on header's values */
7506 lua_pushnil(L);
7507 while (lua_next(L, -2)) {
7508 if (!lua_isstring(L, -1)) {
7509 /* Skip the value if it is not a string */
7510 goto next_value;
7511 }
7512
7513 v = lua_tolstring(L, -1, &vlen);
7514 value = ist2(v, vlen);
7515 name = ist2(n, nlen);
7516
7517 hdrs[hdr_num].n = istdup(name);
7518 hdrs[hdr_num].v = istdup(value);
7519
7520 hdr_num++;
7521
7522 next_value:
7523 lua_pop(L, 1);
7524 }
7525
7526 next_hdr:
7527 lua_pop(L, 1);
7528
7529 }
7530
7531 if (hdr_num) {
7532 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007533 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007534 if (!result)
7535 goto skip_headers;
7536 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7537
7538 result[hdr_num].n = IST_NULL;
7539 result[hdr_num].v = IST_NULL;
7540 }
7541
7542skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007543
7544 return result;
7545}
7546
7547
William Lallemandbd5739e2021-10-28 15:41:38 +02007548/*
7549 * For each yield, checks if there is some data in the httpclient and push them
7550 * in the lua buffer, once the httpclient finished its job, push the result on
7551 * the stack
7552 */
7553__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7554{
7555 struct buffer *tr;
7556 int res;
7557 struct hlua *hlua = hlua_gethlua(L);
7558 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7559
7560
7561 tr = get_trash_chunk();
7562
7563 res = httpclient_res_xfer(hlua_hc->hc, tr);
7564 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7565
7566 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7567
7568 luaL_pushresult(&hlua_hc->b);
7569 lua_settable(L, -3);
7570
7571 lua_pushstring(L, "status");
7572 lua_pushinteger(L, hlua_hc->hc->res.status);
7573 lua_settable(L, -3);
7574
7575
7576 lua_pushstring(L, "reason");
7577 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7578 lua_settable(L, -3);
7579
7580 lua_pushstring(L, "headers");
7581 hlua_httpclient_get_headers(L, hlua_hc);
7582 lua_settable(L, -3);
7583
7584 return 1;
7585 }
7586
7587 if (httpclient_data(hlua_hc->hc))
7588 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7589
7590 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7591
7592 return 0;
7593}
7594
7595/*
7596 * Call this when trying to stream a body during a request
7597 */
7598__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7599{
7600 struct hlua *hlua;
7601 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7602 const char *body_str = NULL;
7603 int ret;
7604 int end = 0;
7605 size_t buf_len;
7606 size_t to_send = 0;
7607
7608 hlua = hlua_gethlua(L);
7609
7610 if (!hlua || !hlua->task)
7611 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7612 "'frontend', 'backend' or 'task'"));
7613
7614 ret = lua_getfield(L, -1, "body");
7615 if (ret != LUA_TSTRING)
7616 goto rcv;
7617
7618 body_str = lua_tolstring(L, -1, &buf_len);
7619 lua_pop(L, 1);
7620
Christopher Fauletfc591292022-01-12 14:46:03 +01007621 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007622
7623 if ((hlua_hc->sent + to_send) >= buf_len)
7624 end = 1;
7625
7626 /* the end flag is always set since we are using the whole remaining size */
7627 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7628
7629 if (buf_len > hlua_hc->sent) {
7630 /* still need to process the buffer */
7631 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7632 } else {
7633 goto rcv;
7634 /* we sent the whole request buffer we can recv */
7635 }
7636 return 0;
7637
7638rcv:
7639
7640 /* we return a "res" object */
7641 lua_newtable(L);
7642
William Lallemandbd5739e2021-10-28 15:41:38 +02007643 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007644 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007645
William Lallemand933fe392021-11-04 09:45:58 +01007646 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007647 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7648
7649 return 1;
7650}
William Lallemand746e6f32021-10-06 10:57:44 +02007651
William Lallemand3956c4e2021-09-21 16:25:15 +02007652/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007653 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007654 */
7655
William Lallemanddc2cc902021-10-26 11:43:26 +02007656__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007657{
7658 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007659 struct http_hdr *hdrs = NULL;
7660 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007661 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007662 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007663 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007664 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007665 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007666
7667 hlua = hlua_gethlua(L);
7668
7669 if (!hlua || !hlua->task)
7670 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7671 "'frontend', 'backend' or 'task'"));
7672
William Lallemand746e6f32021-10-06 10:57:44 +02007673 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7674 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7675
William Lallemand4f4f2b72022-02-17 20:00:23 +01007676 hlua_hc = hlua_checkhttpclient(L, 1);
7677
William Lallemand7177a952022-03-03 15:33:12 +01007678 lua_pushnil(L); /* first key */
7679 while (lua_next(L, 2)) {
7680 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7681 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7682 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007683
William Lallemand7177a952022-03-03 15:33:12 +01007684 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7685 if (lua_type(L, -1) != LUA_TSTRING)
7686 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7687 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007688
William Lallemand7177a952022-03-03 15:33:12 +01007689 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7690 if (lua_type(L, -1) != LUA_TNUMBER)
7691 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7692 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007693
William Lallemand7177a952022-03-03 15:33:12 +01007694 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7695 if (lua_type(L, -1) != LUA_TTABLE)
7696 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7697 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007698
William Lallemand7177a952022-03-03 15:33:12 +01007699 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7700 if (lua_type(L, -1) != LUA_TSTRING)
7701 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7702 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007703
William Lallemand7177a952022-03-03 15:33:12 +01007704 } else {
7705 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7706 }
7707 /* removes 'value'; keeps 'key' for next iteration */
7708 lua_pop(L, 1);
7709 }
William Lallemanddec25c32021-10-25 19:48:37 +02007710
William Lallemand746e6f32021-10-06 10:57:44 +02007711 if (!url_str) {
7712 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7713 return 0;
7714 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007715
William Lallemand10a37362022-03-02 16:18:26 +01007716 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007717
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007718 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007719 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007720 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007721
7722 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007723 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7724 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7725 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007726 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007727
William Lallemandbd5739e2021-10-28 15:41:38 +02007728 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007729 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007730 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7731 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007732
William Lallemandbd5739e2021-10-28 15:41:38 +02007733 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007734
William Lallemand746e6f32021-10-06 10:57:44 +02007735 /* free the temporary headers array */
7736 hdrs_i = hdrs;
7737 while (hdrs_i && isttest(hdrs_i->n)) {
7738 istfree(&hdrs_i->n);
7739 istfree(&hdrs_i->v);
7740 hdrs_i++;
7741 }
7742 ha_free(&hdrs);
7743
7744
William Lallemand6137a9e2021-10-26 15:01:53 +02007745 if (ret != ERR_NONE) {
7746 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7747 return 0;
7748 }
7749
William Lallemandc2d3db42022-04-26 11:46:13 +02007750 if (!httpclient_start(hlua_hc->hc))
7751 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007752
William Lallemandbd5739e2021-10-28 15:41:38 +02007753 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007754
William Lallemand3956c4e2021-09-21 16:25:15 +02007755 return 0;
7756}
7757
7758/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007759 * Sends an HTTP HEAD request and wait for a response
7760 *
7761 * httpclient:head(url, headers, payload)
7762 */
7763__LJMP static int hlua_httpclient_head(lua_State *L)
7764{
7765 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7766}
7767
7768/*
7769 * Send an HTTP GET request and wait for a response
7770 *
7771 * httpclient:get(url, headers, payload)
7772 */
7773__LJMP static int hlua_httpclient_get(lua_State *L)
7774{
7775 return hlua_httpclient_send(L, HTTP_METH_GET);
7776
7777}
7778
7779/*
7780 * Sends an HTTP PUT request and wait for a response
7781 *
7782 * httpclient:put(url, headers, payload)
7783 */
7784__LJMP static int hlua_httpclient_put(lua_State *L)
7785{
7786 return hlua_httpclient_send(L, HTTP_METH_PUT);
7787}
7788
7789/*
7790 * Send an HTTP POST request and wait for a response
7791 *
7792 * httpclient:post(url, headers, payload)
7793 */
7794__LJMP static int hlua_httpclient_post(lua_State *L)
7795{
7796 return hlua_httpclient_send(L, HTTP_METH_POST);
7797}
7798
7799
7800/*
7801 * Sends an HTTP DELETE request and wait for a response
7802 *
7803 * httpclient:delete(url, headers, payload)
7804 */
7805__LJMP static int hlua_httpclient_delete(lua_State *L)
7806{
7807 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7808}
7809
7810/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007811 *
7812 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007813 * Class TXN
7814 *
7815 *
7816 */
7817
7818/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007819 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007820 */
7821__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7822{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007823 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007824}
7825
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007826__LJMP static int hlua_set_var(lua_State *L)
7827{
7828 struct hlua_txn *htxn;
7829 const char *name;
7830 size_t len;
7831 struct sample smp;
7832
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007833 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7834 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007835
7836 /* It is useles to retrieve the stream, but this function
7837 * runs only in a stream context.
7838 */
7839 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7840 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7841
7842 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007843 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007844 hlua_lua2smp(L, 3, &smp);
7845
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02007846 /* Store the sample in a variable. We don't need to dup the smp, vars API
7847 * already takes care of duplicating dynamic var data.
7848 */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007849 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007850
7851 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7852 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7853 else
7854 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7855
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007856 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007857}
7858
Christopher Faulet85d79c92016-11-09 16:54:56 +01007859__LJMP static int hlua_unset_var(lua_State *L)
7860{
7861 struct hlua_txn *htxn;
7862 const char *name;
7863 size_t len;
7864 struct sample smp;
7865
7866 MAY_LJMP(check_args(L, 2, "unset_var"));
7867
7868 /* It is useles to retrieve the stream, but this function
7869 * runs only in a stream context.
7870 */
7871 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7872 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7873
7874 /* Unset the variable. */
7875 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007876 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7877 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007878}
7879
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007880__LJMP static int hlua_get_var(lua_State *L)
7881{
7882 struct hlua_txn *htxn;
7883 const char *name;
7884 size_t len;
7885 struct sample smp;
7886
7887 MAY_LJMP(check_args(L, 2, "get_var"));
7888
7889 /* It is useles to retrieve the stream, but this function
7890 * runs only in a stream context.
7891 */
7892 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7893 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7894
Willy Tarreau7560dd42016-03-10 16:28:58 +01007895 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007896 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007897 lua_pushnil(L);
7898 return 1;
7899 }
7900
Aurelien DARRAGON41217722023-05-17 10:44:47 +02007901 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007902}
7903
Willy Tarreau59551662015-03-10 14:23:13 +01007904__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007905{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007906 struct hlua *hlua;
7907
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007908 MAY_LJMP(check_args(L, 2, "set_priv"));
7909
Willy Tarreau87b09662015-04-03 00:22:06 +02007910 /* It is useles to retrieve the stream, but this function
7911 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007912 */
7913 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007914
7915 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007916 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007917 if (!hlua)
7918 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007919
7920 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007921 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007922
7923 /* Get and store new value. */
7924 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7925 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7926
7927 return 0;
7928}
7929
Willy Tarreau59551662015-03-10 14:23:13 +01007930__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007931{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007932 struct hlua *hlua;
7933
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007934 MAY_LJMP(check_args(L, 1, "get_priv"));
7935
Willy Tarreau87b09662015-04-03 00:22:06 +02007936 /* It is useles to retrieve the stream, but this function
7937 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007938 */
7939 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007940
7941 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007942 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007943 if (!hlua) {
7944 lua_pushnil(L);
7945 return 1;
7946 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007947
7948 /* Push configuration index in the stack. */
7949 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7950
7951 return 1;
7952}
7953
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007954/* Create stack entry containing a class TXN. This function
7955 * return 0 if the stack does not contains free slots,
7956 * otherwise it returns 1.
7957 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007958static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007959{
Willy Tarreaude491382015-04-06 11:04:28 +02007960 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007961
7962 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007963 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007964 return 0;
7965
7966 /* NOTE: The allocation never fails. The failure
7967 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007968 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007969 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007970 /* Create the object: obj[0] = userdata. */
7971 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007972 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007973 lua_rawseti(L, -2, 0);
7974
Willy Tarreaude491382015-04-06 11:04:28 +02007975 htxn->s = s;
7976 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007977 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007978 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007979
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007980 /* Create the "f" field that contains a list of fetches. */
7981 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007982 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007983 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007984 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007985
7986 /* Create the "sf" field that contains a list of stringsafe fetches. */
7987 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007988 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007989 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007990 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007991
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007992 /* Create the "c" field that contains a list of converters. */
7993 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007994 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007995 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007996 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007997
7998 /* Create the "sc" field that contains a list of stringsafe converters. */
7999 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01008000 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008001 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008002 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008003
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008004 /* Create the "req" field that contains the request channel object. */
8005 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01008006 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008007 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008008 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008009
8010 /* Create the "res" field that contains the response channel object. */
8011 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01008012 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008013 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008014 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01008015
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008016 /* Creates the HTTP object is the current proxy allows http. */
8017 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01008018 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02008019 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008020 return 0;
8021 }
8022 else
8023 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008024 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008025
Christopher Faulet78c35472020-02-26 17:14:08 +01008026 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
8027 /* HTTPMessage object are created when a lua TXN is created from
8028 * a filter context only
8029 */
8030
8031 /* Creates the HTTP-Request object is the current proxy allows http. */
8032 lua_pushstring(L, "http_req");
8033 if (p->mode == PR_MODE_HTTP) {
8034 if (!hlua_http_msg_new(L, &s->txn->req))
8035 return 0;
8036 }
8037 else
8038 lua_pushnil(L);
8039 lua_rawset(L, -3);
8040
8041 /* Creates the HTTP-Response object is the current proxy allows http. */
8042 lua_pushstring(L, "http_res");
8043 if (p->mode == PR_MODE_HTTP) {
8044 if (!hlua_http_msg_new(L, &s->txn->rsp))
8045 return 0;
8046 }
8047 else
8048 lua_pushnil(L);
8049 lua_rawset(L, -3);
8050 }
8051
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008052 /* Pop a class sesison metatable and affect it to the userdata. */
8053 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
8054 lua_setmetatable(L, -2);
8055
8056 return 1;
8057}
8058
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008059__LJMP static int hlua_txn_deflog(lua_State *L)
8060{
8061 const char *msg;
8062 struct hlua_txn *htxn;
8063
8064 MAY_LJMP(check_args(L, 2, "deflog"));
8065 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8066 msg = MAY_LJMP(luaL_checkstring(L, 2));
8067
8068 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
8069 return 0;
8070}
8071
8072__LJMP static int hlua_txn_log(lua_State *L)
8073{
8074 int level;
8075 const char *msg;
8076 struct hlua_txn *htxn;
8077
8078 MAY_LJMP(check_args(L, 3, "log"));
8079 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8080 level = MAY_LJMP(luaL_checkinteger(L, 2));
8081 msg = MAY_LJMP(luaL_checkstring(L, 3));
8082
8083 if (level < 0 || level >= NB_LOG_LEVELS)
8084 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8085
8086 hlua_sendlog(htxn->s->be, level, msg);
8087 return 0;
8088}
8089
8090__LJMP static int hlua_txn_log_debug(lua_State *L)
8091{
8092 const char *msg;
8093 struct hlua_txn *htxn;
8094
8095 MAY_LJMP(check_args(L, 2, "Debug"));
8096 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8097 msg = MAY_LJMP(luaL_checkstring(L, 2));
8098 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
8099 return 0;
8100}
8101
8102__LJMP static int hlua_txn_log_info(lua_State *L)
8103{
8104 const char *msg;
8105 struct hlua_txn *htxn;
8106
8107 MAY_LJMP(check_args(L, 2, "Info"));
8108 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8109 msg = MAY_LJMP(luaL_checkstring(L, 2));
8110 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
8111 return 0;
8112}
8113
8114__LJMP static int hlua_txn_log_warning(lua_State *L)
8115{
8116 const char *msg;
8117 struct hlua_txn *htxn;
8118
8119 MAY_LJMP(check_args(L, 2, "Warning"));
8120 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8121 msg = MAY_LJMP(luaL_checkstring(L, 2));
8122 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
8123 return 0;
8124}
8125
8126__LJMP static int hlua_txn_log_alert(lua_State *L)
8127{
8128 const char *msg;
8129 struct hlua_txn *htxn;
8130
8131 MAY_LJMP(check_args(L, 2, "Alert"));
8132 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8133 msg = MAY_LJMP(luaL_checkstring(L, 2));
8134 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8135 return 0;
8136}
8137
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008138__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8139{
8140 struct hlua_txn *htxn;
8141 int ll;
8142
8143 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8144 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8145 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8146
8147 if (ll < 0 || ll > 7)
8148 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
8149
8150 htxn->s->logs.level = ll;
8151 return 0;
8152}
8153
8154__LJMP static int hlua_txn_set_tos(lua_State *L)
8155{
8156 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008157 int tos;
8158
8159 MAY_LJMP(check_args(L, 2, "set_tos"));
8160 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8161 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8162
Willy Tarreau1a18b542018-12-11 16:37:42 +01008163 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008164 return 0;
8165}
8166
8167__LJMP static int hlua_txn_set_mark(lua_State *L)
8168{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008169 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008170 int mark;
8171
8172 MAY_LJMP(check_args(L, 2, "set_mark"));
8173 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8174 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8175
Lukas Tribus579e3e32019-08-11 18:03:45 +02008176 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008177 return 0;
8178}
8179
Patrick Hemmer268a7072018-05-11 12:52:31 -04008180__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8181{
8182 struct hlua_txn *htxn;
8183
8184 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8185 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8186 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8187 return 0;
8188}
8189
8190__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8191{
8192 struct hlua_txn *htxn;
8193
8194 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8195 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8196 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8197 return 0;
8198}
8199
Christopher Faulet700d9e82020-01-31 12:21:52 +01008200/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008201 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008202 * message and terminate the transaction. It returns 1 on success and 0 on
8203 * error. The Reply must be on top of the stack.
8204 */
8205__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8206{
8207 struct htx *htx;
8208 struct htx_sl *sl;
8209 struct h1m h1m;
8210 const char *status, *reason, *body;
8211 size_t status_len, reason_len, body_len;
8212 int ret, code, flags;
8213
8214 code = 200;
8215 status = "200";
8216 status_len = 3;
8217 ret = lua_getfield(L, -1, "status");
8218 if (ret == LUA_TNUMBER) {
8219 code = lua_tointeger(L, -1);
8220 status = lua_tolstring(L, -1, &status_len);
8221 }
8222 lua_pop(L, 1);
8223
8224 reason = http_get_reason(code);
8225 reason_len = strlen(reason);
8226 ret = lua_getfield(L, -1, "reason");
8227 if (ret == LUA_TSTRING)
8228 reason = lua_tolstring(L, -1, &reason_len);
8229 lua_pop(L, 1);
8230
8231 body = NULL;
8232 body_len = 0;
8233 ret = lua_getfield(L, -1, "body");
8234 if (ret == LUA_TSTRING)
8235 body = lua_tolstring(L, -1, &body_len);
8236 lua_pop(L, 1);
8237
8238 /* Prepare the response before inserting the headers */
8239 h1m_init_res(&h1m);
8240 htx = htx_from_buf(&s->res.buf);
8241 channel_htx_truncate(&s->res, htx);
8242 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8243 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8244 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8245 ist2(status, status_len), ist2(reason, reason_len));
8246 }
8247 else {
8248 flags = HTX_SL_F_IS_RESP;
8249 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8250 ist2(status, status_len), ist2(reason, reason_len));
8251 }
8252 if (!sl)
8253 goto fail;
8254 sl->info.res.status = code;
8255
8256 /* Push in the stack the "headers" entry. */
8257 ret = lua_getfield(L, -1, "headers");
8258 if (ret != LUA_TTABLE)
8259 goto skip_headers;
8260
8261 lua_pushnil(L);
8262 while (lua_next(L, -2) != 0) {
8263 struct ist name, value;
8264 const char *n, *v;
8265 size_t nlen, vlen;
8266
8267 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8268 /* Skip element if the key is not a string or if the value is not a table */
8269 goto next_hdr;
8270 }
8271
8272 n = lua_tolstring(L, -2, &nlen);
8273 name = ist2(n, nlen);
8274 if (isteqi(name, ist("content-length"))) {
8275 /* Always skip content-length header. It will be added
8276 * later with the correct len
8277 */
8278 goto next_hdr;
8279 }
8280
8281 /* Loop on header's values */
8282 lua_pushnil(L);
8283 while (lua_next(L, -2)) {
8284 if (!lua_isstring(L, -1)) {
8285 /* Skip the value if it is not a string */
8286 goto next_value;
8287 }
8288
8289 v = lua_tolstring(L, -1, &vlen);
8290 value = ist2(v, vlen);
8291
8292 if (isteqi(name, ist("transfer-encoding")))
8293 h1_parse_xfer_enc_header(&h1m, value);
8294 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8295 goto fail;
8296
8297 next_value:
8298 lua_pop(L, 1);
8299 }
8300
8301 next_hdr:
8302 lua_pop(L, 1);
8303 }
8304 skip_headers:
8305 lua_pop(L, 1);
8306
8307 /* Update h1m flags: CLEN is set if CHNK is not present */
8308 if (!(h1m.flags & H1_MF_CHNK)) {
8309 const char *clen = ultoa(body_len);
8310
8311 h1m.flags |= H1_MF_CLEN;
8312 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8313 goto fail;
8314 }
8315 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8316 h1m.flags |= H1_MF_XFER_LEN;
8317
8318 /* Update HTX start-line flags */
8319 if (h1m.flags & H1_MF_XFER_ENC)
8320 flags |= HTX_SL_F_XFER_ENC;
8321 if (h1m.flags & H1_MF_XFER_LEN) {
8322 flags |= HTX_SL_F_XFER_LEN;
8323 if (h1m.flags & H1_MF_CHNK)
8324 flags |= HTX_SL_F_CHNK;
8325 else if (h1m.flags & H1_MF_CLEN)
8326 flags |= HTX_SL_F_CLEN;
8327 if (h1m.body_len == 0)
8328 flags |= HTX_SL_F_BODYLESS;
8329 }
8330 sl->flags |= flags;
8331
8332
8333 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008334 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008335 goto fail;
8336
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008337 htx->flags |= HTX_FL_EOM;
8338
Christopher Faulet700d9e82020-01-31 12:21:52 +01008339 /* Now, forward the response and terminate the transaction */
8340 s->txn->status = code;
8341 htx_to_buf(htx, &s->res.buf);
8342 if (!http_forward_proxy_resp(s, 1))
8343 goto fail;
8344
8345 return 1;
8346
8347 fail:
8348 channel_htx_truncate(&s->res, htx);
8349 return 0;
8350}
8351
8352/* Terminate a transaction if called from a lua action. For TCP streams,
8353 * processing is just aborted. Nothing is returned to the client and all
8354 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8355 * is forwarded to the client before terminating the transaction. On success,
8356 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8357 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8358 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008359 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008360__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008361{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008362 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008363 struct stream *s;
8364 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008365
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008366 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008367
Christopher Faulet700d9e82020-01-31 12:21:52 +01008368 /* If the flags NOTERM is set, we cannot terminate the session, so we
8369 * just end the execution of the current lua code. */
8370 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008371 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008372
Christopher Faulet700d9e82020-01-31 12:21:52 +01008373 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008374 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008375 struct channel *req = &s->req;
8376 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008377
Christopher Faulet700d9e82020-01-31 12:21:52 +01008378 channel_auto_read(req);
8379 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008380 channel_erase(req);
8381
Christopher Faulet700d9e82020-01-31 12:21:52 +01008382 channel_auto_read(res);
8383 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008384 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008385
8386 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8387 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008388 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008389
Christopher Faulet700d9e82020-01-31 12:21:52 +01008390 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8391 /* No reply or invalid reply */
8392 s->txn->status = 0;
8393 http_reply_and_close(s, 0, NULL);
8394 }
8395 else {
8396 /* Remove extra args to have the reply on top of the stack */
8397 if (lua_gettop(L) > 2)
8398 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008399
Christopher Faulet700d9e82020-01-31 12:21:52 +01008400 if (!hlua_txn_forward_reply(L, s)) {
8401 if (!(s->flags & SF_ERR_MASK))
8402 s->flags |= SF_ERR_PRXCOND;
8403 lua_pushinteger(L, ACT_RET_ERR);
8404 WILL_LJMP(hlua_done(L));
8405 return 0; /* Never reached */
8406 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008407 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008408
Christopher Faulet700d9e82020-01-31 12:21:52 +01008409 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8410 if (htxn->dir == SMP_OPT_DIR_REQ) {
8411 /* let's log the request time */
Willy Tarreau69530f52023-04-28 09:16:15 +02008412 s->logs.request_ts = now_ns;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008413 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008414 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008415 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008416
Christopher Faulet700d9e82020-01-31 12:21:52 +01008417 done:
8418 if (!(s->flags & SF_ERR_MASK))
8419 s->flags |= SF_ERR_LOCAL;
8420 if (!(s->flags & SF_FINST_MASK))
8421 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008422
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008423 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8424 lua_pushinteger(L, -1);
8425 else
8426 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008427 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008428 return 0;
8429}
8430
Christopher Faulet700d9e82020-01-31 12:21:52 +01008431/*
8432 *
8433 *
8434 * Class REPLY
8435 *
8436 *
8437 */
8438
8439/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8440 * free slots, the function fails and returns 0;
8441 */
8442static int hlua_txn_reply_new(lua_State *L)
8443{
8444 struct hlua_txn *htxn;
8445 const char *reason, *body = NULL;
8446 int ret, status;
8447
8448 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008449 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008450 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8451 WILL_LJMP(lua_error(L));
8452 }
8453
8454 /* Default value */
8455 status = 200;
8456 reason = http_get_reason(status);
8457
8458 if (lua_istable(L, 2)) {
8459 /* load status and reason from the table argument at index 2 */
8460 ret = lua_getfield(L, 2, "status");
8461 if (ret == LUA_TNIL)
8462 goto reason;
8463 else if (ret != LUA_TNUMBER) {
8464 /* invalid status: ignore the reason */
8465 goto body;
8466 }
8467 status = lua_tointeger(L, -1);
8468
8469 reason:
8470 lua_pop(L, 1); /* restore the stack: remove status */
8471 ret = lua_getfield(L, 2, "reason");
8472 if (ret == LUA_TSTRING)
8473 reason = lua_tostring(L, -1);
8474
8475 body:
8476 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8477 ret = lua_getfield(L, 2, "body");
8478 if (ret == LUA_TSTRING)
8479 body = lua_tostring(L, -1);
8480 lua_pop(L, 1); /* restore the stack: remove body */
8481 }
8482
8483 /* Create the Reply table */
8484 lua_newtable(L);
8485
8486 /* Add status element */
8487 lua_pushstring(L, "status");
8488 lua_pushinteger(L, status);
8489 lua_settable(L, -3);
8490
8491 /* Add reason element */
8492 reason = http_get_reason(status);
8493 lua_pushstring(L, "reason");
8494 lua_pushstring(L, reason);
8495 lua_settable(L, -3);
8496
8497 /* Add body element, nil if undefined */
8498 lua_pushstring(L, "body");
8499 if (body)
8500 lua_pushstring(L, body);
8501 else
8502 lua_pushnil(L);
8503 lua_settable(L, -3);
8504
8505 /* Add headers element */
8506 lua_pushstring(L, "headers");
8507 lua_newtable(L);
8508
8509 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8510 if (lua_istable(L, 2)) {
8511 /* load headers from the table argument at index 2. If it is a table, copy it. */
8512 ret = lua_getfield(L, 2, "headers");
8513 if (ret == LUA_TTABLE) {
8514 /* stack: [ ... <headers:table>, <table> ] */
8515 lua_pushnil(L);
8516 while (lua_next(L, -2) != 0) {
8517 /* stack: [ ... <headers:table>, <table>, k, v] */
8518 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8519 /* invalid value type, skip it */
8520 lua_pop(L, 1);
8521 continue;
8522 }
8523
8524
8525 /* Duplicate the key and swap it with the value. */
8526 lua_pushvalue(L, -2);
8527 lua_insert(L, -2);
8528 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8529
8530 lua_newtable(L);
8531 lua_insert(L, -2);
8532 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8533
8534 if (lua_isstring(L, -1)) {
8535 /* push the value in the inner table */
8536 lua_rawseti(L, -2, 1);
8537 }
8538 else { /* table */
8539 lua_pushnil(L);
8540 while (lua_next(L, -2) != 0) {
8541 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8542 if (!lua_isstring(L, -1)) {
8543 /* invalid value type, skip it*/
8544 lua_pop(L, 1);
8545 continue;
8546 }
8547 /* push the value in the inner table */
8548 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8549 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8550 }
8551 lua_pop(L, 1);
8552 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8553 }
8554
8555 /* push (k,v) on the stack in the headers table:
8556 * stack: [ ... <headers:table>, <table>, k, k, v ]
8557 */
8558 lua_settable(L, -5);
8559 /* stack: [ ... <headers:table>, <table>, k ] */
8560 }
8561 }
8562 lua_pop(L, 1);
8563 }
8564 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8565 lua_settable(L, -3);
8566 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8567
8568 /* Pop a class sesison metatable and affect it to the userdata. */
8569 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8570 lua_setmetatable(L, -2);
8571 return 1;
8572}
8573
8574/* Set the reply status code, and optionally the reason. If no reason is
8575 * provided, the default one corresponding to the status code is used.
8576 */
8577__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8578{
8579 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8580 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8581
8582 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008583 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008584
8585 if (status < 100 || status > 599) {
8586 lua_pushboolean(L, 0);
8587 return 1;
8588 }
8589 if (!reason)
8590 reason = http_get_reason(status);
8591
8592 lua_pushinteger(L, status);
8593 lua_setfield(L, 1, "status");
8594
8595 lua_pushstring(L, reason);
8596 lua_setfield(L, 1, "reason");
8597
8598 lua_pushboolean(L, 1);
8599 return 1;
8600}
8601
8602/* Add a header into the reply object. Each header name is associated to an
8603 * array of values in the "headers" table. If the header name is not found, a
8604 * new entry is created.
8605 */
8606__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8607{
8608 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8609 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8610 int ret;
8611
8612 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008613 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008614
8615 /* Push in the stack the "headers" entry. */
8616 ret = lua_getfield(L, 1, "headers");
8617 if (ret != LUA_TTABLE) {
8618 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8619 WILL_LJMP(lua_error(L));
8620 }
8621
8622 /* check if the header is already registered. If not, register it. */
8623 ret = lua_getfield(L, -1, name);
8624 if (ret == LUA_TNIL) {
8625 /* Entry not found. */
8626 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8627
8628 /* Insert the new header name in the array in the top of the stack.
8629 * It left the new array in the top of the stack.
8630 */
8631 lua_newtable(L);
8632 lua_pushstring(L, name);
8633 lua_pushvalue(L, -2);
8634 lua_settable(L, -4);
8635 }
8636 else if (ret != LUA_TTABLE) {
8637 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8638 WILL_LJMP(lua_error(L));
8639 }
8640
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008641 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008642 * the header value as new entry.
8643 */
8644 lua_pushstring(L, value);
8645 ret = lua_rawlen(L, -2);
8646 lua_rawseti(L, -2, ret + 1);
8647
8648 lua_pushboolean(L, 1);
8649 return 1;
8650}
8651
8652/* Remove all occurrences of a given header name. */
8653__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8654{
8655 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8656 int ret;
8657
8658 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008659 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008660
8661 /* Push in the stack the "headers" entry. */
8662 ret = lua_getfield(L, 1, "headers");
8663 if (ret != LUA_TTABLE) {
8664 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8665 WILL_LJMP(lua_error(L));
8666 }
8667
8668 lua_pushstring(L, name);
8669 lua_pushnil(L);
8670 lua_settable(L, -3);
8671
8672 lua_pushboolean(L, 1);
8673 return 1;
8674}
8675
8676/* Set the reply's body. Overwrite any existing entry. */
8677__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8678{
8679 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8680
8681 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008682 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008683
8684 lua_pushstring(L, payload);
8685 lua_setfield(L, 1, "body");
8686
8687 lua_pushboolean(L, 1);
8688 return 1;
8689}
8690
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008691__LJMP static int hlua_log(lua_State *L)
8692{
8693 int level;
8694 const char *msg;
8695
8696 MAY_LJMP(check_args(L, 2, "log"));
8697 level = MAY_LJMP(luaL_checkinteger(L, 1));
8698 msg = MAY_LJMP(luaL_checkstring(L, 2));
8699
8700 if (level < 0 || level >= NB_LOG_LEVELS)
8701 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8702
8703 hlua_sendlog(NULL, level, msg);
8704 return 0;
8705}
8706
8707__LJMP static int hlua_log_debug(lua_State *L)
8708{
8709 const char *msg;
8710
8711 MAY_LJMP(check_args(L, 1, "debug"));
8712 msg = MAY_LJMP(luaL_checkstring(L, 1));
8713 hlua_sendlog(NULL, LOG_DEBUG, msg);
8714 return 0;
8715}
8716
8717__LJMP static int hlua_log_info(lua_State *L)
8718{
8719 const char *msg;
8720
8721 MAY_LJMP(check_args(L, 1, "info"));
8722 msg = MAY_LJMP(luaL_checkstring(L, 1));
8723 hlua_sendlog(NULL, LOG_INFO, msg);
8724 return 0;
8725}
8726
8727__LJMP static int hlua_log_warning(lua_State *L)
8728{
8729 const char *msg;
8730
8731 MAY_LJMP(check_args(L, 1, "warning"));
8732 msg = MAY_LJMP(luaL_checkstring(L, 1));
8733 hlua_sendlog(NULL, LOG_WARNING, msg);
8734 return 0;
8735}
8736
8737__LJMP static int hlua_log_alert(lua_State *L)
8738{
8739 const char *msg;
8740
8741 MAY_LJMP(check_args(L, 1, "alert"));
8742 msg = MAY_LJMP(luaL_checkstring(L, 1));
8743 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008744 return 0;
8745}
8746
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008747__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008748{
8749 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008750 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008751 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008752 return 0;
8753}
8754
8755__LJMP static int hlua_sleep(lua_State *L)
8756{
8757 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008758 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008759
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008760 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008761
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008762 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008763 wakeup_ms = tick_add(now_ms, delay);
8764 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008765
Willy Tarreau9635e032018-10-16 17:52:55 +02008766 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008767 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008768}
8769
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008770__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008771{
8772 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008773 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008774
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008775 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008776
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008777 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008778 wakeup_ms = tick_add(now_ms, delay);
8779 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008780
Willy Tarreau9635e032018-10-16 17:52:55 +02008781 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008782 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008783}
8784
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008785/* This functionis an LUA binding. it permits to give back
8786 * the hand at the HAProxy scheduler. It is used when the
8787 * LUA processing consumes a lot of time.
8788 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008789__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008790{
8791 return 0;
8792}
8793
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008794__LJMP static int hlua_yield(lua_State *L)
8795{
Willy Tarreau9635e032018-10-16 17:52:55 +02008796 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008797 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008798}
8799
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008800/* This function change the nice of the currently executed
8801 * task. It is used set low or high priority at the current
8802 * task.
8803 */
Willy Tarreau59551662015-03-10 14:23:13 +01008804__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008805{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008806 struct hlua *hlua;
8807 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008808
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008809 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008810 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008811
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008812 /* Get hlua struct, or NULL if we execute from main lua state */
8813 hlua = hlua_gethlua(L);
8814
8815 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008816 if (!hlua || !hlua->task)
8817 return 0;
8818
8819 if (nice < -1024)
8820 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008821 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008822 nice = 1024;
8823
8824 hlua->task->nice = nice;
8825 return 0;
8826}
8827
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +02008828/* safe lua coroutine.create() function:
8829 *
8830 * This is a simple wrapper for coroutine.create() that
8831 * ensures the current hlua state ctx is available from
8832 * the new subroutine state
8833 */
8834__LJMP static int hlua_coroutine_create(lua_State *L)
8835{
8836 lua_State *new; /* new coroutine state */
8837 struct hlua **hlua_store;
8838 struct hlua *hlua = hlua_gethlua(L);
8839
8840 new = lua_newthread(L);
8841 if (!new)
8842 return 0;
8843
8844 hlua_store = lua_getextraspace(new);
8845 /* Expose current hlua ctx on new lua thread
8846 * (hlua_gethlua() will properly return the last "known"
8847 * hlua ctx instead of NULL when it is called from such coroutines)
8848 */
8849 *hlua_store = hlua;
8850
8851 /* new lua thread is on the top of the stack, we
8852 * need to duplicate first stack argument (<f> from coroutine.create(<f>))
8853 * on the top of the stack to be able to use xmove() to move it on the new
8854 * stack
8855 */
8856 lua_pushvalue(L, 1);
8857 /* move <f> function to the new stack */
8858 lua_xmove(L, new, 1);
8859 /* new lua thread is back at the top of the stack */
8860 return 1;
8861}
8862
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008863/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008864 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8865 * return an E_AGAIN signal, the emmiter of this signal must set a
8866 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008867 *
8868 * Task wrapper are longjmp safe because the only one Lua code
8869 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008870 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008871struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008872{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008873 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008874 enum hlua_exec status;
8875
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008876 if (task->tid < 0)
8877 task->tid = tid;
8878
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008879 /* If it is the first call to the task, we must initialize the
8880 * execution timeouts.
8881 */
8882 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008883 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008884
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008885 /* Execute the Lua code. */
8886 status = hlua_ctx_resume(hlua, 1);
8887
8888 switch (status) {
8889 /* finished or yield */
8890 case HLUA_E_OK:
8891 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008892 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008893 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008894 break;
8895
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008896 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008897 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008898 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008899 break;
8900
8901 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008902 case HLUA_E_ETMOUT:
8903 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8904 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008905 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008906 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008907 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008908 case HLUA_E_ERR:
8909 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008910 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008911 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008912 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008913 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008914 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008915 break;
8916 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008917 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008918}
8919
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02008920/* Helper function to prepare the lua ctx for a given stream
8921 *
Aurelien DARRAGON02493662023-08-09 15:19:56 +02008922 * ctx will be enforced in <state_id> parent stack on initial creation.
8923 * If s->hlua->state_id differs from <state_id>, which may happen at
8924 * runtime since existing stream hlua ctx will be reused for other
8925 * "independent" (but stream-related) lua executions, hlua will be
8926 * recreated with the expected state id.
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02008927 *
8928 * Returns 1 for success and 0 for failure
8929 */
8930static int hlua_stream_ctx_prepare(struct stream *s, int state_id)
8931{
8932 /* In the execution wrappers linked with a stream, the
8933 * Lua context can be not initialized. This behavior
8934 * permits to save performances because a systematic
8935 * Lua initialization cause 5% performances loss.
8936 */
Aurelien DARRAGON02493662023-08-09 15:19:56 +02008937 ctx_renew:
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02008938 if (!s->hlua) {
8939 struct hlua *hlua;
8940
8941 hlua = pool_alloc(pool_head_hlua);
8942 if (!hlua)
8943 return 0;
8944 HLUA_INIT(hlua);
8945 if (!hlua_ctx_init(hlua, state_id, s->task)) {
8946 pool_free(pool_head_hlua, hlua);
8947 return 0;
8948 }
8949 s->hlua = hlua;
8950 }
Aurelien DARRAGON02493662023-08-09 15:19:56 +02008951 else if (s->hlua->state_id != state_id) {
8952 /* ctx already created, but not in proper state.
8953 * It should only happen after the previous execution is
8954 * finished, otherwise it's probably a bug since we don't
8955 * want to abort unfinished job..
8956 */
8957 BUG_ON(HLUA_IS_RUNNING(s->hlua));
8958 hlua_ctx_destroy(s->hlua);
8959 s->hlua = NULL;
8960 goto ctx_renew;
8961 }
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02008962 return 1;
8963}
8964
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008965/* This function is an LUA binding that register LUA function to be
8966 * executed after the HAProxy configuration parsing and before the
8967 * HAProxy scheduler starts. This function expect only one LUA
8968 * argument that is a function. This function returns nothing, but
8969 * throws if an error is encountered.
8970 */
8971__LJMP static int hlua_register_init(lua_State *L)
8972{
8973 struct hlua_init_function *init;
8974 int ref;
8975
8976 MAY_LJMP(check_args(L, 1, "register_init"));
8977
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008978 if (hlua_gethlua(L)) {
8979 /* runtime processing */
8980 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8981 }
8982
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008983 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8984
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008985 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008986 if (!init) {
8987 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008988 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008989 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008990
8991 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008992 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008993 return 0;
8994}
8995
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008996/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008997 * executed in parallel of the main HAroxy activity. The task is
8998 * created and it is set in the HAProxy scheduler. It can be called
8999 * from the "init" section, "post init" or during the runtime.
9000 *
9001 * Lua prototype:
9002 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009003 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
9004 *
9005 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009006 */
Aurelien DARRAGONe0b16352023-04-21 17:38:37 +02009007__LJMP static int hlua_register_task(lua_State *L)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009008{
Christopher Faulet5294ec02021-04-12 12:24:47 +02009009 struct hlua *hlua = NULL;
9010 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009011 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009012 int nb_arg;
9013 int it;
9014 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01009015 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009016
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009017 nb_arg = lua_gettop(L);
9018 if (nb_arg < 1)
9019 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
9020 else if (nb_arg > 5)
9021 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009022
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009023 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009024 ref = MAY_LJMP(hlua_checkfunction(L, 1));
9025
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009026 /* extract optional args (if any) */
9027 it = 0;
9028 while (--nb_arg) {
9029 lua_pushvalue(L, 2 + it);
9030 arg_ref[it] = hlua_ref(L); /* get arg reference */
9031 it += 1;
9032 }
9033 nb_arg = it;
9034
Thierry Fournier75fc0292020-11-28 13:18:56 +01009035 /* Get the reference state. If the reference is NULL, L is the master
9036 * state, otherwise hlua->T is.
9037 */
9038 hlua = hlua_gethlua(L);
9039 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01009040 /* we are in runtime processing */
9041 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01009042 else
Thierry Fournier021d9862020-11-28 23:42:03 +01009043 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01009044 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01009045
Willy Tarreaubafbe012017-11-24 17:34:44 +01009046 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009047 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02009048 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009049 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009050
Thierry Fournier59f11be2020-11-29 00:37:41 +01009051 /* We are in the common lua state, execute the task anywhere,
9052 * otherwise, inherit the current thread identifier
9053 */
9054 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009055 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01009056 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009057 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02009058 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02009059 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02009060
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009061 task->context = hlua;
9062 task->process = hlua_process_task;
9063
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009064 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02009065 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009066
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009067 /* Ensure there is enough space on the stack for the function
9068 * plus optional arguments
9069 */
9070 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
9071 goto alloc_error;
9072
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009073 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009074 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01009075 /* function ref not needed anymore since it was pushed to the substack */
9076 hlua_unref(L, ref);
9077
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009078 hlua->nargs = nb_arg;
9079
9080 /* push optional arguments to the function */
9081 for (it = 0; it < nb_arg; it++) {
9082 /* push arg to the stack */
9083 hlua_pushref(hlua->T, arg_ref[it]);
9084 /* arg ref not needed anymore since it was pushed to the substack */
9085 hlua_unref(L, arg_ref[it]);
9086 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009087
9088 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02009089 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009090
9091 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02009092
9093 alloc_error:
9094 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009095 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01009096 for (it = 0; it < nb_arg; it++) {
9097 hlua_unref(L, arg_ref[it]);
9098 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02009099 hlua_ctx_destroy(hlua);
9100 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9101 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009102}
9103
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009104/* called from unsafe location */
9105static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
9106{
9107 /* hlua cleanup */
9108
9109 hlua_lock(hlua_sub->hlua);
9110 /* registry is shared between coroutines */
9111 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9112 hlua_unlock(hlua_sub->hlua);
9113
9114 hlua_ctx_destroy(hlua_sub->hlua);
9115
9116 /* free */
9117 pool_free(pool_head_hlua_event_sub, hlua_sub);
9118}
9119
9120/* single event handler: hlua ctx is shared between multiple events handlers
9121 * issued from the same subscription. Thus, it is not destroyed when the event
9122 * is processed: it is destroyed when no more events are expected for the
9123 * subscription (ie: when the subscription ends).
9124 *
9125 * Moreover, events are processed sequentially within the subscription:
9126 * one event must be fully processed before another one may be processed.
9127 * This ensures proper consistency for lua event handling from an ordering
9128 * point of view. This is especially useful with server events for example
9129 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
9130 * actions from lua (e.g.: sending emails or making API calls).
9131 *
9132 * Due to this design, each lua event handler is pleased to process the event
9133 * as fast as possible to prevent the event queue from growing up.
9134 * Strictly speaking, there is no runtime limit for the callback function
9135 * (timeout set to default task timeout), but if the event queue goes past
9136 * the limit of unconsumed events an error will be reported and the
9137 * susbscription will pause itself for as long as it takes for the handler to
9138 * catch up (events will be lost as a result).
9139 * If the event handler does not need the sequential ordering and wants to
9140 * process multiple events at a time, it may spawn a new side-task using
9141 * 'core.register_task' to delegate the event handling and make parallel event
9142 * processing within the same subscription set.
9143 */
9144static void hlua_event_handler(struct hlua *hlua)
9145{
9146 enum hlua_exec status;
9147
9148 /* If it is the first call to the task, we must initialize the
9149 * execution timeouts.
9150 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009151 if (!HLUA_IS_RUNNING(hlua))
9152 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009153
9154 /* make sure to reset the task expiry before each hlua_ctx_resume()
9155 * since the task is re-used for multiple cb function calls
9156 * We couldn't risk to have t->expire pointing to a past date because
9157 * it was set during last function invocation but was never reset since
9158 * (ie: E_AGAIN)
9159 */
9160 hlua->task->expire = TICK_ETERNITY;
9161
9162 /* Execute the Lua code. */
9163 status = hlua_ctx_resume(hlua, 1);
9164
9165 switch (status) {
9166 /* finished or yield */
9167 case HLUA_E_OK:
9168 break;
9169
9170 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
9171 notification_gc(&hlua->com);
9172 hlua->task->expire = hlua->wake_time;
9173 break;
9174
9175 /* finished with error. */
9176 case HLUA_E_ETMOUT:
9177 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
9178 break;
9179
9180 case HLUA_E_ERRMSG:
9181 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
9182 break;
9183
9184 case HLUA_E_ERR:
9185 default:
9186 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
9187 break;
9188 }
9189}
9190
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009191__LJMP static void hlua_event_hdl_cb_push_event_checkres(lua_State *L,
9192 struct event_hdl_cb_data_server_checkres *check)
9193{
9194 lua_pushstring(L, "agent");
9195 lua_pushboolean(L, check->agent);
9196 lua_settable(L, -3);
9197 lua_pushstring(L, "result");
9198 switch (check->result) {
9199 case CHK_RES_FAILED:
9200 lua_pushstring(L, "FAILED");
9201 break;
9202 case CHK_RES_PASSED:
9203 lua_pushstring(L, "PASSED");
9204 break;
9205 case CHK_RES_CONDPASS:
9206 lua_pushstring(L, "CONDPASS");
9207 break;
9208 default:
9209 lua_pushnil(L);
9210 break;
9211 }
9212 lua_settable(L, -3);
9213
9214 lua_pushstring(L, "duration");
9215 lua_pushinteger(L, check->duration);
9216 lua_settable(L, -3);
9217
9218 lua_pushstring(L, "reason");
9219 lua_newtable(L);
9220
9221 lua_pushstring(L, "short");
9222 lua_pushstring(L, get_check_status_info(check->reason.status));
9223 lua_settable(L, -3);
9224 lua_pushstring(L, "desc");
9225 lua_pushstring(L, get_check_status_description(check->reason.status));
9226 lua_settable(L, -3);
9227 if (check->reason.status >= HCHK_STATUS_L57DATA) {
9228 /* code only available when the check reached data analysis stage */
9229 lua_pushstring(L, "code");
9230 lua_pushinteger(L, check->reason.code);
9231 lua_settable(L, -3);
9232 }
9233
9234 lua_settable(L, -3); /* reason table */
9235
9236 lua_pushstring(L, "health");
9237 lua_newtable(L);
9238
9239 lua_pushstring(L, "cur");
9240 lua_pushinteger(L, check->health.cur);
9241 lua_settable(L, -3);
9242 lua_pushstring(L, "rise");
9243 lua_pushinteger(L, check->health.rise);
9244 lua_settable(L, -3);
9245 lua_pushstring(L, "fall");
9246 lua_pushinteger(L, check->health.fall);
9247 lua_settable(L, -3);
9248
9249 lua_settable(L, -3); /* health table */
9250}
9251
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009252/* This function pushes various arguments such as event type and event data to
9253 * the lua function that will be called to consume the event.
9254 */
9255__LJMP static void hlua_event_hdl_cb_push_args(struct hlua_event_sub *hlua_sub,
9256 struct event_hdl_async_event *e)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009257{
9258 struct hlua *hlua = hlua_sub->hlua;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009259 struct event_hdl_sub_type event = e->type;
9260 void *data = e->data;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009261
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009262 /* push event type */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009263 hlua->nargs = 1;
9264 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009265
9266 /* push event data (according to event type) */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009267 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
9268 struct event_hdl_cb_data_server *e_server = data;
9269 struct proxy *px;
9270 struct server *server;
9271
9272 hlua->nargs += 1;
9273 lua_newtable(hlua->T);
9274 /* Add server name */
9275 lua_pushstring(hlua->T, "name");
9276 lua_pushstring(hlua->T, e_server->safe.name);
9277 lua_settable(hlua->T, -3);
9278 /* Add server puid */
9279 lua_pushstring(hlua->T, "puid");
9280 lua_pushinteger(hlua->T, e_server->safe.puid);
9281 lua_settable(hlua->T, -3);
9282 /* Add server rid */
9283 lua_pushstring(hlua->T, "rid");
9284 lua_pushinteger(hlua->T, e_server->safe.rid);
9285 lua_settable(hlua->T, -3);
9286 /* Add server proxy name */
9287 lua_pushstring(hlua->T, "proxy_name");
9288 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9289 lua_settable(hlua->T, -3);
Aurelien DARRAGON55f84c72023-03-22 17:49:04 +01009290 /* Add server proxy uuid */
9291 lua_pushstring(hlua->T, "proxy_uuid");
9292 lua_pushinteger(hlua->T, e_server->safe.proxy_uuid);
9293 lua_settable(hlua->T, -3);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009294
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009295 /* special events, fetch additional info with explicit type casting */
9296 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_STATE, event)) {
9297 struct event_hdl_cb_data_server_state *state = data;
9298 int it;
9299
9300 if (!lua_checkstack(hlua->T, 20))
9301 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9302
9303 /* state subclass */
9304 lua_pushstring(hlua->T, "state");
9305 lua_newtable(hlua->T);
9306
9307 lua_pushstring(hlua->T, "admin");
9308 lua_pushboolean(hlua->T, state->safe.type);
9309 lua_settable(hlua->T, -3);
9310
9311 /* is it because of a check ? */
9312 if (!state->safe.type &&
9313 (state->safe.op_st_chg.cause == SRV_OP_STCHGC_HEALTH ||
9314 state->safe.op_st_chg.cause == SRV_OP_STCHGC_AGENT)) {
9315 /* yes, provide check result */
9316 lua_pushstring(hlua->T, "check");
9317 lua_newtable(hlua->T);
9318 hlua_event_hdl_cb_push_event_checkres(hlua->T, &state->safe.op_st_chg.check);
9319 lua_settable(hlua->T, -3); /* check table */
9320 }
9321
9322 lua_pushstring(hlua->T, "cause");
9323 if (state->safe.type)
9324 lua_pushstring(hlua->T, srv_adm_st_chg_cause(state->safe.adm_st_chg.cause));
9325 else
9326 lua_pushstring(hlua->T, srv_op_st_chg_cause(state->safe.op_st_chg.cause));
9327 lua_settable(hlua->T, -3);
9328
9329 /* old_state, new_state */
9330 for (it = 0; it < 2; it++) {
9331 enum srv_state srv_state = (!it) ? state->safe.old_state : state->safe.new_state;
9332
9333 lua_pushstring(hlua->T, (!it) ? "old_state" : "new_state");
9334 switch (srv_state) {
9335 case SRV_ST_STOPPED:
9336 lua_pushstring(hlua->T, "STOPPED");
9337 break;
9338 case SRV_ST_STOPPING:
9339 lua_pushstring(hlua->T, "STOPPING");
9340 break;
9341 case SRV_ST_STARTING:
9342 lua_pushstring(hlua->T, "STARTING");
9343 break;
9344 case SRV_ST_RUNNING:
9345 lua_pushstring(hlua->T, "RUNNING");
9346 break;
9347 default:
9348 lua_pushnil(hlua->T);
9349 break;
9350 }
9351 lua_settable(hlua->T, -3);
9352 }
9353
9354 /* requeued */
9355 lua_pushstring(hlua->T, "requeued");
9356 lua_pushinteger(hlua->T, state->safe.requeued);
9357 lua_settable(hlua->T, -3);
9358
9359 lua_settable(hlua->T, -3); /* state table */
9360 }
Aurelien DARRAGON948dd3d2023-04-26 11:27:09 +02009361 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_ADMIN, event)) {
9362 struct event_hdl_cb_data_server_admin *admin = data;
9363 int it;
9364
9365 if (!lua_checkstack(hlua->T, 20))
9366 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9367
9368 /* admin subclass */
9369 lua_pushstring(hlua->T, "admin");
9370 lua_newtable(hlua->T);
9371
9372 lua_pushstring(hlua->T, "cause");
9373 lua_pushstring(hlua->T, srv_adm_st_chg_cause(admin->safe.cause));
9374 lua_settable(hlua->T, -3);
9375
9376 /* old_admin, new_admin */
9377 for (it = 0; it < 2; it++) {
9378 enum srv_admin srv_admin = (!it) ? admin->safe.old_admin : admin->safe.new_admin;
9379
9380 lua_pushstring(hlua->T, (!it) ? "old_admin" : "new_admin");
9381
9382 /* admin state matrix */
9383 lua_newtable(hlua->T);
9384
9385 lua_pushstring(hlua->T, "MAINT");
9386 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_MAINT);
9387 lua_settable(hlua->T, -3);
9388 lua_pushstring(hlua->T, "FMAINT");
9389 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FMAINT);
9390 lua_settable(hlua->T, -3);
9391 lua_pushstring(hlua->T, "IMAINT");
9392 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IMAINT);
9393 lua_settable(hlua->T, -3);
9394 lua_pushstring(hlua->T, "RMAINT");
9395 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_RMAINT);
9396 lua_settable(hlua->T, -3);
9397 lua_pushstring(hlua->T, "CMAINT");
9398 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_CMAINT);
9399 lua_settable(hlua->T, -3);
9400
9401 lua_pushstring(hlua->T, "DRAIN");
9402 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_DRAIN);
9403 lua_settable(hlua->T, -3);
9404 lua_pushstring(hlua->T, "FDRAIN");
9405 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FDRAIN);
9406 lua_settable(hlua->T, -3);
9407 lua_pushstring(hlua->T, "IDRAIN");
9408 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IDRAIN);
9409 lua_settable(hlua->T, -3);
9410
9411 lua_settable(hlua->T, -3); /* matrix table */
9412 }
9413 /* requeued */
9414 lua_pushstring(hlua->T, "requeued");
9415 lua_pushinteger(hlua->T, admin->safe.requeued);
9416 lua_settable(hlua->T, -3);
9417
9418 lua_settable(hlua->T, -3); /* admin table */
9419 }
Aurelien DARRAGON0bd53b22023-03-30 15:53:33 +02009420 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_CHECK, event)) {
9421 struct event_hdl_cb_data_server_check *check = data;
9422
9423 if (!lua_checkstack(hlua->T, 20))
9424 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9425
9426 /* check subclass */
9427 lua_pushstring(hlua->T, "check");
9428 lua_newtable(hlua->T);
9429
9430 /* check result snapshot */
9431 hlua_event_hdl_cb_push_event_checkres(hlua->T, &check->safe.res);
9432
9433 lua_settable(hlua->T, -3); /* check table */
9434 }
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009435
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009436 /* attempt to provide reference server object
9437 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9438 */
Aurelien DARRAGON3d9bf4e2023-03-22 17:46:12 +01009439 px = proxy_find_by_id(e_server->safe.proxy_uuid, PR_CAP_BE, 0);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009440 BUG_ON(!px);
9441 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9442 if (server) {
9443 lua_pushstring(hlua->T, "reference");
9444 hlua_fcn_new_server(hlua->T, server);
9445 lua_settable(hlua->T, -3);
9446 }
9447 }
9448 /* sub mgmt */
9449 hlua->nargs += 1;
9450 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
Aurelien DARRAGON096b3832023-04-20 11:32:46 +02009451
9452 /* when? */
9453 hlua->nargs += 1;
9454 lua_pushinteger(hlua->T, e->when.tv_sec);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009455}
9456
9457/* events runner: if there's an ongoing hlua event handling process, finish it
9458 * then, check if there are new events waiting to be processed
9459 * (events are processed sequentially)
9460 *
9461 * We have a safety measure to warn/guard if the event queue is growing up
9462 * too much due to many events being generated and lua handler is unable to
9463 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9464 * TODO: make it tunable
9465 */
9466static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9467{
9468 struct hlua_event_sub *hlua_sub = context;
9469 struct event_hdl_async_event *event;
9470 const char *error = NULL;
9471
9472 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009473 const char *trace = NULL;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009474
9475 /* We reached the limit of pending events in the queue: we should
9476 * warn the user, and temporarily pause the subscription to give a chance
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009477 * to the handler to catch up? (it also prevents resource shortage since
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009478 * the queue could grow indefinitely otherwise)
9479 * TODO: find a way to inform the handler that it missed some events
9480 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9481 *
9482 * Nonetheless, reaching this limit means that the handler is not fast enough
9483 * and/or that it subscribed to events that happen too frequently and did not
9484 * expect it. This could come from an inadequate design in the user's script.
9485 */
9486 event_hdl_pause(hlua_sub->sub);
9487 hlua_sub->paused = 1;
9488
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009489 if (SET_SAFE_LJMP(hlua_sub->hlua)) {
9490 /* The following Lua call may fail. */
9491 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9492 /* At this point the execution is safe. */
9493 RESET_SAFE_LJMP(hlua_sub->hlua);
9494 } else {
9495 /* Lua error was raised while fetching lua trace from current ctx */
9496 SEND_ERR(NULL, "Lua event_hdl: unexpected error (memory failure?).\n");
9497 }
9498 ha_warning("Lua event_hdl: pausing the subscription because the handler fails "
9499 "to keep up the pace (%u unconsumed events) from %s.\n",
9500 event_hdl_async_equeue_size(&hlua_sub->equeue),
9501 (trace) ? trace : "[unknown]");
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009502 }
9503
9504 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9505 /* ongoing hlua event handler, resume it */
9506 hlua_event_handler(hlua_sub->hlua);
9507 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9508 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9509 /* ending event: no more events to come */
9510 event_hdl_async_free_event(event);
9511 task_destroy(task);
9512 hlua_event_subscription_destroy(hlua_sub);
9513 return NULL;
9514 }
9515 /* new event: start processing it */
9516
9517 /* The following Lua calls can fail. */
9518 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9519 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9520 error = lua_tostring(hlua_sub->hlua->T, -1);
9521 else
9522 error = "critical error";
9523 ha_alert("Lua event_hdl: %s.\n", error);
9524 goto skip_event;
9525 }
9526
9527 /* Check stack available size. */
9528 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9529 ha_alert("Lua event_hdl: full stack.\n");
9530 RESET_SAFE_LJMP(hlua_sub->hlua);
9531 goto skip_event;
9532 }
9533
9534 /* Restore the function in the stack. */
9535 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9536
9537 /* push args */
9538 hlua_sub->hlua->nargs = 0;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009539 MAY_LJMP(hlua_event_hdl_cb_push_args(hlua_sub, event));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009540
9541 /* At this point the execution is safe. */
9542 RESET_SAFE_LJMP(hlua_sub->hlua);
9543
9544 /* At this point the event was successfully translated into hlua ctx,
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009545 * or hlua error occurred, so we can safely discard it
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009546 */
9547 event_hdl_async_free_event(event);
9548 event = NULL;
9549
9550 hlua_event_handler(hlua_sub->hlua);
9551 skip_event:
9552 if (event)
9553 event_hdl_async_free_event(event);
9554
9555 }
9556
9557 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9558 /* we just finished the processing of one event..
9559 * check for new events before becoming idle
9560 */
9561 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9562 /* more events to process, make sure the task
9563 * will be resumed ASAP to process pending events
9564 */
9565 task_wakeup(task, TASK_WOKEN_OTHER);
9566 }
9567 else if (hlua_sub->paused) {
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009568 /* empty queue, the handler caught up: resume the subscription */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009569 event_hdl_resume(hlua_sub->sub);
9570 hlua_sub->paused = 0;
9571 }
9572 }
9573
9574 return task;
9575}
9576
9577/* Must be called directly under lua protected/safe environment
9578 * (not from external callback)
9579 * <fcn_ref> should NOT be dropped after the function successfully returns:
9580 * it will be done automatically in hlua_event_subscription_destroy() when the
9581 * subscription ends.
9582 *
9583 * Returns the new subscription on success and NULL on failure (memory error)
9584 */
9585static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9586 int state_id, int fcn_ref)
9587{
9588 struct hlua_event_sub *hlua_sub;
9589 struct task *task = NULL;
9590
9591 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9592 if (!hlua_sub)
9593 goto mem_error;
9594 hlua_sub->task = NULL;
9595 hlua_sub->hlua = NULL;
9596 hlua_sub->paused = 0;
9597 if ((task = task_new_here()) == NULL) {
9598 ha_alert("out of memory while allocating hlua event task");
9599 goto mem_error;
9600 }
9601 task->process = hlua_event_runner;
9602 task->context = hlua_sub;
9603 event_hdl_async_equeue_init(&hlua_sub->equeue);
9604 hlua_sub->task = task;
9605 hlua_sub->fcn_ref = fcn_ref;
9606 hlua_sub->state_id = state_id;
9607 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9608 if (!hlua_sub->hlua)
9609 goto mem_error;
9610 HLUA_INIT(hlua_sub->hlua);
9611 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9612 goto mem_error;
9613
9614 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9615 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9616 task,
9617 hlua_sub,
9618 NULL));
9619 if (!hlua_sub->sub)
9620 goto mem_error;
9621
9622 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9623
9624 mem_error:
9625 if (hlua_sub) {
Tim Duesterhusfe83f582023-04-22 17:47:34 +02009626 task_destroy(hlua_sub->task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009627 if (hlua_sub->hlua)
9628 hlua_ctx_destroy(hlua_sub->hlua);
9629 pool_free(pool_head_hlua_event_sub, hlua_sub);
9630 }
9631
9632 return NULL;
9633}
9634
9635/* looks for an array of strings referring to a composition of event_hdl subscription
9636 * types at <index> in <L> stack
9637 */
9638__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9639{
9640 struct event_hdl_sub_type subscriptions;
9641 const char *msg;
9642
9643 if (lua_type(L, index) != LUA_TTABLE) {
9644 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9645 luaL_argerror(L, index, msg);
9646 }
9647
9648 subscriptions = EVENT_HDL_SUB_NONE;
9649
9650 /* browse the argument as an array. */
9651 lua_pushnil(L);
9652 while (lua_next(L, index) != 0) {
9653 if (lua_type(L, -1) != LUA_TSTRING) {
9654 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9655 luaL_argerror(L, index, msg);
9656 }
9657
9658 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9659 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9660 luaL_argerror(L, index, msg);
9661 }
9662
9663 /* perform subscriptions |= current sub */
9664 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9665
9666 /* pop the current value. */
9667 lua_pop(L, 1);
9668 }
9669
9670 return subscriptions;
9671}
9672
9673/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9674 * the function to prevent LJMP
9675 *
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009676 * If no error occurred, the function returns 1, else it returns 0 and
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009677 * the error message is pushed at the top of the stack
9678 */
9679__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9680{
9681 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9682
9683 /* this function may raise errors */
9684 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9685}
9686static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9687{
9688 if (!lua_checkstack(L, 2))
9689 return 0;
9690 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9691 lua_pushlightuserdata(L, sub);
9692 switch (lua_pcall(L, 1, 1, 0)) {
9693 case LUA_OK:
9694 return 1;
9695 default:
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009696 /* error was caught */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009697 return 0;
9698 }
9699}
9700
9701/* This function is a LUA helper used for registering lua event callbacks.
9702 * It expects an event subscription array and the function to be executed
9703 * when subscribed events occur (stack arguments).
9704 * It can be called from the "init" section, "post init" or during the runtime.
9705 *
9706 * <sub_list> is the subscription list where the subscription will be attempted
9707 *
9708 * Pushes the newly allocated subscription on the stack on success
9709 */
9710__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9711{
9712 struct hlua *hlua;
9713 struct event_hdl_sub *sub;
9714 struct event_hdl_sub_type subscriptions;
9715 int fcn_ref;
9716 int state_id;
9717
9718 MAY_LJMP(check_args(L, 2, "event_sub"));
9719
9720 /* Get the reference state */
9721 hlua = hlua_gethlua(L);
9722 if (hlua)
9723 /* we are in runtime processing, any thread may subscribe to events:
9724 * subscription events will be handled by the thread who performed
9725 * the registration.
9726 */
9727 state_id = hlua->state_id;
9728 else {
9729 /* we are in initialization mode, only thread 0 (actual calling thread)
9730 * may subscribe to events to prevent the same handler (from different lua
9731 * stacks) from being registered multiple times
9732 *
9733 * hlua_state_id == 0: monostack (lua-load)
9734 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9735 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9736 */
9737 if (hlua_state_id > 1)
9738 return 0; /* skip registration */
9739 state_id = hlua_state_id;
9740 }
9741
9742 /* First argument : event subscriptions. */
9743 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9744
9745 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9746 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9747 return 0; /* Never reached */
9748 }
9749
9750 /* Second argument : lua function. */
9751 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9752
9753 /* try to subscribe */
9754 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9755 if (!sub) {
9756 hlua_unref(L, fcn_ref);
9757 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9758 return 0; /* Never reached */
9759 }
9760
9761 /* push the subscription to the stack
9762 *
9763 * Here we use the safe function so that lua errors will be
9764 * handled explicitly to prevent 'sub' from being lost
9765 */
9766 if (!hlua_new_event_sub_safe(L, sub)) {
9767 /* Some events could already be pending in the handler's queue.
9768 * However it is wiser to cancel the subscription since we are unable to
9769 * provide a valid reference to it.
9770 * Pending events will be delivered (unless lua keeps raising errors).
9771 */
9772 event_hdl_unsubscribe(sub); /* cancel the subscription */
9773 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9774 return 0; /* Never reached */
9775 }
9776 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9777
9778 return 1;
9779}
9780
9781/* This function is a LUA wrapper used for registering global lua event callbacks
9782 * The new subscription is pushed onto the stack on success
9783 * Returns the number of arguments pushed to the stack (1 for success)
9784 */
9785__LJMP static int hlua_event_global_sub(lua_State *L)
9786{
9787 /* NULL <sub_list> = global subscription list */
9788 return MAY_LJMP(hlua_event_sub(L, NULL));
9789}
9790
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009791/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9792 * doesn't allow "yield" functions because the HAProxy engine cannot
9793 * resume converters.
9794 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009795static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009796{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009797 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009798 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009799 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009800
Willy Tarreaube508f12016-03-10 11:47:01 +01009801 if (!stream)
9802 return 0;
9803
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02009804 if (!hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn))) {
9805 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9806 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009807 }
9808
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009809 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009810 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009811
9812 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009813 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009814 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9815 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009816 else
9817 error = "critical error";
9818 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009819 return 0;
9820 }
9821
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009822 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009823 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009824 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009825 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009826 return 0;
9827 }
9828
9829 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009830 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009831
9832 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009833 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009834 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009835 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009836 return 0;
9837 }
Aurelien DARRAGON41217722023-05-17 10:44:47 +02009838 MAY_LJMP(hlua_smp2lua(stream->hlua->T, smp));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009839 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009840
9841 /* push keywords in the stack. */
9842 if (arg_p) {
9843 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009844 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009845 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009846 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009847 return 0;
9848 }
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +02009849 MAY_LJMP(hlua_arg2lua(stream->hlua->T, arg_p));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009850 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009851 }
9852 }
9853
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009854 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009855 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009856
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009857 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009858 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009859 }
9860
9861 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009862 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009863 /* finished. */
9864 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009865 /* If the stack is empty, the function fails. */
9866 if (lua_gettop(stream->hlua->T) <= 0)
9867 return 0;
9868
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009869 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009870 hlua_lua2smp(stream->hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02009871 /* dup the smp before popping the related lua value and
9872 * returning it to haproxy
9873 */
9874 smp_dup(smp);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009875 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009876 return 1;
9877
9878 /* yield. */
9879 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009880 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009881 return 0;
9882
9883 /* finished with error. */
9884 case HLUA_E_ERRMSG:
9885 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009886 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009887 fcn->name, lua_tostring(stream->hlua->T, -1));
9888 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009889 return 0;
9890
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009891 case HLUA_E_ETMOUT:
9892 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9893 return 0;
9894
9895 case HLUA_E_NOMEM:
9896 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9897 return 0;
9898
9899 case HLUA_E_YIELD:
9900 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9901 return 0;
9902
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009903 case HLUA_E_ERR:
9904 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009905 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009906 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009907
9908 default:
9909 return 0;
9910 }
9911}
9912
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009913/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9914 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009915 * resume sample-fetches. This function will be called by the sample
9916 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009917 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009918static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9919 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009920{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009921 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009922 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009923 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009924 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009925
Willy Tarreaube508f12016-03-10 11:47:01 +01009926 if (!stream)
9927 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009928
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +02009929 if (!hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn))) {
9930 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9931 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009932 }
9933
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009934 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009935 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009936
9937 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009938 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009939 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9940 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009941 else
9942 error = "critical error";
9943 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009944 return 0;
9945 }
9946
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009947 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009948 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009949 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009950 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009951 return 0;
9952 }
9953
9954 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009955 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009956
9957 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009958 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009959 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009960 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009961 return 0;
9962 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009963 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009964
9965 /* push keywords in the stack. */
9966 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9967 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009968 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009969 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009970 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009971 return 0;
9972 }
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +02009973 MAY_LJMP(hlua_arg2lua(stream->hlua->T, arg_p));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009974 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009975 }
9976
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009977 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009978 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009979
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009980 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009981 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009982 }
9983
9984 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009985 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009986 /* finished. */
9987 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009988 /* If the stack is empty, the function fails. */
9989 if (lua_gettop(stream->hlua->T) <= 0)
9990 return 0;
9991
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009992 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009993 hlua_lua2smp(stream->hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02009994 /* dup the smp before popping the related lua value and
9995 * returning it to haproxy
9996 */
9997 smp_dup(smp);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009998 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009999
10000 /* Set the end of execution flag. */
10001 smp->flags &= ~SMP_F_MAY_CHANGE;
10002 return 1;
10003
10004 /* yield. */
10005 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010006 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010007 return 0;
10008
10009 /* finished with error. */
10010 case HLUA_E_ERRMSG:
10011 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010012 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010013 fcn->name, lua_tostring(stream->hlua->T, -1));
10014 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010015 return 0;
10016
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010017 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010018 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
10019 return 0;
10020
10021 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010022 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
10023 return 0;
10024
10025 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010026 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
10027 return 0;
10028
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010029 case HLUA_E_ERR:
10030 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010031 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +010010032 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010033
10034 default:
10035 return 0;
10036 }
10037}
10038
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010039/* This function is an LUA binding used for registering
10040 * "sample-conv" functions. It expects a converter name used
10041 * in the haproxy configuration file, and an LUA function.
10042 */
10043__LJMP static int hlua_register_converters(lua_State *L)
10044{
10045 struct sample_conv_kw_list *sck;
10046 const char *name;
10047 int ref;
10048 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +020010049 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010050 struct sample_conv *sc;
10051 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010052
10053 MAY_LJMP(check_args(L, 2, "register_converters"));
10054
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010055 if (hlua_gethlua(L)) {
10056 /* runtime processing */
10057 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
10058 }
10059
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010060 /* First argument : converter name. */
10061 name = MAY_LJMP(luaL_checkstring(L, 1));
10062
10063 /* Second argument : lua function. */
10064 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10065
Thierry Fournierf67442e2020-11-28 20:41:07 +010010066 /* Check if the converter is already registered */
10067 trash = get_trash_chunk();
10068 chunk_printf(trash, "lua.%s", name);
10069 sc = find_sample_conv(trash->area, trash->data);
10070 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010071 fcn = sc->private;
10072 if (fcn->function_ref[hlua_state_id] != -1) {
10073 ha_warning("Trying to register converter 'lua.%s' more than once. "
10074 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010075 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010076 }
10077 fcn->function_ref[hlua_state_id] = ref;
10078 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010079 }
10080
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010081 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010082 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010083 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +020010084 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010085 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010086 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +020010087 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010088
10089 /* Fill fcn. */
10090 fcn->name = strdup(name);
10091 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +020010092 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010093 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010094
10095 /* List head */
10096 sck->list.n = sck->list.p = NULL;
10097
10098 /* converter keyword. */
10099 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010100 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010101 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +020010102 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010103
10104 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
10105 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010106 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 +010010107 sck->kw[0].val_args = NULL;
10108 sck->kw[0].in_type = SMP_T_STR;
10109 sck->kw[0].out_type = SMP_T_STR;
10110 sck->kw[0].private = fcn;
10111
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010112 /* Register this new converter */
10113 sample_register_convs(sck);
10114
10115 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +020010116
10117 alloc_error:
10118 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010119 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +020010120 ha_free(&sck);
10121 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10122 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010123}
10124
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010125/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010126 * "sample-fetch" functions. It expects a converter name used
10127 * in the haproxy configuration file, and an LUA function.
10128 */
10129__LJMP static int hlua_register_fetches(lua_State *L)
10130{
10131 const char *name;
10132 int ref;
10133 int len;
10134 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +020010135 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010136 struct sample_fetch *sf;
10137 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010138
10139 MAY_LJMP(check_args(L, 2, "register_fetches"));
10140
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010141 if (hlua_gethlua(L)) {
10142 /* runtime processing */
10143 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
10144 }
10145
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010146 /* First argument : sample-fetch name. */
10147 name = MAY_LJMP(luaL_checkstring(L, 1));
10148
10149 /* Second argument : lua function. */
10150 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10151
Thierry Fournierf67442e2020-11-28 20:41:07 +010010152 /* Check if the sample-fetch is already registered */
10153 trash = get_trash_chunk();
10154 chunk_printf(trash, "lua.%s", name);
10155 sf = find_sample_fetch(trash->area, trash->data);
10156 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010157 fcn = sf->private;
10158 if (fcn->function_ref[hlua_state_id] != -1) {
10159 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
10160 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010161 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010162 }
10163 fcn->function_ref[hlua_state_id] = ref;
10164 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010165 }
10166
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010167 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010168 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010169 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +020010170 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010171 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010172 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +020010173 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010174
10175 /* Fill fcn. */
10176 fcn->name = strdup(name);
10177 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +020010178 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010179 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010180
10181 /* List head */
10182 sfk->list.n = sfk->list.p = NULL;
10183
10184 /* sample-fetch keyword. */
10185 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010186 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010187 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +020010188 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010189
10190 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
10191 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010192 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 +010010193 sfk->kw[0].val_args = NULL;
10194 sfk->kw[0].out_type = SMP_T_STR;
10195 sfk->kw[0].use = SMP_USE_HTTP_ANY;
10196 sfk->kw[0].val = 0;
10197 sfk->kw[0].private = fcn;
10198
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010199 /* Register this new fetch. */
10200 sample_register_fetches(sfk);
10201
10202 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +020010203
10204 alloc_error:
10205 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010206 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +020010207 ha_free(&sfk);
10208 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10209 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010210}
10211
Christopher Faulet501465d2020-02-26 14:54:16 +010010212/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010213 */
Christopher Faulet501465d2020-02-26 14:54:16 +010010214__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010215{
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010216 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010217 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +020010218 int wakeup_ms; // tick value
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010219
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010220 /* Get hlua struct, or NULL if we execute from main lua state */
10221 hlua = hlua_gethlua(L);
10222 if (!hlua) {
10223 return 0;
10224 }
10225
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010226 MAY_LJMP(check_args(L, 1, "wake_time"));
10227
10228 delay = MAY_LJMP(luaL_checkinteger(L, 1));
10229 wakeup_ms = tick_add(now_ms, delay);
10230 hlua->wake_time = wakeup_ms;
10231 return 0;
10232}
10233
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010234/* This function is a wrapper to execute each LUA function declared as an action
10235 * wrapper during the initialisation period. This function may return any
10236 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
10237 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
10238 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010239 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010240static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +020010241 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010242{
10243 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010244 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010245 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010246 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010247
10248 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +010010249 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
10250 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
10251 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
10252 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010253 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010254 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010255 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010256 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010257
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020010258 if (!hlua_stream_ctx_prepare(s, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn))) {
10259 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
10260 rule->arg.hlua_rule->fcn->name);
10261 goto end;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010262 }
10263
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010264 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010265 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010266
10267 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010268 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010269 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10270 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010271 else
10272 error = "critical error";
10273 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010274 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010275 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010276 }
10277
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010278 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010279 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010280 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010281 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010282 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010283 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010284 }
10285
10286 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010287 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010288
Willy Tarreau87b09662015-04-03 00:22:06 +020010289 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +020010290 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010291 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010292 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010293 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010294 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010295 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010296 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010297
10298 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010299 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010300 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010301 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010302 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010303 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010304 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010305 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010306 lua_pushstring(s->hlua->T, *arg);
10307 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010308 }
10309
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010310 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010311 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010312
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010313 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010314 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010315 }
10316
10317 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +010010318 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010319 /* finished. */
10320 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010321 /* Catch the return value */
10322 if (lua_gettop(s->hlua->T) > 0)
10323 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010324
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010325 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +020010326 if (act_ret == ACT_RET_YIELD) {
10327 if (flags & ACT_OPT_FINAL)
10328 goto err_yield;
10329
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010330 if (dir == SMP_OPT_DIR_REQ)
10331 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10332 s->hlua->wake_time);
10333 else
10334 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10335 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010336 }
10337 goto end;
10338
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010339 /* yield. */
10340 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +010010341 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010342 if (dir == SMP_OPT_DIR_REQ)
10343 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10344 s->hlua->wake_time);
10345 else
10346 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10347 s->hlua->wake_time);
10348
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010349 /* Some actions can be wake up when a "write" event
10350 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010351 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010352 */
Christopher Faulet51fa3582019-07-26 14:54:52 +020010353 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010354 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010355 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010356 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010357 act_ret = ACT_RET_YIELD;
10358 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010359
10360 /* finished with error. */
10361 case HLUA_E_ERRMSG:
10362 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010363 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010364 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010365 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010366 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010367
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010368 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010369 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010370 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010371
10372 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010373 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010374 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010375
10376 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +020010377 err_yield:
10378 act_ret = ACT_RET_CONT;
Aurelien DARRAGONcf5b75e2023-08-31 21:45:21 +020010379 SEND_ERR(px, "Lua function '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010380 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010381 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010382
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010383 case HLUA_E_ERR:
10384 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010385 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010386 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010387
10388 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010389 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010390 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010391
10392 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010393 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010394 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010395 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010396}
10397
Willy Tarreau144f84a2021-03-02 16:09:26 +010010398struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010399{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010400 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010401
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010402 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010403 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010404 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010405}
10406
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010407static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010408{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010409 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010410 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010411 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010412 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010413 struct task *task;
10414 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010415 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010416
Willy Tarreaubafbe012017-11-24 17:34:44 +010010417 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010418 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010419 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010420 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010421 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010422 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010423 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010424 tcp_ctx->hlua = hlua;
10425 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010426
10427 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010428 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010429 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010430 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010431 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010432 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010433 }
10434 task->nice = 0;
10435 task->context = ctx;
10436 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010437 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010438
10439 /* In the execution wrappers linked with a stream, the
10440 * Lua context can be not initialized. This behavior
10441 * permits to save performances because a systematic
10442 * Lua initialization cause 5% performances loss.
10443 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010444 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010445 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010446 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010447 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010448 }
10449
10450 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010451 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010452
10453 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010454 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010455 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10456 error = lua_tostring(hlua->T, -1);
10457 else
10458 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010459 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010460 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010461 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010462 }
10463
10464 /* Check stack available size. */
10465 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010466 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010467 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010468 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010469 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010470 }
10471
10472 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010473 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010474
10475 /* Create and and push object stream in the stack. */
10476 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010477 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010478 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010479 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010480 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010481 }
10482 hlua->nargs = 1;
10483
10484 /* push keywords in the stack. */
10485 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10486 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010487 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010488 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010489 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010490 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010491 }
10492 lua_pushstring(hlua->T, *arg);
10493 hlua->nargs++;
10494 }
10495
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010496 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010497
10498 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010499 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010500 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010501
Christopher Fauletc9929382022-05-12 11:52:27 +020010502 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010503}
10504
Willy Tarreau60409db2019-08-21 14:14:50 +020010505void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010506{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010507 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010508 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010509 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010510 struct act_rule *rule = ctx->rule;
10511 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010512 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010513
Christopher Faulet31572222023-03-31 11:13:48 +020010514 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10515 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010516
Christopher Faulet31572222023-03-31 11:13:48 +020010517 /* The applet execution is already done. */
10518 if (tcp_ctx->flags & APPLET_DONE)
10519 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010520
10521 /* Execute the function. */
10522 switch (hlua_ctx_resume(hlua, 1)) {
10523 /* finished. */
10524 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010525 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010526 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10527 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010528
10529 /* yield. */
10530 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010531 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010532 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010533 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010534
10535 /* finished with error. */
10536 case HLUA_E_ERRMSG:
10537 /* Display log. */
10538 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010539 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010540 lua_pop(hlua->T, 1);
10541 goto error;
10542
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010543 case HLUA_E_ETMOUT:
10544 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010545 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010546 goto error;
10547
10548 case HLUA_E_NOMEM:
10549 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010550 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010551 goto error;
10552
10553 case HLUA_E_YIELD: /* unexpected */
10554 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010555 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010556 goto error;
10557
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010558 case HLUA_E_ERR:
10559 /* Display log. */
10560 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010561 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010562 goto error;
10563
10564 default:
10565 goto error;
10566 }
10567
Christopher Faulet31572222023-03-31 11:13:48 +020010568out:
10569 /* eat the whole request */
10570 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10571 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010572
Christopher Faulet31572222023-03-31 11:13:48 +020010573error:
10574 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010575 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010576 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010577}
10578
10579static void hlua_applet_tcp_release(struct appctx *ctx)
10580{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010581 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10582
10583 task_destroy(tcp_ctx->task);
10584 tcp_ctx->task = NULL;
10585 hlua_ctx_destroy(tcp_ctx->hlua);
10586 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010587}
10588
Christopher Fauletc9929382022-05-12 11:52:27 +020010589/* The function returns 0 if the initialisation is complete or -1 if
10590 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010591 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010592static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010593{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010594 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010595 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010596 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010597 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010598 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010599 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010600 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010601 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010602
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010603 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010604 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010605 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010606 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010607 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010608 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010609 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010610 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010611 http_ctx->hlua = hlua;
10612 http_ctx->left_bytes = -1;
10613 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010614
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010615 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010616 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010617
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010618 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010619 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010620 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010621 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010622 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010623 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010624 }
10625 task->nice = 0;
10626 task->context = ctx;
10627 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010628 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010629
10630 /* In the execution wrappers linked with a stream, the
10631 * Lua context can be not initialized. This behavior
10632 * permits to save performances because a systematic
10633 * Lua initialization cause 5% performances loss.
10634 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010635 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010636 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010637 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010638 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010639 }
10640
10641 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010642 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010643
10644 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010645 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010646 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10647 error = lua_tostring(hlua->T, -1);
10648 else
10649 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010650 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010651 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010652 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010653 }
10654
10655 /* Check stack available size. */
10656 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010657 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010658 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010659 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010660 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010661 }
10662
10663 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010664 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010665
10666 /* Create and and push object stream in the stack. */
10667 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010668 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010669 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010670 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010671 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010672 }
10673 hlua->nargs = 1;
10674
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010675 /* push keywords in the stack. */
10676 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10677 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010678 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010679 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010680 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010681 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010682 }
10683 lua_pushstring(hlua->T, *arg);
10684 hlua->nargs++;
10685 }
10686
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010687 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010688
10689 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010690 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010691
Christopher Fauletc9929382022-05-12 11:52:27 +020010692 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010693}
10694
Willy Tarreau60409db2019-08-21 14:14:50 +020010695void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010696{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010697 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010698 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010699 struct stream *strm = __sc_strm(sc);
10700 struct channel *req = sc_oc(sc);
10701 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010702 struct act_rule *rule = ctx->rule;
10703 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010704 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010705 struct htx *req_htx, *res_htx;
10706
10707 res_htx = htx_from_buf(&res->buf);
10708
Christopher Faulet31572222023-03-31 11:13:48 +020010709 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10710 goto out;
10711
10712 /* The applet execution is already done. */
10713 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010714 goto out;
10715
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010716 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010717 if (!b_size(&res->buf)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010718 sc_need_room(sc, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010719 goto out;
10720 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010721
10722 /* Set the currently running flag. */
10723 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010724 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010725 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010726 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010727 goto out;
10728 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010729 }
10730
Christopher Faulet31572222023-03-31 11:13:48 +020010731 /* Execute the function. */
10732 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010733 /* finished. */
10734 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010735 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010736 break;
10737
10738 /* yield. */
10739 case HLUA_E_AGAIN:
10740 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010741 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010742 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010743
10744 /* finished with error. */
10745 case HLUA_E_ERRMSG:
10746 /* Display log. */
10747 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010748 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010749 lua_pop(hlua->T, 1);
10750 goto error;
10751
10752 case HLUA_E_ETMOUT:
10753 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010754 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010755 goto error;
10756
10757 case HLUA_E_NOMEM:
10758 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010759 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010760 goto error;
10761
10762 case HLUA_E_YIELD: /* unexpected */
10763 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010764 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010765 goto error;
10766
10767 case HLUA_E_ERR:
10768 /* Display log. */
10769 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010770 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010771 goto error;
10772
10773 default:
10774 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010775 }
10776
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010777 if (http_ctx->flags & APPLET_DONE) {
10778 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010779 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010780
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010781 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010782 goto error;
10783
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010784 /* no more data are expected. If the response buffer is empty
10785 * for a chunked message, be sure to add something (EOT block in
10786 * this case) to have something to send. It is important to be
10787 * sure the EOM flags will be handled by the endpoint.
10788 */
10789 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10790 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010791 sc_need_room(sc, sizeof(struct htx_blk)+1);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010792 goto out;
10793 }
10794 channel_add_input(res, 1);
10795 }
10796
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010797 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010798 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010799 strm->txn->status = http_ctx->status;
10800 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010801 }
10802
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010803 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010804 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010805 /* eat the whole request */
10806 if (co_data(req)) {
10807 req_htx = htx_from_buf(&req->buf);
10808 co_htx_skip(req, req_htx, co_data(req));
10809 htx_to_buf(req_htx, &req->buf);
10810 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010811 return;
10812
10813 error:
10814
10815 /* If we are in HTTP mode, and we are not send any
10816 * data, return a 500 server error in best effort:
10817 * if there is no room available in the buffer,
10818 * just close the connection.
10819 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010820 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010821 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010822
10823 channel_erase(res);
10824 res->buf.data = b_data(err);
10825 memcpy(res->buf.area, b_head(err), b_data(err));
10826 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010827 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010828 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010829 }
Christopher Faulet31572222023-03-31 11:13:48 +020010830 else
10831 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10832
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010833 if (!(strm->flags & SF_ERR_MASK))
10834 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010835 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010836 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010837}
10838
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010839static void hlua_applet_http_release(struct appctx *ctx)
10840{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010841 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10842
10843 task_destroy(http_ctx->task);
10844 http_ctx->task = NULL;
10845 hlua_ctx_destroy(http_ctx->hlua);
10846 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010847}
10848
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010849/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010850 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010851 *
10852 * This function can fail with an abort() due to an Lua critical error.
10853 * We are in the configuration parsing process of HAProxy, this abort() is
10854 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010855 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010856static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10857 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010858{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010859 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010860 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010861
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010862 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010863 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010864 if (!rule->arg.hlua_rule) {
10865 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010866 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010867 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010868
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010869 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010870 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10871 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010872 if (!rule->arg.hlua_rule->args) {
10873 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010874 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010875 }
10876
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010877 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010878 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010879
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010880 /* Expect some arguments */
10881 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010882 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010883 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010884 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010885 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010886 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010887 if (!rule->arg.hlua_rule->args[i]) {
10888 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010889 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010890 }
10891 (*cur_arg)++;
10892 }
10893 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010894
Thierry FOURNIER42148732015-09-02 17:17:33 +020010895 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010896 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010897 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010898
10899 error:
10900 if (rule->arg.hlua_rule) {
10901 if (rule->arg.hlua_rule->args) {
10902 for (i = 0; i < fcn->nargs; i++)
10903 ha_free(&rule->arg.hlua_rule->args[i]);
10904 ha_free(&rule->arg.hlua_rule->args);
10905 }
10906 ha_free(&rule->arg.hlua_rule);
10907 }
10908 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010909}
10910
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010911static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10912 struct act_rule *rule, char **err)
10913{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010914 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010915
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010916 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010917 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010918 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010919 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010920 * the call of this analyzer.
10921 */
10922 if (rule->from != ACT_F_HTTP_REQ) {
10923 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10924 return ACT_RET_PRS_ERR;
10925 }
10926
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010927 /* Memory for the rule. */
10928 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10929 if (!rule->arg.hlua_rule) {
10930 memprintf(err, "out of memory error");
10931 return ACT_RET_PRS_ERR;
10932 }
10933
10934 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010935 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010936
10937 /* TODO: later accept arguments. */
10938 rule->arg.hlua_rule->args = NULL;
10939
10940 /* Add applet pointer in the rule. */
10941 rule->applet.obj_type = OBJ_TYPE_APPLET;
10942 rule->applet.name = fcn->name;
10943 rule->applet.init = hlua_applet_http_init;
10944 rule->applet.fct = hlua_applet_http_fct;
10945 rule->applet.release = hlua_applet_http_release;
10946 rule->applet.timeout = hlua_timeout_applet;
10947
10948 return ACT_RET_PRS_OK;
10949}
10950
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010951/* This function is an LUA binding used for registering
10952 * "sample-conv" functions. It expects a converter name used
10953 * in the haproxy configuration file, and an LUA function.
10954 */
10955__LJMP static int hlua_register_action(lua_State *L)
10956{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010957 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010958 const char *name;
10959 int ref;
10960 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010961 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010962 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010963 struct buffer *trash;
10964 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010965
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010966 /* Initialise the number of expected arguments at 0. */
10967 nargs = 0;
10968
10969 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10970 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010971
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010972 if (hlua_gethlua(L)) {
10973 /* runtime processing */
10974 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10975 }
10976
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010977 /* First argument : converter name. */
10978 name = MAY_LJMP(luaL_checkstring(L, 1));
10979
10980 /* Second argument : environment. */
10981 if (lua_type(L, 2) != LUA_TTABLE)
10982 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10983
10984 /* Third argument : lua function. */
10985 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10986
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010987 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010988 if (lua_gettop(L) >= 4)
10989 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10990
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010991 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010992 lua_pushnil(L);
10993 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010994 if (lua_type(L, -1) != LUA_TSTRING) {
10995 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010996 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010997 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010998
Thierry Fournierf67442e2020-11-28 20:41:07 +010010999 /* Check if action exists */
11000 trash = get_trash_chunk();
11001 chunk_printf(trash, "lua.%s", name);
11002 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
11003 akw = tcp_req_cont_action(trash->area);
11004 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
11005 akw = tcp_res_cont_action(trash->area);
11006 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
11007 akw = action_http_req_custom(trash->area);
11008 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
11009 akw = action_http_res_custom(trash->area);
11010 } else {
11011 akw = NULL;
11012 }
11013 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011014 fcn = akw->private;
11015 if (fcn->function_ref[hlua_state_id] != -1) {
11016 ha_warning("Trying to register action 'lua.%s' more than once. "
11017 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011018 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011019 }
11020 fcn->function_ref[hlua_state_id] = ref;
11021
11022 /* pop the environment string. */
11023 lua_pop(L, 1);
11024 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011025 }
11026
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011027 /* Check required environment. Only accepted "http" or "tcp". */
11028 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020011029 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011030 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011031 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011032 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011033 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011034 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011035
11036 /* Fill fcn. */
11037 fcn->name = strdup(name);
11038 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011039 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010011040 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011041
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011042 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010011043 fcn->nargs = nargs;
11044
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011045 /* List head */
11046 akl->list.n = akl->list.p = NULL;
11047
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011048 /* action keyword. */
11049 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020011050 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011051 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011052 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011053
11054 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11055
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011056 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011057 akl->kw[0].private = fcn;
11058 akl->kw[0].parse = action_register_lua;
11059
11060 /* select the action registering point. */
11061 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
11062 tcp_req_cont_keywords_register(akl);
11063 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
11064 tcp_res_cont_keywords_register(akl);
11065 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
11066 http_req_keywords_register(akl);
11067 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
11068 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011069 else {
11070 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011071 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011072 if (akl)
11073 ha_free((char **)&(akl->kw[0].kw));
11074 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011075 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011076 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
11077 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011078 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011079
11080 /* pop the environment string. */
11081 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011082
11083 /* reset for next loop */
11084 akl = NULL;
11085 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011086 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011087 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011088
11089 alloc_error:
11090 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011091 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011092 ha_free(&akl);
11093 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11094 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011095}
11096
11097static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
11098 struct act_rule *rule, char **err)
11099{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020011100 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011101
Christopher Faulet280f85b2019-07-15 15:02:04 +020011102 if (px->mode == PR_MODE_HTTP) {
11103 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010011104 return ACT_RET_PRS_ERR;
11105 }
11106
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011107 /* Memory for the rule. */
11108 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11109 if (!rule->arg.hlua_rule) {
11110 memprintf(err, "out of memory error");
11111 return ACT_RET_PRS_ERR;
11112 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011113
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011114 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011115 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011116
11117 /* TODO: later accept arguments. */
11118 rule->arg.hlua_rule->args = NULL;
11119
11120 /* Add applet pointer in the rule. */
11121 rule->applet.obj_type = OBJ_TYPE_APPLET;
11122 rule->applet.name = fcn->name;
11123 rule->applet.init = hlua_applet_tcp_init;
11124 rule->applet.fct = hlua_applet_tcp_fct;
11125 rule->applet.release = hlua_applet_tcp_release;
11126 rule->applet.timeout = hlua_timeout_applet;
11127
11128 return 0;
11129}
11130
11131/* This function is an LUA binding used for registering
11132 * "sample-conv" functions. It expects a converter name used
11133 * in the haproxy configuration file, and an LUA function.
11134 */
11135__LJMP static int hlua_register_service(lua_State *L)
11136{
11137 struct action_kw_list *akl;
11138 const char *name;
11139 const char *env;
11140 int ref;
11141 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011142 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011143 struct buffer *trash;
11144 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011145
11146 MAY_LJMP(check_args(L, 3, "register_service"));
11147
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011148 if (hlua_gethlua(L)) {
11149 /* runtime processing */
11150 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
11151 }
11152
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011153 /* First argument : converter name. */
11154 name = MAY_LJMP(luaL_checkstring(L, 1));
11155
11156 /* Second argument : environment. */
11157 env = MAY_LJMP(luaL_checkstring(L, 2));
11158
11159 /* Third argument : lua function. */
11160 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11161
Thierry Fournierf67442e2020-11-28 20:41:07 +010011162 /* Check for service already registered */
11163 trash = get_trash_chunk();
11164 chunk_printf(trash, "lua.%s", name);
11165 akw = service_find(trash->area);
11166 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011167 fcn = akw->private;
11168 if (fcn->function_ref[hlua_state_id] != -1) {
11169 ha_warning("Trying to register service 'lua.%s' more than once. "
11170 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011171 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011172 }
11173 fcn->function_ref[hlua_state_id] = ref;
11174 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011175 }
11176
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011177 /* Allocate and fill the sample fetch keyword struct. */
11178 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
11179 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011180 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011181 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011182 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011183 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011184
11185 /* Fill fcn. */
11186 len = strlen("<lua.>") + strlen(name) + 1;
11187 fcn->name = calloc(1, len);
11188 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011189 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011190 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010011191 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011192
11193 /* List head */
11194 akl->list.n = akl->list.p = NULL;
11195
11196 /* converter keyword. */
11197 len = strlen("lua.") + strlen(name) + 1;
11198 akl->kw[0].kw = calloc(1, len);
11199 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011200 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011201
11202 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11203
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010011204 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011205 if (strcmp(env, "tcp") == 0)
11206 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011207 else if (strcmp(env, "http") == 0)
11208 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011209 else {
11210 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011211 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011212 if (akl)
11213 ha_free((char **)&(akl->kw[0].kw));
11214 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011215 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010011216 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020011217 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011218
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011219 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011220 akl->kw[0].private = fcn;
11221
11222 /* End of array. */
11223 memset(&akl->kw[1], 0, sizeof(*akl->kw));
11224
11225 /* Register this new converter */
11226 service_keywords_register(akl);
11227
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011228 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011229
11230 alloc_error:
11231 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011232 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011233 ha_free(&akl);
11234 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11235 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011236}
11237
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011238/* This function initialises Lua cli handler. It copies the
11239 * arguments in the Lua stack and create channel IO objects.
11240 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020011241static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011242{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011243 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011244 struct hlua *hlua;
11245 struct hlua_function *fcn;
11246 int i;
11247 const char *error;
11248
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011249 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011250 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011251
Willy Tarreaubafbe012017-11-24 17:34:44 +010011252 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011253 if (!hlua) {
11254 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011255 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011256 }
11257 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011258 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011259
11260 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050011261 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011262 * applet_http. It is absolutely compatible.
11263 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011264 ctx->task = task_new_here();
11265 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010011266 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011267 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011268 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011269 ctx->task->nice = 0;
11270 ctx->task->context = appctx;
11271 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011272
11273 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011274 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011275 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011276 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011277 }
11278
11279 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011280 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011281 if (lua_type(hlua->T, -1) == LUA_TSTRING)
11282 error = lua_tostring(hlua->T, -1);
11283 else
11284 error = "critical error";
11285 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
11286 goto error;
11287 }
11288
11289 /* Check stack available size. */
11290 if (!lua_checkstack(hlua->T, 2)) {
11291 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11292 goto error;
11293 }
11294
11295 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011296 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011297
11298 /* Once the arguments parsed, the CLI is like an AppletTCP,
11299 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011300 */
11301 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
11302 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11303 goto error;
11304 }
11305 hlua->nargs = 1;
11306
11307 /* push keywords in the stack. */
11308 for (i = 0; *args[i]; i++) {
11309 /* Check stack available size. */
11310 if (!lua_checkstack(hlua->T, 1)) {
11311 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11312 goto error;
11313 }
11314 lua_pushstring(hlua->T, args[i]);
11315 hlua->nargs++;
11316 }
11317
11318 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011319 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011320
11321 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011322 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011323
11324 /* It's ok */
11325 return 0;
11326
11327 /* It's not ok. */
11328error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011329 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011330 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011331 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011332 return 1;
11333}
11334
11335static int hlua_cli_io_handler_fct(struct appctx *appctx)
11336{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011337 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011338 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020011339 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011340 struct hlua_function *fcn;
11341
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011342 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020011343 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011344 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011345
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011346 /* Execute the function. */
11347 switch (hlua_ctx_resume(hlua, 1)) {
11348
11349 /* finished. */
11350 case HLUA_E_OK:
11351 return 1;
11352
11353 /* yield. */
11354 case HLUA_E_AGAIN:
11355 /* We want write. */
11356 if (HLUA_IS_WAKERESWR(hlua))
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020011357 sc_need_room(sc, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011358 /* Set the timeout. */
11359 if (hlua->wake_time != TICK_ETERNITY)
11360 task_schedule(hlua->task, hlua->wake_time);
11361 return 0;
11362
11363 /* finished with error. */
11364 case HLUA_E_ERRMSG:
11365 /* Display log. */
11366 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
11367 fcn->name, lua_tostring(hlua->T, -1));
11368 lua_pop(hlua->T, 1);
11369 return 1;
11370
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011371 case HLUA_E_ETMOUT:
11372 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
11373 fcn->name);
11374 return 1;
11375
11376 case HLUA_E_NOMEM:
11377 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
11378 fcn->name);
11379 return 1;
11380
11381 case HLUA_E_YIELD: /* unexpected */
11382 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
11383 fcn->name);
11384 return 1;
11385
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011386 case HLUA_E_ERR:
11387 /* Display log. */
11388 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11389 fcn->name);
11390 return 1;
11391
11392 default:
11393 return 1;
11394 }
11395
11396 return 1;
11397}
11398
11399static void hlua_cli_io_release_fct(struct appctx *appctx)
11400{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011401 struct hlua_cli_ctx *ctx = appctx->svcctx;
11402
11403 hlua_ctx_destroy(ctx->hlua);
11404 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011405}
11406
11407/* This function is an LUA binding used for registering
11408 * new keywords in the cli. It expects a list of keywords
11409 * which are the "path". It is limited to 5 keywords. A
11410 * description of the command, a function to be executed
11411 * for the parsing and a function for io handlers.
11412 */
11413__LJMP static int hlua_register_cli(lua_State *L)
11414{
11415 struct cli_kw_list *cli_kws;
11416 const char *message;
11417 int ref_io;
11418 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011419 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011420 int index;
11421 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011422 struct buffer *trash;
11423 const char *kw[5];
11424 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011425 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011426 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011427
11428 MAY_LJMP(check_args(L, 3, "register_cli"));
11429
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011430 if (hlua_gethlua(L)) {
11431 /* runtime processing */
11432 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11433 }
11434
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011435 /* First argument : an array of maximum 5 keywords. */
11436 if (!lua_istable(L, 1))
11437 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11438
11439 /* Second argument : string with contextual message. */
11440 message = MAY_LJMP(luaL_checkstring(L, 2));
11441
11442 /* Third and fourth argument : lua function. */
11443 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11444
Thierry Fournierf67442e2020-11-28 20:41:07 +010011445 /* Check for CLI service already registered */
11446 trash = get_trash_chunk();
11447 index = 0;
11448 lua_pushnil(L);
11449 memset(kw, 0, sizeof(kw));
11450 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011451 if (index >= CLI_PREFIX_KW_NB) {
11452 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011453 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 +010011454 }
11455 if (lua_type(L, -1) != LUA_TSTRING) {
11456 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011457 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011458 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011459 kw[index] = lua_tostring(L, -1);
11460 if (index == 0)
11461 chunk_printf(trash, "%s", kw[index]);
11462 else
11463 chunk_appendf(trash, " %s", kw[index]);
11464 index++;
11465 lua_pop(L, 1);
11466 }
11467 cli_kw = cli_find_kw_exact((char **)kw);
11468 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011469 fcn = cli_kw->private;
11470 if (fcn->function_ref[hlua_state_id] != -1) {
11471 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11472 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011473 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011474 }
11475 fcn->function_ref[hlua_state_id] = ref_io;
11476 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011477 }
11478
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011479 /* Allocate and fill the sample fetch keyword struct. */
11480 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011481 if (!cli_kws) {
11482 errmsg = "Lua out of memory error.";
11483 goto error;
11484 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011485 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011486 if (!fcn) {
11487 errmsg = "Lua out of memory error.";
11488 goto error;
11489 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011490
11491 /* Fill path. */
11492 index = 0;
11493 lua_pushnil(L);
11494 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011495 if (index >= 5) {
11496 errmsg = "1st argument must be a table with a maximum of 5 entries";
11497 goto error;
11498 }
11499 if (lua_type(L, -1) != LUA_TSTRING) {
11500 errmsg = "1st argument must be a table filled with strings";
11501 goto error;
11502 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011503 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011504 if (!cli_kws->kw[0].str_kw[index]) {
11505 errmsg = "Lua out of memory error.";
11506 goto error;
11507 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011508 index++;
11509 lua_pop(L, 1);
11510 }
11511
11512 /* Copy help message. */
11513 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011514 if (!cli_kws->kw[0].usage) {
11515 errmsg = "Lua out of memory error.";
11516 goto error;
11517 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011518
11519 /* Fill fcn io handler. */
11520 len = strlen("<lua.cli>") + 1;
11521 for (i = 0; i < index; i++)
11522 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11523 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011524 if (!fcn->name) {
11525 errmsg = "Lua out of memory error.";
11526 goto error;
11527 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011528
11529 end = fcn->name;
11530 len = 8;
11531 memcpy(end, "<lua.cli", len);
11532 end += len;
11533
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011534 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011535 *(end++) = '.';
11536 len = strlen(cli_kws->kw[0].str_kw[i]);
11537 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11538 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011539 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011540 *(end++) = '>';
11541 *(end++) = 0;
11542
Thierry Fournierc7492592020-11-28 23:57:24 +010011543 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011544
11545 /* Fill last entries. */
11546 cli_kws->kw[0].private = fcn;
11547 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11548 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11549 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11550
11551 /* Register this new converter */
11552 cli_register_kw(cli_kws);
11553
11554 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011555
11556 error:
11557 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011558 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011559 if (cli_kws) {
11560 for (i = 0; i < index; i++)
11561 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11562 ha_free((char **)&(cli_kws->kw[0].usage));
11563 }
11564 ha_free(&cli_kws);
11565 WILL_LJMP(luaL_error(L, errmsg));
11566 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011567}
11568
Christopher Faulet69c581a2021-05-31 08:54:04 +020011569static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11570{
11571 struct hlua_flt_config *conf = fconf->conf;
11572 lua_State *L;
11573 int error, pos, state_id, flt_ref;
11574
11575 state_id = reg_flt_to_stack_id(conf->reg);
11576 L = hlua_states[state_id];
11577 pos = lua_gettop(L);
11578
11579 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011580 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011581
11582 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011583 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011584
11585 /* Duplicate the filter class so each filter will have its own copy */
11586 lua_newtable(L);
11587 lua_pushnil(L);
11588
11589 while (lua_next(L, pos+2)) {
11590 lua_pushvalue(L, -2);
11591 lua_insert(L, -2);
11592 lua_settable(L, -4);
11593 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011594 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011595
11596 /* Remove the original lua filter class from the stack */
11597 lua_pop(L, 1);
11598
11599 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011600 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011601
11602 /* extra args are pushed in a table */
11603 lua_newtable(L);
11604 for (pos = 0; conf->args[pos]; pos++) {
11605 /* Check stack available size. */
11606 if (!lua_checkstack(L, 1)) {
11607 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11608 goto error;
11609 }
11610 lua_pushstring(L, conf->args[pos]);
11611 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11612 }
11613
11614 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11615 switch (error) {
11616 case LUA_OK:
11617 /* replace the filter ref */
11618 conf->ref[state_id] = flt_ref;
11619 break;
11620 case LUA_ERRRUN:
11621 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11622 goto error;
11623 case LUA_ERRMEM:
11624 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11625 goto error;
11626 case LUA_ERRERR:
11627 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11628 goto error;
11629#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11630 case LUA_ERRGCMM:
11631 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11632 goto error;
11633#endif
11634 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011635 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011636 goto error;
11637 }
11638
11639 lua_settop(L, 0);
11640 return 0;
11641
11642 error:
11643 lua_settop(L, 0);
11644 return -1;
11645}
11646
11647static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11648{
11649 struct hlua_flt_config *conf = fconf->conf;
11650 lua_State *L;
11651 int state_id;
11652
11653 if (!conf)
11654 return;
11655
11656 state_id = reg_flt_to_stack_id(conf->reg);
11657 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011658 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011659}
11660
11661static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11662{
11663 struct hlua_flt_config *conf = fconf->conf;
11664 int state_id = reg_flt_to_stack_id(conf->reg);
11665
11666 /* Rely on per-thread init for global scripts */
11667 if (!state_id)
11668 return hlua_filter_init_per_thread(px, fconf);
11669 return 0;
11670}
11671
11672static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11673{
11674
11675 if (fconf->conf) {
11676 struct hlua_flt_config *conf = fconf->conf;
11677 int state_id = reg_flt_to_stack_id(conf->reg);
11678 int pos;
11679
11680 /* Rely on per-thread deinit for global scripts */
11681 if (!state_id)
11682 hlua_filter_deinit_per_thread(px, fconf);
11683
11684 for (pos = 0; conf->args[pos]; pos++)
11685 free(conf->args[pos]);
11686 free(conf->args);
11687 }
11688 ha_free(&fconf->conf);
11689 ha_free((char **)&fconf->id);
11690 ha_free(&fconf->ops);
11691}
11692
11693static int hlua_filter_new(struct stream *s, struct filter *filter)
11694{
11695 struct hlua_flt_config *conf = FLT_CONF(filter);
11696 struct hlua_flt_ctx *flt_ctx = NULL;
11697 int ret = 1;
11698
Aurelien DARRAGONb25d5d32023-08-09 14:56:19 +020011699 if (!hlua_stream_ctx_prepare(s, reg_flt_to_stack_id(conf->reg))) {
11700 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11701 conf->reg->name);
11702 ret = 0;
11703 goto end;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011704 }
11705
11706 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11707 if (!flt_ctx) {
11708 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11709 conf->reg->name);
11710 ret = 0;
11711 goto end;
11712 }
11713 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11714 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11715 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11716 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11717 conf->reg->name);
11718 ret = 0;
11719 goto end;
11720 }
11721 HLUA_INIT(flt_ctx->hlua[0]);
11722 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011723 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11724 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011725 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11726 conf->reg->name);
11727 ret = 0;
11728 goto end;
11729 }
11730
11731 if (!HLUA_IS_RUNNING(s->hlua)) {
11732 /* The following Lua calls can fail. */
11733 if (!SET_SAFE_LJMP(s->hlua)) {
11734 const char *error;
11735
11736 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11737 error = lua_tostring(s->hlua->T, -1);
11738 else
11739 error = "critical error";
11740 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11741 ret = 0;
11742 goto end;
11743 }
11744
11745 /* Check stack size. */
11746 if (!lua_checkstack(s->hlua->T, 1)) {
11747 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011748 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011749 ret = 0;
11750 goto end;
11751 }
11752
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011753 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011754 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11755 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11756 conf->reg->name);
11757 RESET_SAFE_LJMP(s->hlua);
11758 ret = 0;
11759 goto end;
11760 }
11761 lua_insert(s->hlua->T, -2);
11762
11763 /* Push the copy on the stack */
11764 s->hlua->nargs = 1;
11765
11766 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011767 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011768
11769 /* At this point the execution is safe. */
11770 RESET_SAFE_LJMP(s->hlua);
11771 }
11772
11773 switch (hlua_ctx_resume(s->hlua, 0)) {
11774 case HLUA_E_OK:
11775 /* Nothing returned or not a table, ignore the filter for current stream */
11776 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11777 ret = 0;
11778 goto end;
11779 }
11780
11781 /* Attached the filter pointer to the ctx */
11782 lua_pushstring(s->hlua->T, "__filter");
11783 lua_pushlightuserdata(s->hlua->T, filter);
11784 lua_settable(s->hlua->T, -3);
11785
11786 /* Save a ref on the filter ctx */
11787 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011788 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011789 filter->ctx = flt_ctx;
11790 break;
11791 case HLUA_E_ERRMSG:
11792 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11793 ret = -1;
11794 goto end;
11795 case HLUA_E_ETMOUT:
11796 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11797 ret = 0;
11798 goto end;
11799 case HLUA_E_NOMEM:
11800 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11801 ret = 0;
11802 goto end;
11803 case HLUA_E_AGAIN:
11804 case HLUA_E_YIELD:
11805 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11806 " are not allowed from 'new' function.\n", conf->reg->name);
11807 ret = 0;
11808 goto end;
11809 case HLUA_E_ERR:
11810 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11811 ret = 0;
11812 goto end;
11813 default:
11814 ret = 0;
11815 goto end;
11816 }
11817
11818 end:
11819 if (s->hlua)
11820 lua_settop(s->hlua->T, 0);
11821 if (ret <= 0) {
11822 if (flt_ctx) {
11823 hlua_ctx_destroy(flt_ctx->hlua[0]);
11824 hlua_ctx_destroy(flt_ctx->hlua[1]);
11825 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11826 }
11827 }
11828 return ret;
11829}
11830
11831static void hlua_filter_delete(struct stream *s, struct filter *filter)
11832{
11833 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11834
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011835 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011836 hlua_ctx_destroy(flt_ctx->hlua[0]);
11837 hlua_ctx_destroy(flt_ctx->hlua[1]);
11838 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11839 filter->ctx = NULL;
11840}
11841
Christopher Faulet9f55a502020-02-25 15:21:02 +010011842static int hlua_filter_from_payload(struct filter *filter)
11843{
11844 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11845
11846 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11847}
11848
Christopher Fauletc404f112020-02-26 15:03:09 +010011849static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11850 int dir, unsigned int flags)
11851{
11852 struct hlua *flt_hlua;
11853 struct hlua_flt_config *conf = FLT_CONF(filter);
11854 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11855 unsigned int hflags = HLUA_TXN_FLT_CTX;
11856 int ret = 1;
11857
11858 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11859 if (!flt_hlua)
11860 goto end;
11861
11862 if (!HLUA_IS_RUNNING(flt_hlua)) {
11863 int extra_idx = lua_gettop(flt_hlua->T);
11864
11865 /* The following Lua calls can fail. */
11866 if (!SET_SAFE_LJMP(flt_hlua)) {
11867 const char *error;
11868
11869 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11870 error = lua_tostring(flt_hlua->T, -1);
11871 else
11872 error = "critical error";
11873 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11874 goto end;
11875 }
11876
11877 /* Check stack size. */
11878 if (!lua_checkstack(flt_hlua->T, 3)) {
11879 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11880 RESET_SAFE_LJMP(flt_hlua);
11881 goto end;
11882 }
11883
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011884 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011885 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11886 RESET_SAFE_LJMP(flt_hlua);
11887 goto end;
11888 }
11889 lua_insert(flt_hlua->T, -2);
11890
11891 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11892 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11893 RESET_SAFE_LJMP(flt_hlua);
11894 goto end;
11895 }
11896 flt_hlua->nargs = 2;
11897
11898 if (flags & HLUA_FLT_CB_ARG_CHN) {
11899 if (dir == SMP_OPT_DIR_REQ)
11900 lua_getfield(flt_hlua->T, -1, "req");
11901 else
11902 lua_getfield(flt_hlua->T, -1, "res");
11903 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11904 lua_pushstring(flt_hlua->T, "__filter");
11905 lua_pushlightuserdata(flt_hlua->T, filter);
11906 lua_settable(flt_hlua->T, -3);
11907 }
11908 flt_hlua->nargs++;
11909 }
11910 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011911 if (dir == SMP_OPT_DIR_REQ)
11912 lua_getfield(flt_hlua->T, -1, "http_req");
11913 else
11914 lua_getfield(flt_hlua->T, -1, "http_res");
11915 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11916 lua_pushstring(flt_hlua->T, "__filter");
11917 lua_pushlightuserdata(flt_hlua->T, filter);
11918 lua_settable(flt_hlua->T, -3);
11919 }
11920 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011921 }
11922
11923 /* Check stack size. */
11924 if (!lua_checkstack(flt_hlua->T, 1)) {
11925 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11926 RESET_SAFE_LJMP(flt_hlua);
11927 goto end;
11928 }
11929
11930 while (extra_idx--) {
11931 lua_pushvalue(flt_hlua->T, 1);
11932 lua_remove(flt_hlua->T, 1);
11933 flt_hlua->nargs++;
11934 }
11935
11936 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011937 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010011938
11939 /* At this point the execution is safe. */
11940 RESET_SAFE_LJMP(flt_hlua);
11941 }
11942
11943 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11944 case HLUA_E_OK:
11945 /* Catch the return value if it required */
11946 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11947 ret = lua_tointeger(flt_hlua->T, -1);
11948 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11949 }
11950
11951 /* Set timeout in the required channel. */
11952 if (flt_hlua->wake_time != TICK_ETERNITY) {
11953 if (dir == SMP_OPT_DIR_REQ)
11954 s->req.analyse_exp = flt_hlua->wake_time;
11955 else
11956 s->res.analyse_exp = flt_hlua->wake_time;
11957 }
11958 break;
11959 case HLUA_E_AGAIN:
11960 /* Set timeout in the required channel. */
11961 if (flt_hlua->wake_time != TICK_ETERNITY) {
11962 if (dir == SMP_OPT_DIR_REQ)
11963 s->req.analyse_exp = flt_hlua->wake_time;
11964 else
11965 s->res.analyse_exp = flt_hlua->wake_time;
11966 }
11967 /* Some actions can be wake up when a "write" event
11968 * is detected on a response channel. This is useful
11969 * only for actions targeted on the requests.
11970 */
11971 if (HLUA_IS_WAKERESWR(flt_hlua))
11972 s->res.flags |= CF_WAKE_WRITE;
11973 if (HLUA_IS_WAKEREQWR(flt_hlua))
11974 s->req.flags |= CF_WAKE_WRITE;
11975 ret = 0;
11976 goto end;
11977 case HLUA_E_ERRMSG:
11978 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11979 ret = -1;
11980 goto end;
11981 case HLUA_E_ETMOUT:
11982 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11983 goto end;
11984 case HLUA_E_NOMEM:
11985 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11986 goto end;
11987 case HLUA_E_YIELD:
11988 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11989 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11990 goto end;
11991 case HLUA_E_ERR:
11992 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11993 goto end;
11994 default:
11995 goto end;
11996 }
11997
11998
11999 end:
12000 return ret;
12001}
12002
12003static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
12004{
12005 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12006
12007 flt_ctx->flags = 0;
12008 return hlua_filter_callback(s, filter, "start_analyze",
12009 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12010 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
12011}
12012
12013static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
12014{
12015 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12016
12017 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12018 return hlua_filter_callback(s, filter, "end_analyze",
12019 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12020 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
12021}
12022
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012023static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
12024{
12025 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12026
12027 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12028 return hlua_filter_callback(s, filter, "http_headers",
12029 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12030 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12031}
12032
12033static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
12034 unsigned int offset, unsigned int len)
12035{
12036 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12037 struct hlua *flt_hlua;
12038 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12039 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12040 int ret;
12041
12042 flt_hlua = flt_ctx->hlua[idx];
12043 flt_ctx->cur_off[idx] = offset;
12044 flt_ctx->cur_len[idx] = len;
12045 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12046 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12047 if (ret != -1) {
12048 ret = flt_ctx->cur_len[idx];
12049 if (lua_gettop(flt_hlua->T) > 0) {
12050 ret = lua_tointeger(flt_hlua->T, -1);
12051 if (ret > flt_ctx->cur_len[idx])
12052 ret = flt_ctx->cur_len[idx];
12053 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12054 }
12055 }
12056 return ret;
12057}
12058
12059static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
12060{
12061 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12062
12063 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12064 return hlua_filter_callback(s, filter, "http_end",
12065 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12066 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12067}
12068
Christopher Fauletc404f112020-02-26 15:03:09 +010012069static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
12070 unsigned int offset, unsigned int len)
12071{
12072 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12073 struct hlua *flt_hlua;
12074 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12075 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12076 int ret;
12077
12078 flt_hlua = flt_ctx->hlua[idx];
12079 flt_ctx->cur_off[idx] = offset;
12080 flt_ctx->cur_len[idx] = len;
12081 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12082 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
12083 if (ret != -1) {
12084 ret = flt_ctx->cur_len[idx];
12085 if (lua_gettop(flt_hlua->T) > 0) {
12086 ret = lua_tointeger(flt_hlua->T, -1);
12087 if (ret > flt_ctx->cur_len[idx])
12088 ret = flt_ctx->cur_len[idx];
12089 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12090 }
12091 }
12092 return ret;
12093}
12094
Christopher Faulet69c581a2021-05-31 08:54:04 +020012095static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
12096 struct flt_conf *fconf, char **err, void *private)
12097{
12098 struct hlua_reg_filter *reg_flt = private;
12099 lua_State *L;
12100 struct hlua_flt_config *conf = NULL;
12101 const char *flt_id = NULL;
12102 int state_id, pos, flt_flags = 0;
12103 struct flt_ops *hlua_flt_ops = NULL;
12104
12105 state_id = reg_flt_to_stack_id(reg_flt);
12106 L = hlua_states[state_id];
12107
12108 /* Initialize the filter ops with default callbacks */
12109 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012110 if (!hlua_flt_ops)
12111 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012112 hlua_flt_ops->init = hlua_filter_init;
12113 hlua_flt_ops->deinit = hlua_filter_deinit;
12114 if (state_id) {
12115 /* Set per-thread callback if script is loaded per-thread */
12116 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
12117 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
12118 }
12119 hlua_flt_ops->attach = hlua_filter_new;
12120 hlua_flt_ops->detach = hlua_filter_delete;
12121
12122 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012123 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012124
Christopher Fauletc404f112020-02-26 15:03:09 +010012125 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
12126 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
12127 lua_pop(L, 1);
12128 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
12129 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
12130 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012131 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
12132 hlua_flt_ops->http_headers = hlua_filter_http_headers;
12133 lua_pop(L, 1);
12134 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
12135 hlua_flt_ops->http_payload = hlua_filter_http_payload;
12136 lua_pop(L, 1);
12137 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
12138 hlua_flt_ops->http_end = hlua_filter_http_end;
12139 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010012140 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
12141 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
12142 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012143
12144 /* Get id and flags of the filter class */
12145 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
12146 flt_id = lua_tostring(L, -1);
12147 lua_pop(L, 1);
12148 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
12149 flt_flags = lua_tointeger(L, -1);
12150 lua_pop(L, 1);
12151
12152 /* Create the filter config */
12153 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012154 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020012155 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012156 conf->reg = reg_flt;
12157
12158 /* duplicate args */
12159 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
12160 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012161 if (!conf->args)
12162 goto error;
12163 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012164 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012165 if (!conf->args[pos])
12166 goto error;
12167 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012168 conf->args[pos] = NULL;
12169 *cur_arg += pos + 1;
12170
Christopher Fauletc86bb872021-08-13 08:33:57 +020012171 if (flt_id) {
12172 fconf->id = strdup(flt_id);
12173 if (!fconf->id)
12174 goto error;
12175 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012176 fconf->flags = flt_flags;
12177 fconf->conf = conf;
12178 fconf->ops = hlua_flt_ops;
12179
12180 lua_settop(L, 0);
12181 return 0;
12182
12183 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020012184 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012185 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012186 if (conf && conf->args) {
12187 for (pos = 0; conf->args[pos]; pos++)
12188 free(conf->args[pos]);
12189 free(conf->args);
12190 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012191 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012192 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012193 lua_settop(L, 0);
12194 return -1;
12195}
12196
Christopher Fauletc404f112020-02-26 15:03:09 +010012197__LJMP static int hlua_register_data_filter(lua_State *L)
12198{
12199 struct filter *filter;
12200 struct channel *chn;
12201
12202 MAY_LJMP(check_args(L, 2, "register_data_filter"));
12203 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12204 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12205
12206 lua_getfield(L, 1, "__filter");
12207 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12208 filter = lua_touserdata (L, -1);
12209 lua_pop(L, 1);
12210
12211 register_data_filter(chn_strm(chn), chn, filter);
12212 return 1;
12213}
12214
12215__LJMP static int hlua_unregister_data_filter(lua_State *L)
12216{
12217 struct filter *filter;
12218 struct channel *chn;
12219
12220 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
12221 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12222 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12223
12224 lua_getfield(L, 1, "__filter");
12225 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12226 filter = lua_touserdata (L, -1);
12227 lua_pop(L, 1);
12228
12229 unregister_data_filter(chn_strm(chn), chn, filter);
12230 return 1;
12231}
12232
Christopher Faulet69c581a2021-05-31 08:54:04 +020012233/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012234 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020012235 * parse configuration arguments.
12236 */
12237__LJMP static int hlua_register_filter(lua_State *L)
12238{
12239 struct buffer *trash;
12240 struct flt_kw_list *fkl;
12241 struct flt_kw *fkw;
12242 const char *name;
12243 struct hlua_reg_filter *reg_flt= NULL;
12244 int flt_ref, fun_ref;
12245 int len;
12246
12247 MAY_LJMP(check_args(L, 3, "register_filter"));
12248
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010012249 if (hlua_gethlua(L)) {
12250 /* runtime processing */
12251 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
12252 }
12253
Christopher Faulet69c581a2021-05-31 08:54:04 +020012254 /* First argument : filter name. */
12255 name = MAY_LJMP(luaL_checkstring(L, 1));
12256
12257 /* Second argument : The filter class */
12258 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
12259
12260 /* Third argument : lua function. */
12261 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
12262
12263 trash = get_trash_chunk();
12264 chunk_printf(trash, "lua.%s", name);
12265 fkw = flt_find_kw(trash->area);
12266 if (fkw != NULL) {
12267 reg_flt = fkw->private;
12268 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
12269 ha_warning("Trying to register filter 'lua.%s' more than once. "
12270 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012271 if (reg_flt->flt_ref[hlua_state_id] != -1)
12272 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
12273 if (reg_flt->fun_ref[hlua_state_id] != -1)
12274 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012275 }
12276 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12277 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12278 return 0;
12279 }
12280
12281 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
12282 if (!fkl)
12283 goto alloc_error;
12284 fkl->scope = "HLUA";
12285
12286 reg_flt = new_hlua_reg_filter(name);
12287 if (!reg_flt)
12288 goto alloc_error;
12289
12290 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12291 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12292
12293 /* The filter keyword */
12294 len = strlen("lua.") + strlen(name) + 1;
12295 fkl->kw[0].kw = calloc(1, len);
12296 if (!fkl->kw[0].kw)
12297 goto alloc_error;
12298
12299 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
12300
12301 fkl->kw[0].parse = hlua_filter_parse_fct;
12302 fkl->kw[0].private = reg_flt;
12303 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
12304
12305 /* Register this new filter */
12306 flt_register_keywords(fkl);
12307
12308 return 0;
12309
12310 alloc_error:
12311 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012312 hlua_unref(L, flt_ref);
12313 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012314 ha_free(&fkl);
12315 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
12316 return 0; /* Never reached */
12317}
12318
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012319static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012320 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012321 char **err, unsigned int *timeout)
12322{
12323 const char *error;
12324
12325 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020012326 if (error == PARSE_TIME_OVER) {
12327 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
12328 args[1], args[0]);
12329 return -1;
12330 }
12331 else if (error == PARSE_TIME_UNDER) {
12332 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
12333 args[1], args[0]);
12334 return -1;
12335 }
12336 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012337 memprintf(err, "%s: invalid timeout", args[0]);
12338 return -1;
12339 }
12340 return 0;
12341}
12342
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012343static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
12344 const struct proxy *defpx, const char *file, int line,
12345 char **err)
12346{
12347 return hlua_read_timeout(args, section_type, curpx, defpx,
12348 file, line, err, &hlua_timeout_burst);
12349}
12350
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012351static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012352 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012353 char **err)
12354{
12355 return hlua_read_timeout(args, section_type, curpx, defpx,
12356 file, line, err, &hlua_timeout_session);
12357}
12358
12359static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012360 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012361 char **err)
12362{
12363 return hlua_read_timeout(args, section_type, curpx, defpx,
12364 file, line, err, &hlua_timeout_task);
12365}
12366
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012367static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012368 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012369 char **err)
12370{
12371 return hlua_read_timeout(args, section_type, curpx, defpx,
12372 file, line, err, &hlua_timeout_applet);
12373}
12374
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012375static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012376 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012377 char **err)
12378{
12379 char *error;
12380
12381 hlua_nb_instruction = strtoll(args[1], &error, 10);
12382 if (*error != '\0') {
12383 memprintf(err, "%s: invalid number", args[0]);
12384 return -1;
12385 }
12386 return 0;
12387}
12388
Willy Tarreau32f61e22015-03-18 17:54:59 +010012389static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012390 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012391 char **err)
12392{
12393 char *error;
12394
12395 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012396 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012397 return -1;
12398 }
12399 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12400 if (*error != '\0') {
12401 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12402 return -1;
12403 }
12404 return 0;
12405}
12406
12407
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012408/* This function is called by the main configuration key "lua-load". It loads and
12409 * execute an lua file during the parsing of the HAProxy configuration file. It is
12410 * the main lua entry point.
12411 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012412 * This function runs with the HAProxy keywords API. It returns -1 if an error
12413 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012414 *
12415 * In some error case, LUA set an error message in top of the stack. This function
12416 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012417 *
12418 * This function can fail with an abort() due to an Lua critical error.
12419 * We are in the configuration parsing process of HAProxy, this abort() is
12420 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012421 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012422static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012423{
12424 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012425 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012426
12427 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012428 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012429 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020012430 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012431 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012432 return -1;
12433 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012434
12435 /* Push args in the Lua stack, except the first one which is the filename */
12436 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012437 /* Check stack size. */
12438 if (!lua_checkstack(L, 1)) {
12439 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12440 return -1;
12441 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012442 lua_pushstring(L, args[nargs]);
12443 }
12444 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012445
12446 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012447 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012448 switch (error) {
12449 case LUA_OK:
12450 break;
12451 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012452 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012453 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012454 return -1;
12455 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012456 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012457 return -1;
12458 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012459 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012460 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012461 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012462#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012463 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012464 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012465 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012466 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012467#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012468 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012469 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012470 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012471 return -1;
12472 }
12473
12474 return 0;
12475}
12476
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012477static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012478 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012479 char **err)
12480{
12481 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012482 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012483 return -1;
12484 }
12485
Thierry Fournier59f11be2020-11-29 00:37:41 +010012486 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012487 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012488 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012489 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012490}
12491
Thierry Fournier59f11be2020-11-29 00:37:41 +010012492static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012493 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012494 char **err)
12495{
12496 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012497 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012498
12499 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012500 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012501 return -1;
12502 }
12503
12504 if (per_thread_load == NULL) {
12505 /* allocate the first entry large enough to store the final NULL */
12506 per_thread_load = calloc(1, sizeof(*per_thread_load));
12507 if (per_thread_load == NULL) {
12508 memprintf(err, "out of memory error");
12509 return -1;
12510 }
12511 }
12512
12513 /* count used entries */
12514 for (len = 0; per_thread_load[len] != NULL; len++)
12515 ;
12516
12517 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12518 if (per_thread_load == NULL) {
12519 memprintf(err, "out of memory error");
12520 return -1;
12521 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012522 per_thread_load[len + 1] = NULL;
12523
Thierry Fournierae6b5682022-09-19 09:04:16 +020012524 /* count args excepting the first, allocate array and copy args */
12525 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012526 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012527 if (per_thread_load[len] == NULL) {
12528 memprintf(err, "out of memory error");
12529 return -1;
12530 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012531 for (i = 1; *(args[i]) != 0; i++) {
12532 per_thread_load[len][i - 1] = strdup(args[i]);
12533 if (per_thread_load[len][i - 1] == NULL) {
12534 memprintf(err, "out of memory error");
12535 return -1;
12536 }
12537 }
12538 per_thread_load[len][i - 1] = strdup("");
12539 if (per_thread_load[len][i - 1] == NULL) {
12540 memprintf(err, "out of memory error");
12541 return -1;
12542 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012543
12544 /* loading for thread 1 only */
12545 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012546 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012547 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012548}
12549
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012550/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12551 * in the given <ctx>.
12552 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012553static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012554{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012555 lua_getglobal(L, "package"); /* push package variable */
12556 lua_pushstring(L, path); /* push given path */
12557 lua_pushstring(L, ";"); /* push semicolon */
12558 lua_getfield(L, -3, type); /* push old path */
12559 lua_concat(L, 3); /* concatenate to new path */
12560 lua_setfield(L, -2, type); /* store new path */
12561 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012562
12563 return 0;
12564}
12565
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012566static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012567 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012568 char **err)
12569{
12570 char *path;
12571 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012572 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012573 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012574
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012575 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012576 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012577 }
12578
12579 if (!(*args[1])) {
12580 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012581 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012582 }
12583 path = args[1];
12584
12585 if (*args[2]) {
12586 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12587 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012588 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012589 }
12590 type = args[2];
12591 }
12592
Thierry Fournier59f11be2020-11-29 00:37:41 +010012593 p = calloc(1, sizeof(*p));
12594 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012595 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012596 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012597 }
12598 p->path = strdup(path);
12599 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012600 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012601 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012602 }
12603 p->type = strdup(type);
12604 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012605 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012606 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012607 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012608 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012609
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012610 /* Handle the global state and the per-thread state for the first
12611 * thread. The remaining threads will be initialized based on
12612 * prepend_path_list.
12613 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012614 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012615 lua_State *L = hlua_states[i];
12616 const char *error;
12617
12618 if (setjmp(safe_ljmp_env) != 0) {
12619 lua_atpanic(L, hlua_panic_safe);
12620 if (lua_type(L, -1) == LUA_TSTRING)
12621 error = lua_tostring(L, -1);
12622 else
12623 error = "critical error";
12624 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12625 exit(1);
12626 } else {
12627 lua_atpanic(L, hlua_panic_ljmp);
12628 }
12629
12630 hlua_prepend_path(L, type, path);
12631
12632 lua_atpanic(L, hlua_panic_safe);
12633 }
12634
Thierry Fournier59f11be2020-11-29 00:37:41 +010012635 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012636
12637err2:
12638 free(p->type);
12639 free(p->path);
12640err:
12641 free(p);
12642 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012643}
12644
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012645/* configuration keywords declaration */
12646static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012647 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012648 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012649 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012650 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12651 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012652 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012653 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012654 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012655 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012656 { 0, NULL, NULL },
12657}};
12658
Willy Tarreau0108d902018-11-25 19:14:37 +010012659INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12660
William Lallemand52139182022-03-30 15:05:42 +020012661#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012662
William Lallemand30fcca12022-03-30 12:03:12 +020012663/*
12664 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12665 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12666 * difference is that the yield in lua and for the CLI is not handled the same
12667 * way.
12668 */
12669__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12670{
12671 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12672 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12673 struct ckch_inst *ckchi = *lua_ckchi;
12674 struct ckch_store *old_ckchs = lua_ckchs[0];
12675 struct ckch_store *new_ckchs = lua_ckchs[1];
12676 struct hlua *hlua;
12677 char *err = NULL;
12678 int y = 1;
12679
12680 hlua = hlua_gethlua(L);
12681
12682 /* get the first ckchi to copy */
12683 if (ckchi == NULL)
12684 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12685
12686 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12687 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12688 struct ckch_inst *new_inst;
12689
12690 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12691 if (y % 10 == 0) {
12692
12693 *lua_ckchi = ckchi;
12694
12695 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12696 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12697 }
12698
12699 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12700 goto error;
12701
12702 /* link the new ckch_inst to the duplicate */
12703 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12704 y++;
12705 }
12706
12707 /* The generation is finished, we can insert everything */
12708 ckch_store_replace(old_ckchs, new_ckchs);
12709
12710 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12711
12712 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12713
12714 return 0;
12715
12716error:
12717 ckch_store_free(new_ckchs);
12718 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12719 WILL_LJMP(luaL_error(L, "%s", err));
12720 free(err);
12721
12722 return 0;
12723}
12724
12725/*
12726 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12727 * from the table in parameter.
12728 *
12729 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12730 * means it does not need to have a transaction since everything is done in the
12731 * same function.
12732 *
12733 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12734 *
12735 */
12736__LJMP static int hlua_ckch_set(lua_State *L)
12737{
12738 struct hlua *hlua;
12739 struct ckch_inst **lua_ckchi;
12740 struct ckch_store **lua_ckchs;
12741 struct ckch_store *old_ckchs = NULL;
12742 struct ckch_store *new_ckchs = NULL;
12743 int errcode = 0;
12744 char *err = NULL;
12745 struct cert_exts *cert_ext = NULL;
12746 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012747 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012748 int ret;
12749
12750 if (lua_type(L, -1) != LUA_TTABLE)
12751 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12752
12753 hlua = hlua_gethlua(L);
12754
12755 /* FIXME: this should not return an error but should come back later */
12756 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12757 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12758
12759 ret = lua_getfield(L, -1, "filename");
12760 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012761 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012762 errcode |= ERR_ALERT | ERR_FATAL;
12763 goto end;
12764 }
12765 filename = (char *)lua_tostring(L, -1);
12766
12767
12768 /* look for the filename in the tree */
12769 old_ckchs = ckchs_lookup(filename);
12770 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012771 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012772 errcode |= ERR_ALERT | ERR_FATAL;
12773 goto end;
12774 }
12775 /* TODO: handle extra_files_noext */
12776
12777 new_ckchs = ckchs_dup(old_ckchs);
12778 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012779 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012780 errcode |= ERR_ALERT | ERR_FATAL;
12781 goto end;
12782 }
12783
William Lallemand52ddd992022-11-22 11:51:53 +010012784 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012785
12786 /* loop on the field in the table, which have the same name as the
12787 * possible extensions of files */
12788 lua_pushnil(L);
12789 while (lua_next(L, 1)) {
12790 int i;
12791 const char *field = lua_tostring(L, -2);
12792 char *payload = (char *)lua_tostring(L, -1);
12793
12794 if (!field || strcmp(field, "filename") == 0) {
12795 lua_pop(L, 1);
12796 continue;
12797 }
12798
12799 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12800 if (strcmp(field, cert_exts[i].ext) == 0) {
12801 cert_ext = &cert_exts[i];
12802 break;
12803 }
12804 }
12805
12806 /* this is the default type, the field is not supported */
12807 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012808 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012809 errcode |= ERR_ALERT | ERR_FATAL;
12810 goto end;
12811 }
12812
12813 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012814 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012815 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012816 errcode |= ERR_ALERT | ERR_FATAL;
12817 goto end;
12818 }
12819 lua_pop(L, 1);
12820 }
12821
12822 /* store the pointers on the lua stack */
12823 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12824 lua_ckchs[0] = old_ckchs;
12825 lua_ckchs[1] = new_ckchs;
12826 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12827 *lua_ckchi = NULL;
12828
12829 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12830 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12831
12832end:
12833 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12834
12835 if (errcode & ERR_CODE) {
12836 ckch_store_free(new_ckchs);
12837 WILL_LJMP(luaL_error(L, "%s", err));
12838 }
12839 free(err);
12840
12841 return 0;
12842}
12843
William Lallemand52139182022-03-30 15:05:42 +020012844#else
12845
12846__LJMP static int hlua_ckch_set(lua_State *L)
12847{
12848 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12849
12850 return 0;
12851}
12852#endif /* ! USE_OPENSSL */
12853
12854
12855
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012856/* This function can fail with an abort() due to an Lua critical error.
12857 * We are in the initialisation process of HAProxy, this abort() is
12858 * tolerated.
12859 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012860int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012861{
12862 struct hlua_init_function *init;
12863 const char *msg;
12864 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012865 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012866 const char *kind;
12867 const char *trace;
12868 int return_status = 1;
12869#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12870 int nres;
12871#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012872
Willy Tarreaucdb53462020-12-02 12:12:00 +010012873 /* disable memory limit checks if limit is not set */
12874 if (!hlua_global_allocator.limit)
12875 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12876
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012877 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012878 if (setjmp(safe_ljmp_env) != 0) {
12879 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012880 if (lua_type(L, -1) == LUA_TSTRING)
12881 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012882 else
12883 error = "critical error";
12884 fprintf(stderr, "Lua post-init: %s.\n", error);
12885 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012886 } else {
12887 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012888 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012889
Thierry Fournierc7492592020-11-28 23:57:24 +010012890 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012891 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012892 /* function ref should be released right away since it was pushed
12893 * on the stack and will not be used anymore
12894 */
12895 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012896
12897#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Aurelien DARRAGON3ddcd1b2023-09-08 19:29:08 +020012898 ret = lua_resume(L, NULL, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012899#else
Aurelien DARRAGON3ddcd1b2023-09-08 19:29:08 +020012900 ret = lua_resume(L, NULL, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012901#endif
12902 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012903 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012904
12905 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012906 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012907 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012908
12909 case LUA_ERRERR:
12910 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012911 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012912 case LUA_ERRRUN:
12913 if (!kind)
12914 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012915 msg = lua_tostring(L, -1);
12916 lua_settop(L, 0); /* Empty the stack. */
Christopher Fauletd09cc512021-03-24 14:48:45 +010012917 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012918 if (msg)
12919 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12920 else
12921 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12922 return_status = 0;
12923 break;
12924
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012925 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012926 /* Unknown error */
12927 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012928 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012929 case LUA_YIELD:
12930 /* yield is not configured at this step, this state doesn't happen */
12931 if (!kind)
12932 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012933 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012934 case LUA_ERRMEM:
12935 if (!kind)
12936 kind = "out of memory error";
Aurelien DARRAGON3e81aed2023-08-09 10:11:49 +020012937 lua_settop(L, 0); /* Empty the stack. */
Christopher Fauletd09cc512021-03-24 14:48:45 +010012938 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012939 ha_alert("Lua init: %s: %s\n", kind, trace);
12940 return_status = 0;
12941 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012942 }
Thierry Fournier670db242020-11-28 10:49:59 +010012943 if (!return_status)
12944 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012945 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012946
12947 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012948 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012949}
12950
Thierry Fournierb8cef172020-11-28 15:37:17 +010012951int hlua_post_init()
12952{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012953 int ret;
12954 int i;
12955 int errors;
12956 char *err = NULL;
12957 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012958 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012959
Willy Tarreaub1310492021-08-30 09:35:18 +020012960#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012961 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012962 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012963 int saved_used_backed = global.ssl_used_backend;
12964 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012965 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012966 global.ssl_used_backend = saved_used_backed;
12967 }
12968#endif
12969
Thierry Fournierc7492592020-11-28 23:57:24 +010012970 /* Perform post init of common thread */
12971 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012972 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012973 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12974 if (ret == 0)
12975 return 0;
12976
12977 /* init remaining lua states and load files */
12978 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12979
12980 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012981 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012982
12983 /* Init lua state */
12984 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12985
12986 /* Load lua files */
12987 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12988 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12989 if (ret != 0) {
12990 ha_alert("Lua init: %s\n", err);
12991 return 0;
12992 }
12993 }
12994 }
12995
12996 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012997 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012998
12999 /* Execute post init for all states */
13000 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
13001
13002 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013003 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013004
13005 /* run post init */
13006 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
13007 if (ret == 0)
13008 return 0;
13009 }
13010
13011 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013012 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010013013
13014 /* control functions registering. Each function must have:
13015 * - only the function_ref[0] set positive and all other to -1
13016 * - only the function_ref[0] set to -1 and all other positive
13017 * This ensure a same reference is not used both in shared
13018 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013019 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010013020 * complicated to found for the end user.
13021 */
13022 errors = 0;
13023 list_for_each_entry(fcn, &referenced_functions, l) {
13024 ret = 0;
13025 for (i = 1; i < global.nbthread + 1; i++) {
13026 if (fcn->function_ref[i] == -1)
13027 ret--;
13028 else
13029 ret++;
13030 }
13031 if (abs(ret) != global.nbthread) {
13032 ha_alert("Lua function '%s' is not referenced in all thread. "
13033 "Expect function in all thread or in none thread.\n", fcn->name);
13034 errors++;
13035 continue;
13036 }
13037
13038 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013039 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
13040 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010013041 "exclusive.\n", fcn->name);
13042 errors++;
13043 }
13044 }
13045
Christopher Faulet69c581a2021-05-31 08:54:04 +020013046 /* Do the same with registered filters */
13047 list_for_each_entry(reg_flt, &referenced_filters, l) {
13048 ret = 0;
13049 for (i = 1; i < global.nbthread + 1; i++) {
13050 if (reg_flt->flt_ref[i] == -1)
13051 ret--;
13052 else
13053 ret++;
13054 }
13055 if (abs(ret) != global.nbthread) {
13056 ha_alert("Lua filter '%s' is not referenced in all thread. "
13057 "Expect function in all thread or in none thread.\n", reg_flt->name);
13058 errors++;
13059 continue;
13060 }
13061
13062 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
13063 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
13064 "and per-thread Lua context (through lua-load-per-thread). these two context "
13065 "exclusive.\n", fcn->name);
13066 errors++;
13067 }
13068 }
13069
13070
Thierry Fournier59f11be2020-11-29 00:37:41 +010013071 if (errors > 0)
13072 return 0;
13073
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013074 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010013075 * -1 in order to have probably a segfault if someone use it
13076 */
13077 hlua_state_id = -1;
13078
13079 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010013080}
13081
Willy Tarreau32f61e22015-03-18 17:54:59 +010013082/* The memory allocator used by the Lua stack. <ud> is a pointer to the
13083 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
13084 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013085 * allocation. <nsize> is the requested new size. A new allocation is
13086 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010013087 * zero. This one verifies that the limits are respected but is optimized
13088 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013089 *
13090 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
13091 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
13092 * that and will simply allocate zero as if it were the result of malloc(0),
13093 * so mapping this onto realloc() will lead to memory leaks on non-glibc
13094 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010013095 */
13096static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
13097{
13098 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010013099 size_t limit, old, new;
13100
13101 /* a limit of ~0 means unlimited and boot complete, so there's no need
13102 * for accounting anymore.
13103 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013104 if (likely(~zone->limit == 0)) {
13105 if (!nsize)
13106 ha_free(&ptr);
13107 else
13108 ptr = realloc(ptr, nsize);
13109 return ptr;
13110 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010013111
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013112 if (!ptr)
13113 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010013114
Willy Tarreaucdb53462020-12-02 12:12:00 +010013115 /* enforce strict limits across all threads */
13116 limit = zone->limit;
13117 old = _HA_ATOMIC_LOAD(&zone->allocated);
13118 do {
13119 new = old + nsize - osize;
13120 if (unlikely(nsize && limit && new > limit))
13121 return NULL;
13122 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010013123
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013124 if (!nsize)
13125 ha_free(&ptr);
13126 else
13127 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010013128
13129 if (unlikely(!ptr && nsize)) // failed
13130 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
13131
13132 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010013133 return ptr;
13134}
13135
Thierry Fournierecb83c22020-11-28 15:49:44 +010013136/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013137 * We are in the initialisation process of HAProxy, this abort() is
13138 * tolerated.
13139 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010013140lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013141{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013142 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013143 int idx;
13144 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013145 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013146 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013147 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013148 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013149 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013150 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013151
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013152 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013153 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013154
firexinghe64d7afb2023-07-13 11:03:34 +080013155 if (!L) {
13156 fprintf(stderr,
13157 "Lua init: critical error: lua_newstate() returned NULL."
13158 " This may possibly be caused by a memory allocation error.\n");
13159 exit(1);
13160 }
13161
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013162 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013163 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013164 *context = NULL;
13165
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013166 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013167 * the Lua function can fail with an abort. We are in the initialisation
13168 * process of HAProxy, this abort() is tolerated.
13169 */
13170
Thierry Fournier3c539322020-11-28 16:05:05 +010013171 /* Call post initialisation function in safe environment. */
13172 if (setjmp(safe_ljmp_env) != 0) {
13173 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013174 if (lua_type(L, -1) == LUA_TSTRING)
13175 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013176 else
13177 error_msg = "critical error";
13178 fprintf(stderr, "Lua init: %s.\n", error_msg);
13179 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013180 } else {
13181 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013182 }
13183
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013184 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013185 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013186#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
13187#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
13188#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013189 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013190#endif
13191#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013192 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013193#endif
13194#undef HLUA_PREPEND_PATH_TOSTRING
13195#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013196
Thierry Fournier59f11be2020-11-29 00:37:41 +010013197 /* Apply configured prepend path */
13198 list_for_each_entry(pp, &prepend_path_list, l)
13199 hlua_prepend_path(L, pp->type, pp->path);
13200
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013201 /*
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +020013202 * Override some lua functions.
13203 *
13204 */
13205
13206 /* push our "safe" coroutine.create() function */
13207 lua_getglobal(L, "coroutine");
13208 lua_pushcclosure(L, hlua_coroutine_create, 0);
13209 lua_setfield(L, -2, "create");
13210
13211 /*
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013212 *
13213 * Create "core" object.
13214 *
13215 */
13216
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010013217 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013218 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013219
Thierry Fournierecb83c22020-11-28 15:49:44 +010013220 /* set the thread id */
13221 hlua_class_const_int(L, "thread", thread_num);
13222
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013223 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010013224 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013225 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013226
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013227 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013228 hlua_class_function(L, "register_init", hlua_register_init);
13229 hlua_class_function(L, "register_task", hlua_register_task);
13230 hlua_class_function(L, "register_fetches", hlua_register_fetches);
13231 hlua_class_function(L, "register_converters", hlua_register_converters);
13232 hlua_class_function(L, "register_action", hlua_register_action);
13233 hlua_class_function(L, "register_service", hlua_register_service);
13234 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020013235 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013236 hlua_class_function(L, "yield", hlua_yield);
13237 hlua_class_function(L, "set_nice", hlua_set_nice);
13238 hlua_class_function(L, "sleep", hlua_sleep);
13239 hlua_class_function(L, "msleep", hlua_msleep);
13240 hlua_class_function(L, "add_acl", hlua_add_acl);
13241 hlua_class_function(L, "del_acl", hlua_del_acl);
13242 hlua_class_function(L, "set_map", hlua_set_map);
13243 hlua_class_function(L, "del_map", hlua_del_map);
13244 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020013245 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010013246 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013247 hlua_class_function(L, "log", hlua_log);
13248 hlua_class_function(L, "Debug", hlua_log_debug);
13249 hlua_class_function(L, "Info", hlua_log_info);
13250 hlua_class_function(L, "Warning", hlua_log_warning);
13251 hlua_class_function(L, "Alert", hlua_log_alert);
13252 hlua_class_function(L, "done", hlua_done);
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020013253 hlua_class_function(L, "disable_legacy_mailers", hlua_disable_legacy_mailers);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013254 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013255
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013256 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013257
13258 /*
13259 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013260 * Create "act" object.
13261 *
13262 */
13263
13264 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013265 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013266
13267 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013268 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
13269 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
13270 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
13271 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
13272 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
13273 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
13274 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
13275 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013276
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013277 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010013278
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013279 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013280
13281 /*
13282 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020013283 * Create "Filter" object.
13284 *
13285 */
13286
13287 /* This table entry is the object "filter" base. */
13288 lua_newtable(L);
13289
13290 /* push flags and constants */
13291 hlua_class_const_int(L, "CONTINUE", 1);
13292 hlua_class_const_int(L, "WAIT", 0);
13293 hlua_class_const_int(L, "ERROR", -1);
13294
13295 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
13296
Christopher Fauletc404f112020-02-26 15:03:09 +010013297 hlua_class_function(L, "wake_time", hlua_set_wake_time);
13298 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
13299 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
13300
Christopher Faulet69c581a2021-05-31 08:54:04 +020013301 lua_setglobal(L, "filter");
13302
13303 /*
13304 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013305 * Register class Map
13306 *
13307 */
13308
13309 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013310 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013311
13312 /* register pattern types. */
13313 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013314 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013315 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013316 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013317 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013318 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013319
13320 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013321 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013322
13323 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013324 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013325
Ilya Shipitsind4259502020-04-08 01:07:56 +050013326 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013327 lua_pushstring(L, "__index");
13328 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013329
13330 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013331 hlua_class_function(L, "lookup", hlua_map_lookup);
13332 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013333
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013334 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013335
Thierry Fournier45e78d72016-02-19 18:34:46 +010013336 /* Register previous table in the registry with reference and named entry.
13337 * The function hlua_register_metatable() pops the stack, so we
13338 * previously create a copy of the table.
13339 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013340 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
13341 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013342
13343 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013344 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013345
13346 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013347 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013348
13349 /*
13350 *
William Lallemand30fcca12022-03-30 12:03:12 +020013351 * Register "CertCache" class
13352 *
13353 */
13354
13355 /* Create and fill the metatable. */
13356 lua_newtable(L);
13357 /* Register */
13358 hlua_class_function(L, "set", hlua_ckch_set);
13359 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
13360
13361 /*
13362 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013363 * Register class Channel
13364 *
13365 */
13366
13367 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013368 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013369
Ilya Shipitsind4259502020-04-08 01:07:56 +050013370 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013371 lua_pushstring(L, "__index");
13372 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013373
13374 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013375 hlua_class_function(L, "data", hlua_channel_get_data);
13376 hlua_class_function(L, "line", hlua_channel_get_line);
13377 hlua_class_function(L, "set", hlua_channel_set_data);
13378 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013379 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013380 hlua_class_function(L, "prepend", hlua_channel_prepend);
13381 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013382 hlua_class_function(L, "send", hlua_channel_send);
13383 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013384 hlua_class_function(L, "input", hlua_channel_get_in_len);
13385 hlua_class_function(L, "output", hlua_channel_get_out_len);
13386 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013387 hlua_class_function(L, "is_full", hlua_channel_is_full);
13388 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013389
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013390 /* Deprecated API */
13391 hlua_class_function(L, "get", hlua_channel_get);
13392 hlua_class_function(L, "dup", hlua_channel_dup);
13393 hlua_class_function(L, "getline", hlua_channel_getline);
13394 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13395 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13396
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013397 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013398
13399 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013400 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013401
13402 /*
13403 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013404 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013405 *
13406 */
13407
13408 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013409 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013410
Ilya Shipitsind4259502020-04-08 01:07:56 +050013411 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013412 lua_pushstring(L, "__index");
13413 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013414
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013415 /* Browse existing fetches and create the associated
13416 * object method.
13417 */
13418 sf = NULL;
13419 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013420 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13421 * by an underscore.
13422 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013423 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013424 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013425 if (*p == '.' || *p == '-' || *p == '+')
13426 *p = '_';
13427
13428 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013429 lua_pushstring(L, trash.area);
13430 lua_pushlightuserdata(L, sf);
13431 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13432 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013433 }
13434
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013435 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013436
13437 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013438 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013439
13440 /*
13441 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013442 * Register class Converters
13443 *
13444 */
13445
13446 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013447 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013448
13449 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013450 lua_pushstring(L, "__index");
13451 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013452
13453 /* Browse existing converters and create the associated
13454 * object method.
13455 */
13456 sc = NULL;
13457 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013458 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13459 * by an underscore.
13460 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013461 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013462 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013463 if (*p == '.' || *p == '-' || *p == '+')
13464 *p = '_';
13465
13466 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013467 lua_pushstring(L, trash.area);
13468 lua_pushlightuserdata(L, sc);
13469 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13470 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013471 }
13472
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013473 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013474
13475 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013476 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013477
13478 /*
13479 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013480 * Register class HTTP
13481 *
13482 */
13483
13484 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013485 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013486
Ilya Shipitsind4259502020-04-08 01:07:56 +050013487 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013488 lua_pushstring(L, "__index");
13489 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013490
13491 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013492 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13493 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13494 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13495 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13496 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13497 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13498 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13499 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13500 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13501 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013502
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013503 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13504 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13505 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13506 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13507 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13508 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13509 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013510
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013511 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013512
13513 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013514 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013515
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013516 /*
13517 *
13518 * Register class HTTPMessage
13519 *
13520 */
13521
13522 /* Create and fill the metatable. */
13523 lua_newtable(L);
13524
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013525 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013526 lua_pushstring(L, "__index");
13527 lua_newtable(L);
13528
13529 /* Register Lua functions. */
13530 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13531 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13532 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13533 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13534 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13535 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13536 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13537 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13538 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13539 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13540 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13541 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13542 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13543 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13544 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13545 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13546 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13547 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13548
13549 hlua_class_function(L, "body", hlua_http_msg_get_body);
13550 hlua_class_function(L, "set", hlua_http_msg_set_data);
13551 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13552 hlua_class_function(L, "append", hlua_http_msg_append);
13553 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13554 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13555 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13556 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13557
13558 hlua_class_function(L, "send", hlua_http_msg_send);
13559 hlua_class_function(L, "forward", hlua_http_msg_forward);
13560
13561 lua_rawset(L, -3);
13562
13563 /* Register previous table in the registry with reference and named entry. */
13564 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013565
13566 /*
13567 *
13568 * Register class HTTPClient
13569 *
13570 */
13571
13572 /* Create and fill the metatable. */
13573 lua_newtable(L);
13574 lua_pushstring(L, "__index");
13575 lua_newtable(L);
13576 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013577 hlua_class_function(L, "head", hlua_httpclient_head);
13578 hlua_class_function(L, "put", hlua_httpclient_put);
13579 hlua_class_function(L, "post", hlua_httpclient_post);
13580 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013581 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013582 /* Register the garbage collector entry. */
13583 lua_pushstring(L, "__gc");
13584 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13585 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13586
William Lallemand3956c4e2021-09-21 16:25:15 +020013587
13588
13589 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013590 /*
13591 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013592 * Register class AppletTCP
13593 *
13594 */
13595
13596 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013597 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013598
Ilya Shipitsind4259502020-04-08 01:07:56 +050013599 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013600 lua_pushstring(L, "__index");
13601 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013602
13603 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013604 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13605 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13606 hlua_class_function(L, "send", hlua_applet_tcp_send);
13607 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13608 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13609 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13610 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13611 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013612
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013613 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013614
13615 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013616 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013617
13618 /*
13619 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013620 * Register class AppletHTTP
13621 *
13622 */
13623
13624 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013625 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013626
Ilya Shipitsind4259502020-04-08 01:07:56 +050013627 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013628 lua_pushstring(L, "__index");
13629 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013630
13631 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013632 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13633 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13634 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13635 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13636 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13637 hlua_class_function(L, "getline", hlua_applet_http_getline);
13638 hlua_class_function(L, "receive", hlua_applet_http_recv);
13639 hlua_class_function(L, "send", hlua_applet_http_send);
13640 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13641 hlua_class_function(L, "set_status", hlua_applet_http_status);
13642 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013643
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013644 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013645
13646 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013647 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013648
13649 /*
13650 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013651 * Register class TXN
13652 *
13653 */
13654
13655 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013656 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013657
Ilya Shipitsind4259502020-04-08 01:07:56 +050013658 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013659 lua_pushstring(L, "__index");
13660 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013661
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013662 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013663 hlua_class_function(L, "set_priv", hlua_set_priv);
13664 hlua_class_function(L, "get_priv", hlua_get_priv);
13665 hlua_class_function(L, "set_var", hlua_set_var);
13666 hlua_class_function(L, "unset_var", hlua_unset_var);
13667 hlua_class_function(L, "get_var", hlua_get_var);
13668 hlua_class_function(L, "done", hlua_txn_done);
13669 hlua_class_function(L, "reply", hlua_txn_reply_new);
13670 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13671 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13672 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13673 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13674 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13675 hlua_class_function(L, "deflog", hlua_txn_deflog);
13676 hlua_class_function(L, "log", hlua_txn_log);
13677 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13678 hlua_class_function(L, "Info", hlua_txn_log_info);
13679 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13680 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013681
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013682 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013683
13684 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013685 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013686
13687 /*
13688 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013689 * Register class reply
13690 *
13691 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013692 lua_newtable(L);
13693 lua_pushstring(L, "__index");
13694 lua_newtable(L);
13695 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13696 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13697 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13698 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13699 lua_settable(L, -3); /* Sets the __index entry. */
13700 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013701
13702
13703 /*
13704 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013705 * Register class Socket
13706 *
13707 */
13708
13709 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013710 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013711
Ilya Shipitsind4259502020-04-08 01:07:56 +050013712 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013713 lua_pushstring(L, "__index");
13714 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013715
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013716#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013717 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013718#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013719 hlua_class_function(L, "connect", hlua_socket_connect);
13720 hlua_class_function(L, "send", hlua_socket_send);
13721 hlua_class_function(L, "receive", hlua_socket_receive);
13722 hlua_class_function(L, "close", hlua_socket_close);
13723 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13724 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13725 hlua_class_function(L, "setoption", hlua_socket_setoption);
13726 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013727
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013728 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013729
13730 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013731 lua_pushstring(L, "__gc");
13732 lua_pushcclosure(L, hlua_socket_gc, 0);
13733 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013734
13735 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013736 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013737
Thierry Fournieraafc7772020-12-04 11:47:47 +010013738 lua_atpanic(L, hlua_panic_safe);
13739
13740 return L;
13741}
13742
13743void hlua_init(void) {
13744 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013745 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013746#ifdef USE_OPENSSL
13747 struct srv_kw *kw;
13748 int tmp_error;
13749 char *error;
13750 char *args[] = { /* SSL client configuration. */
13751 "ssl",
13752 "verify",
13753 "none",
13754 NULL
13755 };
13756#endif
13757
13758 /* Init post init function list head */
13759 for (i = 0; i < MAX_THREADS + 1; i++)
13760 LIST_INIT(&hlua_init_functions[i]);
13761
13762 /* Init state for common/shared lua parts */
13763 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013764 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013765 hlua_states[0] = hlua_init_state(0);
13766
13767 /* Init state 1 for thread 0. We have at least one thread. */
13768 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013769 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013770 hlua_states[1] = hlua_init_state(1);
13771
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013772 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013773 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013774 if (!socket_proxy) {
13775 fprintf(stderr, "Lua init: %s\n", errmsg);
13776 exit(1);
13777 }
13778 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013779
13780 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013781 socket_tcp = new_server(socket_proxy);
13782 if (!socket_tcp) {
13783 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13784 exit(1);
13785 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013786
13787#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013788 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013789 socket_ssl = new_server(socket_proxy);
13790 if (!socket_ssl) {
13791 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13792 exit(1);
13793 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013794
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013795 socket_ssl->use_ssl = 1;
13796 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013797
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013798 for (i = 0; args[i] != NULL; i++) {
13799 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013800 /*
13801 *
13802 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013803 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013804 * features like client certificates and ssl_verify.
13805 *
13806 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013807 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013808 if (tmp_error != 0) {
13809 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13810 abort(); /* This must be never arrives because the command line
13811 not editable by the user. */
13812 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013813 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013814 }
13815 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013816#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013817
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013818}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013819
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013820static void hlua_deinit()
13821{
Willy Tarreau186f3762020-12-04 11:48:12 +010013822 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013823 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13824
13825 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13826 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013827
13828 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13829 if (hlua_states[thr])
13830 lua_close(hlua_states[thr]);
13831 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013832
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013833 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013834
Willy Tarreau0f143af2021-03-05 10:41:48 +010013835#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013836 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013837#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013838
13839 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013840}
13841
13842REGISTER_POST_DEINIT(hlua_deinit);
13843
Willy Tarreau80713382018-11-26 10:19:54 +010013844static void hlua_register_build_options(void)
13845{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013846 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013847
Willy Tarreaubb57d942016-12-21 19:04:56 +010013848 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13849 hap_register_build_opts(ptr, 1);
13850}
Willy Tarreau80713382018-11-26 10:19:54 +010013851
13852INITCALL0(STG_REGISTER, hlua_register_build_options);