blob: b14ac838f84e3f27aa896a252c8958037899ac17 [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>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200148static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100155static inline void lua_take_global_lock()
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100165/* lua lock helpers: only lock when required
166 *
167 * state_id == 0: we're operating on the main lua stack (shared between
168 * os threads), so we need to acquire the main lock
169 *
170 * If the thread already owns the lock (_hlua_locked != 0), skip the lock
171 * attempt. This could happen if we run under protected lua environment.
172 * Not doing this could result in deadlocks because of nested locking
173 * attempts from the same thread
174 */
175static THREAD_LOCAL int _hlua_locked = 0;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100176static inline void hlua_lock(struct hlua *hlua)
177{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100178 if (hlua->state_id != 0)
179 return;
180 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100181 lua_take_global_lock();
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100182 _hlua_locked += 1;
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100183}
184static inline void hlua_unlock(struct hlua *hlua)
185{
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +0100186 if (hlua->state_id != 0)
187 return;
188 BUG_ON(_hlua_locked <= 0);
189 _hlua_locked--;
190 /* drop the lock once the lock count reaches 0 */
191 if (!_hlua_locked)
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100192 lua_drop_global_lock();
193}
194
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100195#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200196 ({ \
197 int ret; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100198 hlua_lock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200199 if (setjmp(safe_ljmp_env) != 0) { \
200 lua_atpanic(__L, hlua_panic_safe); \
201 ret = 0; \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100202 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200203 } else { \
204 lua_atpanic(__L, hlua_panic_ljmp); \
205 ret = 1; \
206 } \
207 ret; \
208 })
209
210/* If we are the last function catching Lua errors, we
211 * must reset the panic function.
212 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100213#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200214 do { \
215 lua_atpanic(__L, hlua_panic_safe); \
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +0100216 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200217 } while(0)
218
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100219#define SET_SAFE_LJMP(__HLUA) \
220 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
221
222#define RESET_SAFE_LJMP(__HLUA) \
223 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
224
225#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100226 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100227
228#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100229 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100230
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200231/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200232#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100233/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200234#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200235/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100236#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100237#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200238
Thierry Fournierafc63e22020-11-28 17:06:51 +0100239/* The main Lua execution context. The 0 index is the
240 * common state shared by all threads.
241 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100242static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100243
Christopher Fauletc404f112020-02-26 15:03:09 +0100244#define HLUA_FLT_CB_FINAL 0x00000001
245#define HLUA_FLT_CB_RETVAL 0x00000002
246#define HLUA_FLT_CB_ARG_CHN 0x00000004
247#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
248
Christopher Faulet9f55a502020-02-25 15:21:02 +0100249#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
250
Christopher Faulet69c581a2021-05-31 08:54:04 +0200251struct hlua_reg_filter {
252 char *name;
253 int flt_ref[MAX_THREADS + 1];
254 int fun_ref[MAX_THREADS + 1];
255 struct list l;
256};
257
258struct hlua_flt_config {
259 struct hlua_reg_filter *reg;
260 int ref[MAX_THREADS + 1];
261 char **args;
262};
263
264struct hlua_flt_ctx {
265 int ref; /* ref to the filter lua object */
266 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
267 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
268 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
269 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
270};
271
Willy Tarreau5321da92022-05-06 11:57:34 +0200272/* appctx context used by the cosockets */
273struct hlua_csk_ctx {
274 int connected;
275 struct xref xref; /* cross reference with the Lua object owner. */
276 struct list wake_on_read;
277 struct list wake_on_write;
278 struct appctx *appctx;
279 int die;
280};
281
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200282/* appctx context used by TCP services */
283struct hlua_tcp_ctx {
284 struct hlua *hlua;
285 int flags;
286 struct task *task;
287};
288
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200289/* appctx context used by HTTP services */
290struct hlua_http_ctx {
291 struct hlua *hlua;
292 int left_bytes; /* The max amount of bytes that we can read. */
293 int flags;
294 int status;
295 const char *reason;
296 struct task *task;
297};
298
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200299/* used by registered CLI keywords */
300struct hlua_cli_ctx {
301 struct hlua *hlua;
302 struct task *task;
303 struct hlua_function *fcn;
304};
305
Christopher Faulet69c581a2021-05-31 08:54:04 +0200306DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
307
Christopher Faulet9f55a502020-02-25 15:21:02 +0100308static int hlua_filter_from_payload(struct filter *filter);
309
Christopher Faulet69c581a2021-05-31 08:54:04 +0200310/* This is the chained list of struct hlua_flt referenced
311 * for haproxy filters. It is used for a post-initialisation control.
312 */
313static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
314
315
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100316/* This is the memory pool containing struct lua for applets
317 * (including cli).
318 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100319DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100320
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100321/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100322static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100323static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100324#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100325static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100326#endif
327
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100328/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100329struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100330
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100331/* The following variables contains the reference of the different
332 * Lua classes. These references are useful for identify metadata
333 * associated with an object.
334 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100335static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100336static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100337static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100338static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100339static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100340static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100341static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200342static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200343static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200344static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200345static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100346static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100347
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100348/* Lua max execution timeouts. By default, stream-related
349 * lua coroutines (e.g.: actions) have a short timeout.
350 * On the other hand tasks coroutines don't have a timeout because
351 * a task may remain alive during all the haproxy execution.
352 *
353 * Timeouts are expressed in milliseconds, they are meant to be used
354 * with hlua timer's API exclusively.
355 * 0 means no timeout
356 */
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200357static uint32_t hlua_timeout_burst = 1000; /* burst timeout. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100358static uint32_t hlua_timeout_session = 4000; /* session timeout. */
359static uint32_t hlua_timeout_task = 0; /* task timeout. */
360static uint32_t hlua_timeout_applet = 4000; /* applet timeout. */
361
362/* hlua multipurpose timer:
363 * used to compute burst lua time (within a single hlua_ctx_resume())
364 * and cumulative lua time for a given coroutine, and to check
365 * the lua coroutine against the configured timeouts
366 */
367
368/* fetch per-thread cpu_time with ms precision (may wrap) */
369static inline uint32_t _hlua_time_ms()
370{
371 /* We're interested in the current cpu time in ms, which will be returned
372 * as a uint32_t to save some space.
373 * We must take the following into account:
374 *
375 * - now_cpu_time_fast() which returns the time in nanoseconds as a uint64_t
376 * will wrap every 585 years.
377 * - uint32_t may only contain 4294967295ms (~=49.7 days), so _hlua_time_ms()
378 * itself will also wrap every 49.7 days.
379 *
380 * While we can safely ignore the now_cpu_time_fast() wrap, we must
381 * take care of the uint32_t wrap by making sure to exclusively
382 * manipulate the time using uint32_t everywhere _hlua_time_ms()
383 * is involved.
384 */
385 return (uint32_t)(now_cpu_time_fast() / 1000000ULL);
386}
387
388/* computes time spent in a single lua execution (in ms) */
389static inline uint32_t _hlua_time_burst(const struct hlua_timer *timer)
390{
391 uint32_t burst_ms;
392
393 /* wrapping is expected and properly
394 * handled thanks to _hlua_time_ms() and burst_ms
395 * being of the same type
396 */
397 burst_ms = _hlua_time_ms() - timer->start;
398 return burst_ms;
399}
400
401static inline void hlua_timer_init(struct hlua_timer *timer, unsigned int max)
402{
403 timer->cumulative = 0;
404 timer->burst = 0;
405 timer->max = max;
406}
407
408/* reset the timer ctx between 2 yields */
409static inline void hlua_timer_reset(struct hlua_timer *timer)
410{
411 timer->cumulative += timer->burst;
412 timer->burst = 0;
413}
414
415/* start the timer right before a new execution */
416static inline void hlua_timer_start(struct hlua_timer *timer)
417{
418 timer->start = _hlua_time_ms();
419}
420
421/* update hlua timer when finishing an execution */
422static inline void hlua_timer_stop(struct hlua_timer *timer)
423{
424 timer->burst += _hlua_time_burst(timer);
425}
426
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200427/* check the timers for current hlua context:
428 * - first check for burst timeout (max execution time for the current
429 hlua resume, ie: time between effective yields)
430 * - then check for yield cumulative timeout
431 *
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100432 * Returns 1 if the check succeeded and 0 if it failed
433 * (ie: timeout exceeded)
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100434 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100435static inline int hlua_timer_check(const struct hlua_timer *timer)
436{
437 uint32_t pburst = _hlua_time_burst(timer); /* pending burst time in ms */
438
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +0200439 if (hlua_timeout_burst && (timer->burst + pburst) > hlua_timeout_burst)
440 return 0; /* burst timeout exceeded */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +0100441 if (timer->max && (timer->cumulative + timer->burst + pburst) > timer->max)
442 return 0; /* cumulative timeout exceeded */
443 return 1; /* ok */
444}
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100445
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100446/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
447 * it is used for preventing infinite loops.
448 *
449 * I test the scheer with an infinite loop containing one incrementation
450 * and one test. I run this loop between 10 seconds, I raise a ceil of
451 * 710M loops from one interrupt each 9000 instructions, so I fix the value
452 * to one interrupt each 10 000 instructions.
453 *
454 * configured | Number of
455 * instructions | loops executed
456 * between two | in milions
457 * forced yields |
458 * ---------------+---------------
459 * 10 | 160
460 * 500 | 670
461 * 1000 | 680
462 * 5000 | 700
463 * 7000 | 700
464 * 8000 | 700
465 * 9000 | 710 <- ceil
466 * 10000 | 710
467 * 100000 | 710
468 * 1000000 | 710
469 *
470 */
471static unsigned int hlua_nb_instruction = 10000;
472
Willy Tarreaucdb53462020-12-02 12:12:00 +0100473/* Descriptor for the memory allocation state. The limit is pre-initialised to
474 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
475 * is replaced with ~0 during post_init after everything was loaded. This way
476 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
477 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100478 */
479struct hlua_mem_allocator {
480 size_t allocated;
481 size_t limit;
482};
483
Willy Tarreaucdb53462020-12-02 12:12:00 +0100484static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100485
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +0100486/* hlua event subscription */
487struct hlua_event_sub {
488 int fcn_ref;
489 int state_id;
490 struct hlua *hlua;
491 struct task *task;
492 event_hdl_async_equeue equeue;
493 struct event_hdl_sub *sub;
494 uint8_t paused;
495};
496
497/* This is the memory pool containing struct hlua_event_sub
498 * for event subscriptions from lua
499 */
500DECLARE_STATIC_POOL(pool_head_hlua_event_sub, "hlua_esub", sizeof(struct hlua_event_sub));
501
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100502/* These functions converts types between HAProxy internal args or
503 * sample and LUA types. Another function permits to check if the
504 * LUA stack contains arguments according with an required ARG_T
505 * format.
506 */
507static int hlua_arg2lua(lua_State *L, const struct arg *arg);
508static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100509__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100510 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100511static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100512static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100513static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
514
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100515__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200516
Thierry Fournier59f11be2020-11-29 00:37:41 +0100517struct prepend_path {
518 struct list l;
519 char *type;
520 char *path;
521};
522
523static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
524
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200525#define SEND_ERR(__be, __fmt, __args...) \
526 do { \
527 send_log(__be, LOG_ERR, __fmt, ## __args); \
528 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100529 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200530 } while (0)
531
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100532static inline struct hlua_function *new_hlua_function()
533{
534 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100535 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100536
537 fcn = calloc(1, sizeof(*fcn));
538 if (!fcn)
539 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200540 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100541 for (i = 0; i < MAX_THREADS + 1; i++)
542 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100543 return fcn;
544}
545
Christopher Fauletdda44442021-04-12 14:05:43 +0200546static inline void release_hlua_function(struct hlua_function *fcn)
547{
548 if (!fcn)
549 return;
550 if (fcn->name)
551 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200552 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200553 ha_free(&fcn);
554}
555
Thierry Fournierc7492592020-11-28 23:57:24 +0100556/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
557static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
558{
559 if (fcn->function_ref[0] == -1)
560 return tid + 1;
561 return 0;
562}
563
Christopher Faulet69c581a2021-05-31 08:54:04 +0200564/* Create a new registered filter. Only its name is filled */
565static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
566{
567 struct hlua_reg_filter *reg_flt;
568 int i;
569
570 reg_flt = calloc(1, sizeof(*reg_flt));
571 if (!reg_flt)
572 return NULL;
573 reg_flt->name = strdup(name);
574 if (!reg_flt->name) {
575 free(reg_flt);
576 return NULL;
577 }
578 LIST_APPEND(&referenced_filters, &reg_flt->l);
579 for (i = 0; i < MAX_THREADS + 1; i++) {
580 reg_flt->flt_ref[i] = -1;
581 reg_flt->fun_ref[i] = -1;
582 }
583 return reg_flt;
584}
585
586/* Release a registered filter */
587static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
588{
589 if (!reg_flt)
590 return;
591 if (reg_flt->name)
592 ha_free(&reg_flt->name);
593 LIST_DELETE(&reg_flt->l);
594 ha_free(&reg_flt);
595}
596
597/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
598static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
599{
600 if (reg_flt->fun_ref[0] == -1)
601 return tid + 1;
602 return 0;
603}
604
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100605/* Used to check an Lua function type in the stack. It creates and
606 * returns a reference of the function. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100607 * error if the argument is not a "function".
608 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100609 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100610__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100611{
612 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100613 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100614 WILL_LJMP(luaL_argerror(L, argno, msg));
615 }
616 lua_pushvalue(L, argno);
617 return luaL_ref(L, LUA_REGISTRYINDEX);
618}
619
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100620/* Used to check an Lua table type in the stack. It creates and
621 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100622 * error if the argument is not a "table".
623 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100624 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100625__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100626{
627 if (!lua_istable(L, argno)) {
628 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
629 WILL_LJMP(luaL_argerror(L, argno, msg));
630 }
631 lua_pushvalue(L, argno);
632 return luaL_ref(L, LUA_REGISTRYINDEX);
633}
634
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100635/* Get a reference to the object that is at the top of the stack
636 * The referenced object will be popped from the stack
637 *
638 * The function returns the reference to the object which must
639 * be cleared using hlua_unref() when no longer used
640 */
641__LJMP int hlua_ref(lua_State *L)
642{
643 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
644}
645
646/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
647 * on <L> stack
648 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
649 *
650 * When the reference is no longer used, it should be released by calling
651 * hlua_unref()
652 *
653 * <L> can be from any co-routine as long as it belongs to the same lua
654 * parent state that the one used to get the reference.
655 */
656void hlua_pushref(lua_State *L, int ref)
657{
658 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
659}
660
661/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
662 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
663 *
664 * This will allow the reference to be reused and the referred object
665 * to be garbage collected.
666 *
667 * <L> can be from any co-routine as long as it belongs to the same lua
668 * parent state that the one used to get the reference.
669 */
670void hlua_unref(lua_State *L, int ref)
671{
672 luaL_unref(L, LUA_REGISTRYINDEX, ref);
673}
674
Christopher Fauletd09cc512021-03-24 14:48:45 +0100675__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200676{
677 lua_Debug ar;
678 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200679 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200680
681 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200682 /* Fill fields:
683 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
684 * 'l': fills in the field currentline;
685 * 'n': fills in the field name and namewhat;
686 * 't': fills in the field istailcall;
687 */
688 lua_getinfo(L, "Slnt", &ar);
689
Willy Tarreau5c143402022-06-19 17:35:53 +0200690 /* skip these empty entries, usually they come from deep C functions */
691 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
692 continue;
693
694 /* Add separator */
695 if (b_data(msg))
696 chunk_appendf(msg, "%s", sep);
697
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200698 /* Append code localisation */
699 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100700 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200701 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100702 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200703
704 /*
705 * Get function name
706 *
707 * if namewhat is no empty, name is defined.
708 * what contains "Lua" for Lua function, "C" for C function,
709 * or "main" for main code.
710 */
711 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100712 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200713
714 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100715 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200716
717 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100718 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200719
720 else /* nothing left... */
721 chunk_appendf(msg, "?");
722
723
724 /* Display tailed call */
725 if (ar.istailcall)
726 chunk_appendf(msg, " ...");
727 }
728
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200729 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200730}
731
732
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100733/* This function check the number of arguments available in the
734 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500735 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100736 */
737__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
738{
739 if (lua_gettop(L) == nb)
740 return;
741 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
742}
743
Mark Lakes22154b42018-01-29 14:38:40 -0800744/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100745 * and the line number where the error is encountered.
746 */
747static int hlua_pusherror(lua_State *L, const char *fmt, ...)
748{
749 va_list argp;
750 va_start(argp, fmt);
751 luaL_where(L, 1);
752 lua_pushvfstring(L, fmt, argp);
753 va_end(argp);
754 lua_concat(L, 2);
755 return 1;
756}
757
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100758/* This functions is used with sample fetch and converters. It
759 * converts the HAProxy configuration argument in a lua stack
760 * values.
761 *
762 * It takes an array of "arg", and each entry of the array is
763 * converted and pushed in the LUA stack.
764 */
765static int hlua_arg2lua(lua_State *L, const struct arg *arg)
766{
767 switch (arg->type) {
768 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100769 case ARGT_TIME:
770 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100771 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100772 break;
773
774 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200775 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case ARGT_IPV4:
779 case ARGT_IPV6:
780 case ARGT_MSK4:
781 case ARGT_MSK6:
782 case ARGT_FE:
783 case ARGT_BE:
784 case ARGT_TAB:
785 case ARGT_SRV:
786 case ARGT_USR:
787 case ARGT_MAP:
788 default:
789 lua_pushnil(L);
790 break;
791 }
792 return 1;
793}
794
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500795/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100796 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500797 * with sample fetch wrappers. The input arguments are given to the
798 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100799 */
800static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
801{
802 switch (lua_type(L, ud)) {
803
804 case LUA_TNUMBER:
805 case LUA_TBOOLEAN:
806 arg->type = ARGT_SINT;
807 arg->data.sint = lua_tointeger(L, ud);
808 break;
809
810 case LUA_TSTRING:
811 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200812 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200813 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200814 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200815 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100816 break;
817
818 case LUA_TUSERDATA:
819 case LUA_TNIL:
820 case LUA_TTABLE:
821 case LUA_TFUNCTION:
822 case LUA_TTHREAD:
823 case LUA_TLIGHTUSERDATA:
824 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200825 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826 break;
827 }
828 return 1;
829}
830
831/* the following functions are used to convert a struct sample
832 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500833 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100834 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100835static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100836{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200837 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100838 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100839 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200840 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100841 break;
842
843 case SMP_T_BIN:
844 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200845 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100846 break;
847
848 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200849 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100850 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
851 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
852 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
853 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
854 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
855 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
856 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
857 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
858 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200859 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100860 break;
861 default:
862 lua_pushnil(L);
863 break;
864 }
865 break;
866
867 case SMP_T_IPV4:
868 case SMP_T_IPV6:
869 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200870 if (sample_casts[smp->data.type][SMP_T_STR] &&
871 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200872 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100873 else
874 lua_pushnil(L);
875 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100876 default:
877 lua_pushnil(L);
878 break;
879 }
880 return 1;
881}
882
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100883/* the following functions are used to convert a struct sample
884 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500885 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100886 */
887static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
888{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200889 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100890
891 case SMP_T_BIN:
892 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200893 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100894 break;
895
896 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200897 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100898 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
899 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
900 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
901 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
902 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
903 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
904 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
905 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
906 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200907 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100908 break;
909 default:
910 lua_pushstring(L, "");
911 break;
912 }
913 break;
914
915 case SMP_T_SINT:
916 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100917 case SMP_T_IPV4:
918 case SMP_T_IPV6:
919 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200920 if (sample_casts[smp->data.type][SMP_T_STR] &&
921 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200922 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100923 else
924 lua_pushstring(L, "");
925 break;
926 default:
927 lua_pushstring(L, "");
928 break;
929 }
930 return 1;
931}
932
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100933/* the following functions are used to convert an Lua type in a
934 * struct sample. This is useful to provide data from a converter
935 * to the LUA code.
936 */
937static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
938{
939 switch (lua_type(L, ud)) {
940
941 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200942 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200943 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100944 break;
945
946
947 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200948 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200949 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100950 break;
951
952 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200953 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100954 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200955 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200956 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200957 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200958 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100959 break;
960
961 case LUA_TUSERDATA:
962 case LUA_TNIL:
963 case LUA_TTABLE:
964 case LUA_TFUNCTION:
965 case LUA_TTHREAD:
966 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200967 case LUA_TNONE:
968 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200969 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200970 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100971 break;
972 }
973 return 1;
974}
975
Ilya Shipitsind4259502020-04-08 01:07:56 +0500976/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800977 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100979 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500980 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200981 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100982 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100983__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100984 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100985{
986 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200987 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100988 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200989 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200990 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200991 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200992 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100993
994 idx = 0;
995 min_arg = ARGM(mask);
996 mask >>= ARGM_BITS;
997
998 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001000
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001001 /* Check for mandatory arguments. */
1002 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001003 if (idx < min_arg) {
1004
1005 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001006 if (idx > 0) {
1007 msg = "Mandatory argument expected";
1008 goto error;
1009 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001010
1011 /* If first argument have a certain type, some default values
1012 * may be used. See the function smp_resolve_args().
1013 */
1014 switch (mask & ARGT_MASK) {
1015
1016 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001017 if (!(p->cap & PR_CAP_FE)) {
1018 msg = "Mandatory argument expected";
1019 goto error;
1020 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001021 argp[idx].data.prx = p;
1022 argp[idx].type = ARGT_FE;
1023 argp[idx+1].type = ARGT_STOP;
1024 break;
1025
1026 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001027 if (!(p->cap & PR_CAP_BE)) {
1028 msg = "Mandatory argument expected";
1029 goto error;
1030 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001031 argp[idx].data.prx = p;
1032 argp[idx].type = ARGT_BE;
1033 argp[idx+1].type = ARGT_STOP;
1034 break;
1035
1036 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001037 if (!p->table) {
1038 msg = "Mandatory argument expected";
1039 goto error;
1040 }
1041 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001042 argp[idx].type = ARGT_TAB;
1043 argp[idx+1].type = ARGT_STOP;
1044 break;
1045
1046 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001047 msg = "Mandatory argument expected";
1048 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001049 break;
1050 }
1051 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001052 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001053 }
1054
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001055 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001056 if ((mask & ARGT_MASK) == ARGT_STOP &&
1057 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001058 msg = "Last argument expected";
1059 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001060 }
1061
1062 if ((mask & ARGT_MASK) == ARGT_STOP &&
1063 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001064 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001065 }
1066
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001067 /* Convert some argument types. All string in argp[] are for not
1068 * duplicated yet.
1069 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001070 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001071 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001072 if (argp[idx].type != ARGT_SINT) {
1073 msg = "integer expected";
1074 goto error;
1075 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001076 argp[idx].type = ARGT_SINT;
1077 break;
1078
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001079 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001080 if (argp[idx].type != ARGT_SINT) {
1081 msg = "integer expected";
1082 goto error;
1083 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001084 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001085 break;
1086
1087 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088 if (argp[idx].type != ARGT_SINT) {
1089 msg = "integer expected";
1090 goto error;
1091 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001092 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001093 break;
1094
1095 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001096 if (argp[idx].type != ARGT_STR) {
1097 msg = "string expected";
1098 goto error;
1099 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001100 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001101 if (!argp[idx].data.prx) {
1102 msg = "frontend doesn't exist";
1103 goto error;
1104 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001105 argp[idx].type = ARGT_FE;
1106 break;
1107
1108 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001109 if (argp[idx].type != ARGT_STR) {
1110 msg = "string expected";
1111 goto error;
1112 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001113 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001114 if (!argp[idx].data.prx) {
1115 msg = "backend doesn't exist";
1116 goto error;
1117 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001118 argp[idx].type = ARGT_BE;
1119 break;
1120
1121 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001122 if (argp[idx].type != ARGT_STR) {
1123 msg = "string expected";
1124 goto error;
1125 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001126 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001127 if (!argp[idx].data.t) {
1128 msg = "table doesn't exist";
1129 goto error;
1130 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001131 argp[idx].type = ARGT_TAB;
1132 break;
1133
1134 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001135 if (argp[idx].type != ARGT_STR) {
1136 msg = "string expected";
1137 goto error;
1138 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001139 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001140 if (sname) {
1141 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001142 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001143 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001144 if (!px) {
1145 msg = "backend doesn't exist";
1146 goto error;
1147 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001148 }
1149 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001150 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001151 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001152 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001153 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001154 if (!argp[idx].data.srv) {
1155 msg = "server doesn't exist";
1156 goto error;
1157 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001158 argp[idx].type = ARGT_SRV;
1159 break;
1160
1161 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001162 if (argp[idx].type != ARGT_STR) {
1163 msg = "string expected";
1164 goto error;
1165 }
1166 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1167 msg = "invalid IPv4 address";
1168 goto error;
1169 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001170 argp[idx].type = ARGT_IPV4;
1171 break;
1172
1173 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001174 if (argp[idx].type == ARGT_SINT)
1175 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1176 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001177 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1178 msg = "invalid IPv4 mask";
1179 goto error;
1180 }
1181 }
1182 else {
1183 msg = "integer or string expected";
1184 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001185 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001186 argp[idx].type = ARGT_MSK4;
1187 break;
1188
1189 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001190 if (argp[idx].type != ARGT_STR) {
1191 msg = "string expected";
1192 goto error;
1193 }
1194 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1195 msg = "invalid IPv6 address";
1196 goto error;
1197 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001198 argp[idx].type = ARGT_IPV6;
1199 break;
1200
1201 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001202 if (argp[idx].type == ARGT_SINT)
1203 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1204 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001205 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1206 msg = "invalid IPv6 mask";
1207 goto error;
1208 }
1209 }
1210 else {
1211 msg = "integer or string expected";
1212 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001213 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001214 argp[idx].type = ARGT_MSK6;
1215 break;
1216
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001217 case ARGT_REG:
1218 if (argp[idx].type != ARGT_STR) {
1219 msg = "string expected";
1220 goto error;
1221 }
1222 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1223 if (!reg) {
1224 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1225 argp[idx].data.str.area, err);
1226 free(err);
1227 goto error;
1228 }
1229 argp[idx].type = ARGT_REG;
1230 argp[idx].data.reg = reg;
1231 break;
1232
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001233 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001234 if (argp[idx].type != ARGT_STR) {
1235 msg = "string expected";
1236 goto error;
1237 }
1238 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001239 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001240 ul = p->uri_auth->userlist;
1241 else
1242 ul = auth_find_userlist(argp[idx].data.str.area);
1243
1244 if (!ul) {
1245 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1246 goto error;
1247 }
1248 argp[idx].type = ARGT_USR;
1249 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001250 break;
1251
1252 case ARGT_STR:
1253 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1254 msg = "unable to duplicate string arg";
1255 goto error;
1256 }
1257 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001258 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001259
Christopher Fauletd25d9262020-08-06 11:04:46 +02001260 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001261 msg = "type not yet supported";
1262 goto error;
1263 break;
1264
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001265 }
1266
1267 /* Check for type of argument. */
1268 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001269 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1270 arg_type_names[(mask & ARGT_MASK)],
1271 arg_type_names[argp[idx].type & ARGT_MASK]);
1272 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001273 }
1274
1275 /* Next argument. */
1276 mask >>= ARGT_BITS;
1277 idx++;
1278 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001279 return 0;
1280
1281 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001282 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001283 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001284 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1285 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001286}
1287
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001288/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001289 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001290 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001291 *
1292 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001293 * - hlua_sethlua : create the association between hlua context and lua_state.
1294 */
1295static inline struct hlua *hlua_gethlua(lua_State *L)
1296{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001297 struct hlua **hlua = lua_getextraspace(L);
1298 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001299}
1300static inline void hlua_sethlua(struct hlua *hlua)
1301{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001302 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1303 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001304}
1305
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001306/* Will return a non-NULL string indicating the Lua call trace if the caller
1307 * currently is executing from within a Lua function. One line per entry will
1308 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1309 * Lua function is not detected, NULL is returned.
1310 */
1311const char *hlua_show_current_location(const char *pfx)
1312{
1313 lua_State *L;
1314 lua_Debug ar;
1315
1316 /* global or per-thread stack initializing ? */
1317 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1318 return hlua_traceback(L, pfx);
1319
1320 /* per-thread stack running ? */
1321 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1322 return hlua_traceback(L, pfx);
1323
1324 /* global stack running ? */
1325 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1326 return hlua_traceback(L, pfx);
1327
1328 return NULL;
1329}
1330
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001331/* This function is used to send logs. It try to send on screen (stderr)
1332 * and on the default syslog server.
1333 */
1334static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1335{
1336 struct tm tm;
1337 char *p;
1338
1339 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001340 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001341 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001342 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001343 /* Break the message if exceed the buffer size. */
1344 *(p-4) = ' ';
1345 *(p-3) = '.';
1346 *(p-2) = '.';
1347 *(p-1) = '.';
1348 break;
1349 }
Willy Tarreau90807112020-02-25 08:16:33 +01001350 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001351 *p = *msg;
1352 else
1353 *p = '.';
1354 }
1355 *p = '\0';
1356
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001357 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001358 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001359 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1360 return;
1361
Willy Tarreaua678b432015-08-28 10:14:59 +02001362 get_localtime(date.tv_sec, &tm);
1363 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001364 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001365 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001366 fflush(stderr);
1367 }
1368}
1369
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001370/* This function just ensure that the yield will be always
1371 * returned with a timeout and permit to set some flags
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02001372 * <timeout> is a tick value
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001373 */
1374__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001375 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001376{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001377 struct hlua *hlua;
1378
1379 /* Get hlua struct, or NULL if we execute from main lua state */
1380 hlua = hlua_gethlua(L);
1381 if (!hlua) {
1382 return;
1383 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001384
1385 /* Set the wake timeout. If timeout is required, we set
1386 * the expiration time.
1387 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001388 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001389
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001390 hlua->flags |= flags;
1391
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001392 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001393 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001394}
1395
Willy Tarreau87b09662015-04-03 00:22:06 +02001396/* This function initialises the Lua environment stored in the stream.
1397 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001398 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001399 *
1400 * This function is particular. it initialises a new Lua thread. If the
1401 * initialisation fails (example: out of memory error), the lua function
1402 * throws an error (longjmp).
1403 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001404 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001405 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001406 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001407 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001408 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001409int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001410{
1411 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001412 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001413 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001414 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001415 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001416 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001417 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001418 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001419 if (!SET_SAFE_LJMP_PARENT(lua)) {
1420 lua->Tref = LUA_REFNIL;
1421 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001422 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001423 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001424 if (!lua->T) {
1425 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001426 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001427 return 0;
1428 }
1429 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001430 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001431 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001432 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001433 return 1;
1434}
1435
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001436/* kill all associated httpclient to this hlua task
1437 * We must take extra precautions as we're manipulating lua-exposed
1438 * objects without the main lua lock.
1439 */
William Lallemandbb581422022-10-20 10:57:28 +02001440static void hlua_httpclient_destroy_all(struct hlua *hlua)
1441{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001442 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001443
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001444 /* use thread-safe accessors for hc_list since GC cycle initiated by
1445 * another thread sharing the same main lua stack (lua coroutine)
1446 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1447 * in parallel: Lua GC applies on the main stack, it is not limited to
1448 * a single coroutine stack, see Github issue #2037 for reference.
1449 * Remember, coroutines created using lua_newthread() are not meant to
1450 * be thread safe in Lua. (From lua co-author:
1451 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1452 *
1453 * This security measure is superfluous when 'lua-load-per-thread' is used
1454 * since in this case coroutines exclusively run on the same thread
1455 * (main stack is not shared between OS threads).
1456 */
1457 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1458 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001459 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001460 }
1461}
1462
1463
Willy Tarreau87b09662015-04-03 00:22:06 +02001464/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001465 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001466 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001467 */
1468void hlua_ctx_destroy(struct hlua *lua)
1469{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001470 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001471 return;
1472
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001473 if (!lua->T)
1474 goto end;
1475
William Lallemandbb581422022-10-20 10:57:28 +02001476 /* clean all running httpclient */
1477 hlua_httpclient_destroy_all(lua);
1478
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001479 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001480 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001481
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001482 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001483 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001484 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001485 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001486
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001487 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001488 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001489 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001490 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001491 /* Forces a garbage collecting process. If the Lua program is finished
1492 * without error, we run the GC on the thread pointer. Its freed all
1493 * the unused memory.
1494 * If the thread is finnish with an error or is currently yielded,
1495 * it seems that the GC applied on the thread doesn't clean anything,
1496 * so e run the GC on the main thread.
1497 * NOTE: maybe this action locks all the Lua threads untiml the en of
1498 * the garbage collection.
1499 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001500 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001501 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001502 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001503 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001504 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001505 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001506
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001507 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001508
1509end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001510 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001511}
1512
1513/* This function is used to restore the Lua context when a coroutine
1514 * fails. This function copy the common memory between old coroutine
1515 * and the new coroutine. The old coroutine is destroyed, and its
1516 * replaced by the new coroutine.
1517 * If the flag "keep_msg" is set, the last entry of the old is assumed
1518 * as string error message and it is copied in the new stack.
1519 */
1520static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1521{
1522 lua_State *T;
1523 int new_ref;
1524
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001525 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001526 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001527 if (!T)
1528 return 0;
1529
1530 /* Copy last error message. */
1531 if (keep_msg)
1532 lua_xmove(lua->T, T, 1);
1533
1534 /* Copy data between the coroutines. */
1535 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1536 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001537 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001538
1539 /* Destroy old data. */
1540 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1541
1542 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001543 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001544
1545 /* Fill the struct with the new coroutine values. */
1546 lua->Mref = new_ref;
1547 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001548 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001549
1550 /* Set context. */
1551 hlua_sethlua(lua);
1552
1553 return 1;
1554}
1555
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001556void hlua_hook(lua_State *L, lua_Debug *ar)
1557{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001558 struct hlua *hlua;
1559
1560 /* Get hlua struct, or NULL if we execute from main lua state */
1561 hlua = hlua_gethlua(L);
1562 if (!hlua)
1563 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001564
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001565 if (hlua->T != L) {
1566 /* We don't want to enforce a yield on a sub coroutine, since
1567 * we have no guarantees that the yield will be handled properly.
1568 * Indeed, only the hlua->T coroutine is being handled through
1569 * hlua_ctx_resume() function.
1570 *
1571 * Instead, we simply check for timeouts and wait for the sub
1572 * coroutine to finish..
1573 */
1574 goto check_timeout;
1575 }
1576
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001577 /* Lua cannot yield when its returning from a function,
1578 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001579 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001580 */
1581 if (lua_gethookmask(L) & LUA_MASKRET) {
1582 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1583 return;
1584 }
1585
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001586 /* If we interrupt the Lua processing in yieldable state, we yield.
1587 * If the state is not yieldable, trying yield causes an error.
1588 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001589 if (lua_isyieldable(L)) {
1590 /* note: for converters/fetches.. where yielding is not allowed
1591 * hlua_ctx_resume() will simply perform a goto resume_execution
1592 * instead of rescheduling hlua->task.
1593 * also: hlua_ctx_resume() will take care of checking execution
1594 * timeout and re-applying the hook as needed.
1595 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001596 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001597 /* lua docs says that the hook should return immediately after lua_yieldk
1598 *
1599 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1600 *
1601 * Moreover, it seems that we don't want to continue after the yield
1602 * because the end of the function is about handling unyieldable function,
1603 * which is not the case here.
1604 *
1605 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1606 * in the function.
1607 */
1608 return;
1609 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001610
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001611 check_timeout:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001612 /* If we cannot yield, check the timeout. */
1613 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001614 lua_pushfstring(L, "execution timeout");
1615 WILL_LJMP(lua_error(L));
1616 }
1617
1618 /* Try to interrupt the process at the end of the current
1619 * unyieldable function.
1620 */
1621 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001622}
1623
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001624/* This function start or resumes the Lua stack execution. If the flag
1625 * "yield_allowed" if no set and the LUA stack execution returns a yield
1626 * The function return an error.
1627 *
1628 * The function can returns 4 values:
1629 * - HLUA_E_OK : The execution is terminated without any errors.
1630 * - HLUA_E_AGAIN : The execution must continue at the next associated
1631 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001632 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001633 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001634 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001635 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001636 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001637 * LUA code.
1638 */
1639static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1640{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001641#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1642 int nres;
1643#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001644 int ret;
1645 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001646 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001647
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001648 /* Lock the whole Lua execution. This lock must be before the
1649 * label "resume_execution".
1650 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001651 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001652
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001653 /* reset the timer as we might be re-entering the function to
1654 * resume the coroutine after a successful yield
1655 * (cumulative time will be updated)
1656 */
1657 hlua_timer_reset(&lua->timer);
1658
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001659resume_execution:
1660
1661 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1662 * instructions. it is used for preventing infinite loops.
1663 */
1664 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1665
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001666 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001667 HLUA_SET_RUN(lua);
1668 HLUA_CLR_CTRLYIELD(lua);
1669 HLUA_CLR_WAKERESWR(lua);
1670 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001671 HLUA_CLR_NOYIELD(lua);
1672 if (!yield_allowed)
1673 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001674
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001675 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001676 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001677
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001678 /* start the timer as we're about to start lua processing */
1679 hlua_timer_start(&lua->timer);
1680
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001681 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001682#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001683 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001684#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001685 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001686#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001687
1688 /* out of lua processing, stop the timer */
1689 hlua_timer_stop(&lua->timer);
1690
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001691 switch (ret) {
1692
1693 case LUA_OK:
1694 ret = HLUA_E_OK;
1695 break;
1696
1697 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001698 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001699 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001700 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001701 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001702 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001703 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001704 break;
1705 }
1706 /* Process the forced yield. if the general yield is not allowed or
1707 * if no task were associated this the current Lua execution
1708 * coroutine, we resume the execution. Else we want to return in the
1709 * scheduler and we want to be waked up again, to continue the
1710 * current Lua execution. So we schedule our own task.
1711 */
1712 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001713 if (!yield_allowed || !lua->task)
1714 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001715 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001716 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001717 if (!yield_allowed) {
1718 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001719 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001720 break;
1721 }
1722 ret = HLUA_E_AGAIN;
1723 break;
1724
1725 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001726
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001727 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001728 * because the errors ares the only one mean to return immediately
1729 * from and lua execution.
1730 */
1731 if (lua->flags & HLUA_EXIT) {
1732 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001733 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001734 break;
1735 }
1736
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001737 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001738 if (!lua_checkstack(lua->T, 1)) {
1739 ret = HLUA_E_ERR;
1740 break;
1741 }
1742 msg = lua_tostring(lua->T, -1);
1743 lua_settop(lua->T, 0); /* Empty the stack. */
1744 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001745 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001746 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001747 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001748 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001749 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001750 ret = HLUA_E_ERRMSG;
1751 break;
1752
1753 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001754 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001755 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001756 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001757 break;
1758
1759 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001760 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001761 if (!lua_checkstack(lua->T, 1)) {
1762 ret = HLUA_E_ERR;
1763 break;
1764 }
1765 msg = lua_tostring(lua->T, -1);
1766 lua_settop(lua->T, 0); /* Empty the stack. */
1767 lua_pop(lua->T, 1);
1768 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001769 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001770 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001771 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001772 ret = HLUA_E_ERRMSG;
1773 break;
1774
1775 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001776 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001777 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001778 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001779 break;
1780 }
1781
1782 switch (ret) {
1783 case HLUA_E_AGAIN:
1784 break;
1785
1786 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001787 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001788 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001789 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001790 break;
1791
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001792 case HLUA_E_ETMOUT:
1793 case HLUA_E_NOMEM:
1794 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001795 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001796 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001797 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001798 hlua_ctx_renew(lua, 0);
1799 break;
1800
1801 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001802 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001803 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001804 break;
1805 }
1806
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001807 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001808 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001809
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001810 return ret;
1811}
1812
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001813/* This function exit the current code. */
1814__LJMP static int hlua_done(lua_State *L)
1815{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001816 struct hlua *hlua;
1817
1818 /* Get hlua struct, or NULL if we execute from main lua state */
1819 hlua = hlua_gethlua(L);
1820 if (!hlua)
1821 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001822
1823 hlua->flags |= HLUA_EXIT;
1824 WILL_LJMP(lua_error(L));
1825
1826 return 0;
1827}
1828
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001829/* This function is an LUA binding. It provides a function
1830 * for deleting ACL from a referenced ACL file.
1831 */
1832__LJMP static int hlua_del_acl(lua_State *L)
1833{
1834 const char *name;
1835 const char *key;
1836 struct pat_ref *ref;
1837
1838 MAY_LJMP(check_args(L, 2, "del_acl"));
1839
1840 name = MAY_LJMP(luaL_checkstring(L, 1));
1841 key = MAY_LJMP(luaL_checkstring(L, 2));
1842
1843 ref = pat_ref_lookup(name);
1844 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001845 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001846
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001847 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001848 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001849 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001850 return 0;
1851}
1852
1853/* This function is an LUA binding. It provides a function
1854 * for deleting map entry from a referenced map file.
1855 */
1856static int hlua_del_map(lua_State *L)
1857{
1858 const char *name;
1859 const char *key;
1860 struct pat_ref *ref;
1861
1862 MAY_LJMP(check_args(L, 2, "del_map"));
1863
1864 name = MAY_LJMP(luaL_checkstring(L, 1));
1865 key = MAY_LJMP(luaL_checkstring(L, 2));
1866
1867 ref = pat_ref_lookup(name);
1868 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001869 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001870
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001871 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001872 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001873 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001874 return 0;
1875}
1876
1877/* This function is an LUA binding. It provides a function
1878 * for adding ACL pattern from a referenced ACL file.
1879 */
1880static int hlua_add_acl(lua_State *L)
1881{
1882 const char *name;
1883 const char *key;
1884 struct pat_ref *ref;
1885
1886 MAY_LJMP(check_args(L, 2, "add_acl"));
1887
1888 name = MAY_LJMP(luaL_checkstring(L, 1));
1889 key = MAY_LJMP(luaL_checkstring(L, 2));
1890
1891 ref = pat_ref_lookup(name);
1892 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001893 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001894
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001895 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001896 if (pat_ref_find_elt(ref, key) == NULL)
1897 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001898 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001899 return 0;
1900}
1901
1902/* This function is an LUA binding. It provides a function
1903 * for setting map pattern and sample from a referenced map
1904 * file.
1905 */
1906static int hlua_set_map(lua_State *L)
1907{
1908 const char *name;
1909 const char *key;
1910 const char *value;
1911 struct pat_ref *ref;
1912
1913 MAY_LJMP(check_args(L, 3, "set_map"));
1914
1915 name = MAY_LJMP(luaL_checkstring(L, 1));
1916 key = MAY_LJMP(luaL_checkstring(L, 2));
1917 value = MAY_LJMP(luaL_checkstring(L, 3));
1918
1919 ref = pat_ref_lookup(name);
1920 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001921 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001922
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001923 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001924 if (pat_ref_find_elt(ref, key) != NULL)
1925 pat_ref_set(ref, key, value, NULL);
1926 else
1927 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001928 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001929 return 0;
1930}
1931
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001932/* A class is a lot of memory that contain data. This data can be a table,
1933 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001934 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001935 * the name of the object (_G[<name>] = <metable> ).
1936 *
1937 * A metable is a table that modify the standard behavior of a standard
1938 * access to the associated data. The entries of this new metatable are
1939 * defined as is:
1940 *
1941 * http://lua-users.org/wiki/MetatableEvents
1942 *
1943 * __index
1944 *
1945 * we access an absent field in a table, the result is nil. This is
1946 * true, but it is not the whole truth. Actually, such access triggers
1947 * the interpreter to look for an __index metamethod: If there is no
1948 * such method, as usually happens, then the access results in nil;
1949 * otherwise, the metamethod will provide the result.
1950 *
1951 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1952 * the key does not appear in the table, but the metatable has an __index
1953 * property:
1954 *
1955 * - if the value is a function, the function is called, passing in the
1956 * table and the key; the return value of that function is returned as
1957 * the result.
1958 *
1959 * - if the value is another table, the value of the key in that table is
1960 * asked for and returned (and if it doesn't exist in that table, but that
1961 * table's metatable has an __index property, then it continues on up)
1962 *
1963 * - Use "rawget(myTable,key)" to skip this metamethod.
1964 *
1965 * http://www.lua.org/pil/13.4.1.html
1966 *
1967 * __newindex
1968 *
1969 * Like __index, but control property assignment.
1970 *
1971 * __mode - Control weak references. A string value with one or both
1972 * of the characters 'k' and 'v' which specifies that the the
1973 * keys and/or values in the table are weak references.
1974 *
1975 * __call - Treat a table like a function. When a table is followed by
1976 * parenthesis such as "myTable( 'foo' )" and the metatable has
1977 * a __call key pointing to a function, that function is invoked
1978 * (passing any specified arguments) and the return value is
1979 * returned.
1980 *
1981 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1982 * called, if the metatable for myTable has a __metatable
1983 * key, the value of that key is returned instead of the
1984 * actual metatable.
1985 *
1986 * __tostring - Control string representation. When the builtin
1987 * "tostring( myTable )" function is called, if the metatable
1988 * for myTable has a __tostring property set to a function,
1989 * that function is invoked (passing myTable to it) and the
1990 * return value is used as the string representation.
1991 *
1992 * __len - Control table length. When the table length is requested using
1993 * the length operator ( '#' ), if the metatable for myTable has
1994 * a __len key pointing to a function, that function is invoked
1995 * (passing myTable to it) and the return value used as the value
1996 * of "#myTable".
1997 *
1998 * __gc - Userdata finalizer code. When userdata is set to be garbage
1999 * collected, if the metatable has a __gc field pointing to a
2000 * function, that function is first invoked, passing the userdata
2001 * to it. The __gc metamethod is not called for tables.
2002 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
2003 *
2004 * Special metamethods for redefining standard operators:
2005 * http://www.lua.org/pil/13.1.html
2006 *
2007 * __add "+"
2008 * __sub "-"
2009 * __mul "*"
2010 * __div "/"
2011 * __unm "!"
2012 * __pow "^"
2013 * __concat ".."
2014 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002015 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002016 * http://www.lua.org/pil/13.2.html
2017 *
2018 * __eq "=="
2019 * __lt "<"
2020 * __le "<="
2021 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022
2023/*
2024 *
2025 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002026 * Class Map
2027 *
2028 *
2029 */
2030
2031/* Returns a struct hlua_map if the stack entry "ud" is
2032 * a class session, otherwise it throws an error.
2033 */
2034__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2035{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002036 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002037}
2038
2039/* This function is the map constructor. It don't need
2040 * the class Map object. It creates and return a new Map
2041 * object. It must be called only during "body" or "init"
2042 * context because it process some filesystem accesses.
2043 */
2044__LJMP static int hlua_map_new(struct lua_State *L)
2045{
2046 const char *fn;
2047 int match = PAT_MATCH_STR;
2048 struct sample_conv conv;
2049 const char *file = "";
2050 int line = 0;
2051 lua_Debug ar;
2052 char *err = NULL;
2053 struct arg args[2];
2054
2055 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2056 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2057
2058 fn = MAY_LJMP(luaL_checkstring(L, 1));
2059
2060 if (lua_gettop(L) >= 2) {
2061 match = MAY_LJMP(luaL_checkinteger(L, 2));
2062 if (match < 0 || match >= PAT_MATCH_NUM)
2063 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2064 }
2065
2066 /* Get Lua filename and line number. */
2067 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2068 lua_getinfo(L, "Sl", &ar); /* get info about it */
2069 if (ar.currentline > 0) { /* is there info? */
2070 file = ar.short_src;
2071 line = ar.currentline;
2072 }
2073 }
2074
2075 /* fill fake sample_conv struct. */
2076 conv.kw = ""; /* unused. */
2077 conv.process = NULL; /* unused. */
2078 conv.arg_mask = 0; /* unused. */
2079 conv.val_args = NULL; /* unused. */
2080 conv.out_type = SMP_T_STR;
2081 conv.private = (void *)(long)match;
2082 switch (match) {
2083 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2084 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2085 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2086 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2087 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2088 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2089 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002090 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002091 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2092 default:
2093 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2094 }
2095
2096 /* fill fake args. */
2097 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002098 args[0].data.str.area = strdup(fn);
2099 args[0].data.str.data = strlen(fn);
2100 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002101 args[1].type = ARGT_STOP;
2102
2103 /* load the map. */
2104 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002105 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002106 * free the err variable.
2107 */
2108 luaL_where(L, 1);
2109 lua_pushfstring(L, "'new': %s.", err);
2110 lua_concat(L, 2);
2111 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002112 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002113 WILL_LJMP(lua_error(L));
2114 }
2115
2116 /* create the lua object. */
2117 lua_newtable(L);
2118 lua_pushlightuserdata(L, args[0].data.map);
2119 lua_rawseti(L, -2, 0);
2120
2121 /* Pop a class Map metatable and affect it to the userdata. */
2122 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2123 lua_setmetatable(L, -2);
2124
2125
2126 return 1;
2127}
2128
2129__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2130{
2131 struct map_descriptor *desc;
2132 struct pattern *pat;
2133 struct sample smp;
2134
2135 MAY_LJMP(check_args(L, 2, "lookup"));
2136 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002137 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002138 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002139 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002140 }
2141 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002142 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002143 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002144 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 +01002145 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002146 }
2147
2148 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002149 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002150 if (str)
2151 lua_pushstring(L, "");
2152 else
2153 lua_pushnil(L);
2154 return 1;
2155 }
2156
2157 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002158 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002159 return 1;
2160}
2161
2162__LJMP static int hlua_map_lookup(struct lua_State *L)
2163{
2164 return _hlua_map_lookup(L, 0);
2165}
2166
2167__LJMP static int hlua_map_slookup(struct lua_State *L)
2168{
2169 return _hlua_map_lookup(L, 1);
2170}
2171
2172/*
2173 *
2174 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175 * Class Socket
2176 *
2177 *
2178 */
2179
2180__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2181{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002182 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183}
2184
2185/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002186 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187 * received.
2188 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002189static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190{
Willy Tarreau5321da92022-05-06 11:57:34 +02002191 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002192 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002193
Christopher Faulet31572222023-03-31 11:13:48 +02002194 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
2195 notification_wake(&ctx->wake_on_read);
2196 notification_wake(&ctx->wake_on_write);
2197 return;
2198 }
2199
Willy Tarreau5321da92022-05-06 11:57:34 +02002200 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002201 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002202 notification_wake(&ctx->wake_on_read);
2203 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002204 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002205 }
2206
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002207 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002208 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002209 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002210
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002211 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002212 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002213 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002214
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002215 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002216 * to be notified whenever the connection completes.
2217 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002218 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002219 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002220 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002221 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002222 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002223 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224
2225 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002226 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002228 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002229 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002230 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231
2232 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002233 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002234 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002235
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002236 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002237 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002238 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002239 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002240 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241}
2242
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002243static int hlua_socket_init(struct appctx *appctx)
2244{
2245 struct hlua_csk_ctx *ctx = appctx->svcctx;
2246 struct stream *s;
2247
2248 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2249 goto error;
2250
2251 s = appctx_strm(appctx);
2252
Willy Tarreau4596fe22022-05-17 19:07:51 +02002253 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002254 * and retrieve data from the server. The connection is initialized
2255 * with the "struct server".
2256 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002257 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002258
2259 /* Force destination server. */
2260 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2261 s->target = &socket_tcp->obj_type;
2262
2263 ctx->appctx = appctx;
2264 return 0;
2265
2266 error:
2267 return -1;
2268}
2269
Willy Tarreau87b09662015-04-03 00:22:06 +02002270/* This function is called when the "struct stream" is destroyed.
2271 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002272 * Wake all the pending signals.
2273 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002274static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275{
Willy Tarreau5321da92022-05-06 11:57:34 +02002276 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002277 struct xref *peer;
2278
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002279 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002280 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002281 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002282 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283
2284 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002285 notification_wake(&ctx->wake_on_read);
2286 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287}
2288
2289/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002290 * uses this object. If the stream does not exists, just quit.
2291 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002292 * pending signal can rest in the read and write lists. destroy
2293 * it.
2294 */
2295__LJMP static int hlua_socket_gc(lua_State *L)
2296{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002297 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002298 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002299 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002301 MAY_LJMP(check_args(L, 1, "__gc"));
2302
2303 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002304 peer = xref_get_peer_and_lock(&socket->xref);
2305 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002307
2308 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002310 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002311 ctx->die = 1;
2312 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002314 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002315 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 return 0;
2317}
2318
2319/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002320 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 */
sada05ed3302018-05-11 11:48:18 -07002322__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002324 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002325 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002326 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002327 struct hlua *hlua;
2328
2329 /* Get hlua struct, or NULL if we execute from main lua state */
2330 hlua = hlua_gethlua(L);
2331 if (!hlua)
2332 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002334 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002335
2336 /* Check if we run on the same thread than the xreator thread.
2337 * We cannot access to the socket if the thread is different.
2338 */
2339 if (socket->tid != tid)
2340 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2341
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002342 peer = xref_get_peer_and_lock(&socket->xref);
2343 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002344 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002345
2346 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002347 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002349 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002350 ctx->die = 1;
2351 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002353 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002354 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355 return 0;
2356}
2357
sada05ed3302018-05-11 11:48:18 -07002358/* The close function calls close_helper.
2359 */
2360__LJMP static int hlua_socket_close(lua_State *L)
2361{
2362 MAY_LJMP(check_args(L, 1, "close"));
2363 return hlua_socket_close_helper(L);
2364}
2365
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366/* This Lua function assumes that the stack contain three parameters.
2367 * 1 - USERDATA containing a struct socket
2368 * 2 - INTEGER with values of the macro defined below
2369 * If the integer is -1, we must read at most one line.
2370 * If the integer is -2, we ust read all the data until the
2371 * end of the stream.
2372 * If the integer is positive value, we must read a number of
2373 * bytes corresponding to this value.
2374 */
2375#define HLSR_READ_LINE (-1)
2376#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002377__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378{
2379 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2380 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002381 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002382 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002384 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002385 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002386 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002387 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002388 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002389 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002390 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002391 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002392 struct stream *s;
2393 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002394 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002396 /* Get hlua struct, or NULL if we execute from main lua state */
2397 hlua = hlua_gethlua(L);
2398
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 /* Check if this lua stack is schedulable. */
2400 if (!hlua || !hlua->task)
2401 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2402 "'frontend', 'backend' or 'task'"));
2403
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002404 /* Check if we run on the same thread than the xreator thread.
2405 * We cannot access to the socket if the thread is different.
2406 */
2407 if (socket->tid != tid)
2408 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2409
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002410 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002411 peer = xref_get_peer_and_lock(&socket->xref);
2412 if (!peer)
2413 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002414
2415 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2416 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002417 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002418
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002419 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002422 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002423 if (nblk < 0) /* Connection close. */
2424 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002425 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002426 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002427
2428 /* remove final \r\n. */
2429 if (nblk == 1) {
2430 if (blk1[len1-1] == '\n') {
2431 len1--;
2432 skip_at_end++;
2433 if (blk1[len1-1] == '\r') {
2434 len1--;
2435 skip_at_end++;
2436 }
2437 }
2438 }
2439 else {
2440 if (blk2[len2-1] == '\n') {
2441 len2--;
2442 skip_at_end++;
2443 if (blk2[len2-1] == '\r') {
2444 len2--;
2445 skip_at_end++;
2446 }
2447 }
2448 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449 }
2450
2451 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002452 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002453 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454 if (nblk < 0) /* Connection close. */
2455 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002456 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002457 goto connection_empty;
2458 }
2459
2460 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002461 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002462 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002463 if (nblk < 0) /* Connection close. */
2464 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002465 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002466 goto connection_empty;
2467
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002468 missing_bytes = wanted - socket->b.n;
2469 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002471 len1 = missing_bytes;
2472 } if (nblk == 2 && len1 + len2 > missing_bytes)
2473 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474 }
2475
2476 len = len1;
2477
2478 luaL_addlstring(&socket->b, blk1, len1);
2479 if (nblk == 2) {
2480 len += len2;
2481 luaL_addlstring(&socket->b, blk2, len2);
2482 }
2483
2484 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002485 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486
2487 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002488 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002489
2490 /* If the pattern reclaim to read all the data
2491 * in the connection, got out.
2492 */
2493 if (wanted == HLSR_READ_ALL)
2494 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002495 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002496 goto connection_empty;
2497
2498 /* Return result. */
2499 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002500 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501 return 1;
2502
2503connection_closed:
2504
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002505 xref_unlock(&socket->xref, peer);
2506
2507no_peer:
2508
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509 /* If the buffer containds data. */
2510 if (socket->b.n > 0) {
2511 luaL_pushresult(&socket->b);
2512 return 1;
2513 }
2514 lua_pushnil(L);
2515 lua_pushstring(L, "connection closed.");
2516 return 2;
2517
2518connection_empty:
2519
Willy Tarreau5321da92022-05-06 11:57:34 +02002520 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002521 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002523 }
2524 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002525 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002526 return 0;
2527}
2528
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002529/* This Lua function gets two parameters. The first one can be string
2530 * or a number. If the string is "*l", the user requires one line. If
2531 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002532 * If the value is a number, the user require a number of bytes equal
2533 * to the value. The default value is "*l" (a line).
2534 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002535 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002536 * integer takes this values:
2537 * -1 : read a line
2538 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002539 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002540 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002541 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542 * concatenated with the read data.
2543 */
2544__LJMP static int hlua_socket_receive(struct lua_State *L)
2545{
2546 int wanted = HLSR_READ_LINE;
2547 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002548 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002549 char *error;
2550 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002551 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002552
2553 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2554 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2555
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002556 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002557
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002558 /* Check if we run on the same thread than the xreator thread.
2559 * We cannot access to the socket if the thread is different.
2560 */
2561 if (socket->tid != tid)
2562 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2563
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002564 /* check for pattern. */
2565 if (lua_gettop(L) >= 2) {
2566 type = lua_type(L, 2);
2567 if (type == LUA_TSTRING) {
2568 pattern = lua_tostring(L, 2);
2569 if (strcmp(pattern, "*a") == 0)
2570 wanted = HLSR_READ_ALL;
2571 else if (strcmp(pattern, "*l") == 0)
2572 wanted = HLSR_READ_LINE;
2573 else {
2574 wanted = strtoll(pattern, &error, 10);
2575 if (*error != '\0')
2576 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2577 }
2578 }
2579 else if (type == LUA_TNUMBER) {
2580 wanted = lua_tointeger(L, 2);
2581 if (wanted < 0)
2582 WILL_LJMP(luaL_error(L, "Unsupported size."));
2583 }
2584 }
2585
2586 /* Set pattern. */
2587 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002588
2589 /* Check if we would replace the top by itself. */
2590 if (lua_gettop(L) != 2)
2591 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002592
Christopher Fauletc31b2002021-05-03 10:11:13 +02002593 /* Save index of the top of the stack because since buffers are used, it
2594 * may change
2595 */
2596 lastarg = lua_gettop(L);
2597
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002598 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002599 luaL_buffinit(L, &socket->b);
2600
2601 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002602 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603 if (lua_type(L, 3) != LUA_TSTRING)
2604 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2605 pattern = lua_tolstring(L, 3, &len);
2606 luaL_addlstring(&socket->b, pattern, len);
2607 }
2608
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610}
2611
2612/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002613 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002615static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616{
2617 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002618 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002619 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620 struct appctx *appctx;
2621 size_t buf_len;
2622 const char *buf;
2623 int len;
2624 int send_len;
2625 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002626 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002627 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002628 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002629
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002630 /* Get hlua struct, or NULL if we execute from main lua state */
2631 hlua = hlua_gethlua(L);
2632
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633 /* Check if this lua stack is schedulable. */
2634 if (!hlua || !hlua->task)
2635 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2636 "'frontend', 'backend' or 'task'"));
2637
2638 /* Get object */
2639 socket = MAY_LJMP(hlua_checksocket(L, 1));
2640 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002641 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002642
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002643 /* Check if we run on the same thread than the xreator thread.
2644 * We cannot access to the socket if the thread is different.
2645 */
2646 if (socket->tid != tid)
2647 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2648
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002649 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002650 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002651 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002652 lua_pushinteger(L, -1);
2653 return 1;
2654 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002655
2656 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2657 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002658 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002659 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002662 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002663 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002664 lua_pushinteger(L, -1);
2665 return 1;
2666 }
2667
2668 /* Update the input buffer data. */
2669 buf += sent;
2670 send_len = buf_len - sent;
2671
2672 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002673 if (sent >= buf_len) {
2674 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002675 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002676 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002678 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002679 * the request buffer if its not required.
2680 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002681 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002682 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002683 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002684 }
2685
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002686 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002687 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002688 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002690 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002691
2692 /* send data */
2693 if (len < send_len)
2694 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002695 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002696
2697 /* "Not enough space" (-1), "Buffer too little to contain
2698 * the data" (-2) are not expected because the available length
2699 * is tested.
2700 * Other unknown error are also not expected.
2701 */
2702 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002703 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002704 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002705
sada05ed3302018-05-11 11:48:18 -07002706 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002707 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002708 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002709 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002710 return 1;
2711 }
2712
2713 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002714 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002715
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716 /* Update length sent. */
2717 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002718 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719
2720 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002721 if (sent + len >= buf_len) {
2722 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002724 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725
2726hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002727 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002728 xref_unlock(&socket->xref, peer);
2729 WILL_LJMP(luaL_error(L, "out of memory"));
2730 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002731 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002732 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733 return 0;
2734}
2735
2736/* This function initiate the send of data. It just check the input
2737 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002738 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002739 * "hlua_socket_write_yield" that can yield.
2740 *
2741 * The Lua function gets between 3 and 4 parameters. The first one is
2742 * the associated object. The second is a string buffer. The third is
2743 * a facultative integer that represents where is the buffer position
2744 * of the start of the data that can send. The first byte is the
2745 * position "1". The default value is "1". The fourth argument is a
2746 * facultative integer that represents where is the buffer position
2747 * of the end of the data that can send. The default is the last byte.
2748 */
2749static int hlua_socket_send(struct lua_State *L)
2750{
2751 int i;
2752 int j;
2753 const char *buf;
2754 size_t buf_len;
2755
2756 /* Check number of arguments. */
2757 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2758 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2759
2760 /* Get the string. */
2761 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2762
2763 /* Get and check j. */
2764 if (lua_gettop(L) == 4) {
2765 j = MAY_LJMP(luaL_checkinteger(L, 4));
2766 if (j < 0)
2767 j = buf_len + j + 1;
2768 if (j > buf_len)
2769 j = buf_len + 1;
2770 lua_pop(L, 1);
2771 }
2772 else
2773 j = buf_len;
2774
2775 /* Get and check i. */
2776 if (lua_gettop(L) == 3) {
2777 i = MAY_LJMP(luaL_checkinteger(L, 3));
2778 if (i < 0)
2779 i = buf_len + i + 1;
2780 if (i > buf_len)
2781 i = buf_len + 1;
2782 lua_pop(L, 1);
2783 } else
2784 i = 1;
2785
2786 /* Check bth i and j. */
2787 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002788 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789 return 1;
2790 }
2791 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002792 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793 return 1;
2794 }
2795 if (i == 0)
2796 i = 1;
2797 if (j == 0)
2798 j = 1;
2799
2800 /* Pop the string. */
2801 lua_pop(L, 1);
2802
2803 /* Update the buffer length. */
2804 buf += i - 1;
2805 buf_len = j - i + 1;
2806 lua_pushlstring(L, buf, buf_len);
2807
2808 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002809 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002810
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002811 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002812}
2813
Willy Tarreau22b0a682015-06-17 19:43:49 +02002814#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002815__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002816{
2817 static char buffer[SOCKET_INFO_MAX_LEN];
2818 int ret;
2819 int len;
2820 char *p;
2821
2822 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2823 if (ret <= 0) {
2824 lua_pushnil(L);
2825 return 1;
2826 }
2827
2828 if (ret == AF_UNIX) {
2829 lua_pushstring(L, buffer+1);
2830 return 1;
2831 }
2832 else if (ret == AF_INET6) {
2833 buffer[0] = '[';
2834 len = strlen(buffer);
2835 buffer[len] = ']';
2836 len++;
2837 buffer[len] = ':';
2838 len++;
2839 p = buffer;
2840 }
2841 else if (ret == AF_INET) {
2842 p = buffer + 1;
2843 len = strlen(p);
2844 p[len] = ':';
2845 len++;
2846 }
2847 else {
2848 lua_pushnil(L);
2849 return 1;
2850 }
2851
2852 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2853 lua_pushnil(L);
2854 return 1;
2855 }
2856
2857 lua_pushstring(L, p);
2858 return 1;
2859}
2860
2861/* Returns information about the peer of the connection. */
2862__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2863{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002864 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002865 struct xref *peer;
2866 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002867 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002868 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002869 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002870
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002871 MAY_LJMP(check_args(L, 1, "getpeername"));
2872
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002873 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002874
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002875 /* Check if we run on the same thread than the xreator thread.
2876 * We cannot access to the socket if the thread is different.
2877 */
2878 if (socket->tid != tid)
2879 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2880
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002881 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002882 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002883 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002884 lua_pushnil(L);
2885 return 1;
2886 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002887
2888 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002889 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002890 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002891 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002892 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002893 lua_pushnil(L);
2894 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002895 }
2896
Christopher Faulet16f16af2021-10-27 09:34:56 +02002897 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002898 xref_unlock(&socket->xref, peer);
2899 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002900}
2901
2902/* Returns information about my connection side. */
2903static int hlua_socket_getsockname(struct lua_State *L)
2904{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002905 struct hlua_socket *socket;
2906 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002907 struct appctx *appctx;
2908 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002909 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002910 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002911
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002912 MAY_LJMP(check_args(L, 1, "getsockname"));
2913
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002914 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002915
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002916 /* Check if we run on the same thread than the xreator thread.
2917 * We cannot access to the socket if the thread is different.
2918 */
2919 if (socket->tid != tid)
2920 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2921
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002922 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002923 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002924 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002925 lua_pushnil(L);
2926 return 1;
2927 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002928
2929 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002930 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002931
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002932 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002933 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002934 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002935 lua_pushnil(L);
2936 return 1;
2937 }
2938
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002939 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002940 xref_unlock(&socket->xref, peer);
2941 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002942}
2943
2944/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002945static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002946 .obj_type = OBJ_TYPE_APPLET,
2947 .name = "<LUA_TCP>",
2948 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002949 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002950 .release = hlua_socket_release,
2951};
2952
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002953__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002954{
2955 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002956 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002957 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002958 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002959 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002960 struct stream *s;
2961
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002962 /* Get hlua struct, or NULL if we execute from main lua state */
2963 hlua = hlua_gethlua(L);
2964 if (!hlua)
2965 return 0;
2966
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002967 /* Check if we run on the same thread than the xreator thread.
2968 * We cannot access to the socket if the thread is different.
2969 */
2970 if (socket->tid != tid)
2971 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2972
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002973 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002974 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002975 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002976 lua_pushnil(L);
2977 lua_pushstring(L, "Can't connect");
2978 return 2;
2979 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002980
2981 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2982 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002983 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002984
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002985 /* Check if we run on the same thread than the xreator thread.
2986 * We cannot access to the socket if the thread is different.
2987 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002988 if (socket->tid != tid) {
2989 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002990 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002991 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002992
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002993 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002994 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002995 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002996 lua_pushnil(L);
2997 lua_pushstring(L, "Can't connect");
2998 return 2;
2999 }
3000
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02003001 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003002
3003 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003004 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003005 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003006 lua_pushinteger(L, 1);
3007 return 1;
3008 }
3009
Willy Tarreau5321da92022-05-06 11:57:34 +02003010 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003011 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003012 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003013 }
3014 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003015 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003016 return 0;
3017}
3018
3019/* This function fail or initite the connection. */
3020__LJMP static int hlua_socket_connect(struct lua_State *L)
3021{
3022 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003023 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003024 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003025 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003026 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003027 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003028 int low, high;
3029 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003030 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003031 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003032 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003033
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003034 if (lua_gettop(L) < 2)
3035 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003036
3037 /* Get args. */
3038 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003039
3040 /* Check if we run on the same thread than the xreator thread.
3041 * We cannot access to the socket if the thread is different.
3042 */
3043 if (socket->tid != tid)
3044 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3045
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003046 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003047 if (lua_gettop(L) >= 3) {
3048 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003049 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003050
Tim Duesterhus6edab862018-01-06 19:04:45 +01003051 /* Force the ip to end with a colon, to support IPv6 addresses
3052 * that are not enclosed within square brackets.
3053 */
3054 if (port > 0) {
3055 luaL_buffinit(L, &b);
3056 luaL_addstring(&b, ip);
3057 luaL_addchar(&b, ':');
3058 luaL_pushresult(&b);
3059 ip = lua_tolstring(L, lua_gettop(L), NULL);
3060 }
3061 }
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 return 1;
3068 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003069
3070 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003071 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 +02003072 if (!addr) {
3073 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003074 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003075 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003076
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003077 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003078 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003079 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003080 if (port == -1) {
3081 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003082 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003083 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003084 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3085 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003086 if (port == -1) {
3087 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003088 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003089 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003090 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003091 }
3092 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003093
Willy Tarreau5321da92022-05-06 11:57:34 +02003094 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3095 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003096 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003097 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003098
Willy Tarreau3e7be362022-05-27 10:35:27 +02003099 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003100 xref_unlock(&socket->xref, peer);
3101 WILL_LJMP(luaL_error(L, "connect: internal error"));
3102 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003103
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003104 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003105 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003106 if (!hlua)
3107 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003108
3109 /* inform the stream that we want to be notified whenever the
3110 * connection completes.
3111 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003112 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003113 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003114 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003115
Willy Tarreauf31af932020-01-14 09:59:38 +01003116 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003117
Willy Tarreau5321da92022-05-06 11:57:34 +02003118 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003119 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003120 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003121 }
3122 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003123
3124 task_wakeup(s->task, TASK_WOKEN_INIT);
3125 /* Return yield waiting for connection. */
3126
Willy Tarreau9635e032018-10-16 17:52:55 +02003127 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003128
3129 return 0;
3130}
3131
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003132#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003133__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3134{
3135 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003136 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003137 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003138
3139 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3140 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003141
3142 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003143 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003144 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003145 lua_pushnil(L);
3146 return 1;
3147 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003148
Willy Tarreau0698c802022-05-11 14:09:57 +02003149 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003150
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003151 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003152 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003153 return MAY_LJMP(hlua_socket_connect(L));
3154}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003155#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003156
3157__LJMP static int hlua_socket_setoption(struct lua_State *L)
3158{
3159 return 0;
3160}
3161
3162__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3163{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003164 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003165 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003166 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003167 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003168 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003169
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003170 MAY_LJMP(check_args(L, 2, "settimeout"));
3171
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003172 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003173
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003174 /* convert the timeout to millis */
3175 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003176
Thierry Fournier17a921b2018-03-08 09:59:02 +01003177 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003178 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003179 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3180
Mark Lakes56cc1252018-03-27 09:48:06 +02003181 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003182 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003183
3184 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003185 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003186 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003187
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003188 /* Check if we run on the same thread than the xreator thread.
3189 * We cannot access to the socket if the thread is different.
3190 */
3191 if (socket->tid != tid)
3192 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3193
Mark Lakes56cc1252018-03-27 09:48:06 +02003194 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003195 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003196 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003197 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3198 WILL_LJMP(lua_error(L));
3199 return 0;
3200 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003201
Willy Tarreau0698c802022-05-11 14:09:57 +02003202 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003203
Cyril Bonté7bb63452018-08-17 23:51:02 +02003204 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003205 s->scf->ioto = tmout;
3206 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003207
3208 s->task->expire = tick_add_ifset(now_ms, tmout);
3209 task_queue(s->task);
3210
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003211 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003212
Thierry Fourniere9636f12018-03-08 09:54:32 +01003213 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003214 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003215}
3216
3217__LJMP static int hlua_socket_new(lua_State *L)
3218{
3219 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003220 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003221 struct appctx *appctx;
3222
3223 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003224 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003225 hlua_pusherror(L, "socket: full stack");
3226 goto out_fail_conf;
3227 }
3228
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003229 /* Create the object: obj[0] = userdata. */
3230 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003231 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003232 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003233 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003234 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003235
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003236 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003237 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003238 hlua_pusherror(L, "socket: uninitialized pools.");
3239 goto out_fail_conf;
3240 }
3241
Willy Tarreau87b09662015-04-03 00:22:06 +02003242 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003243 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3244 lua_setmetatable(L, -2);
3245
Willy Tarreaud420a972015-04-06 00:39:18 +02003246 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003247 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003248 if (!appctx) {
3249 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003250 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003251 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003252 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3253 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003254 ctx->die = 0;
3255 LIST_INIT(&ctx->wake_on_write);
3256 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003257
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003258 if (appctx_init(appctx) == -1) {
3259 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003260 goto out_fail_appctx;
3261 }
3262
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003263 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003264 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003265 return 1;
3266
Christopher Faulet13a35e52021-12-20 15:34:16 +01003267 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003268 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003269 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003270 WILL_LJMP(lua_error(L));
3271 return 0;
3272}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003273
3274/*
3275 *
3276 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003277 * Class Channel
3278 *
3279 *
3280 */
3281
3282/* Returns the struct hlua_channel join to the class channel in the
3283 * stack entry "ud" or throws an argument error.
3284 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003285__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003286{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003287 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003288}
3289
Willy Tarreau47860ed2015-03-10 14:07:50 +01003290/* Pushes the channel onto the top of the stack. If the stask does not have a
3291 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003292 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003293static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003294{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003295 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003296 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003297 return 0;
3298
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003299 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003300 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003301 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003302
3303 /* Pop a class sesison metatable and affect it to the userdata. */
3304 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3305 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003306 return 1;
3307}
3308
Christopher Faulet9f55a502020-02-25 15:21:02 +01003309/* Helper function returning a filter attached to a channel at the position <ud>
3310 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003311 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003312 * initialized.
3313 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003314static 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 +01003315{
3316 struct filter *filter = NULL;
3317
3318 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3319 struct hlua_flt_ctx *flt_ctx;
3320
3321 filter = lua_touserdata (L, -1);
3322 flt_ctx = filter->ctx;
3323 if (hlua_filter_from_payload(filter)) {
3324 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3325 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3326 }
3327 }
3328
3329 lua_pop(L, 1);
3330 return filter;
3331}
3332
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003333/* Copies <len> bytes of data present in the channel's buffer, starting at the
3334* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003335* responsibility to ensure <len> and <offset> are valid. It always return the
3336* length of the built string. <len> may be 0, in this case, an empty string is
3337* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003338*/
3339static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003341 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003342 luaL_Buffer b;
3343
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003344 block1 = len;
3345 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3346 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3347 block2 = len - block1;
3348
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003349 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003350 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3351 if (block2)
3352 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003353 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003354 return len;
3355}
3356
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003357/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3358 * function returns -1 if data cannot be copied. Otherwise, it returns the
3359 * number of bytes copied.
3360 */
3361static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3362{
3363 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003364
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003365 /* Nothing to do, just return */
3366 if (unlikely(istlen(str) == 0))
3367 goto end;
3368
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003369 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003370 ret = -1;
3371 goto end;
3372 }
3373 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3374
3375 end:
3376 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003377}
3378
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003379/* Removes <len> bytes of data at the absolute position <offset>.
3380 */
3381static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3382{
3383 size_t end = offset + len;
3384
3385 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3386 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3387 b_data(&chn->buf) - end, -len);
3388 b_sub(&chn->buf, len);
3389}
3390
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003391/* Copies input data in the channel's buffer. It is possible to set a specific
3392 * offset (0 by default) and a length (all remaining input data starting for the
3393 * offset by default). If there is not enough input data and more data can be
3394 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003395 *
3396 * From an action, All input data are considered. For a filter, the offset and
3397 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003398 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003399__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003400{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003401 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003402 struct filter *filter;
3403 size_t input, output;
3404 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003405
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003406 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003407
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003408 output = co_data(chn);
3409 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003410
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003411 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3412 if (filter && !hlua_filter_from_payload(filter))
3413 WILL_LJMP(lua_error(L));
3414
3415 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003416 if (lua_gettop(L) > 1) {
3417 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3418 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003419 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003420 offset += output;
3421 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003422 lua_pushfstring(L, "offset out of range.");
3423 WILL_LJMP(lua_error(L));
3424 }
3425 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003426 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003427 if (lua_gettop(L) == 3) {
3428 len = MAY_LJMP(luaL_checkinteger(L, 3));
3429 if (!len)
3430 goto dup;
3431 if (len == -1)
3432 len = global.tune.bufsize;
3433 if (len < 0) {
3434 lua_pushfstring(L, "length out of range.");
3435 WILL_LJMP(lua_error(L));
3436 }
3437 }
3438
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003439 /* Wait for more data if possible if no length was specified and there
3440 * is no data or not enough data was received.
3441 */
3442 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003443 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3444 /* Yield waiting for more data, as requested */
3445 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3446 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003447
3448 /* Return 'nil' if there is no data and the channel can't receive more data */
3449 if (!len) {
3450 lua_pushnil(L);
3451 return -1;
3452 }
3453
3454 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003455 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003456 }
3457
3458 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003459 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003460 return 1;
3461}
3462
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003463/* Copies the first line (including the trailing LF) of input data in the
3464 * channel's buffer. It is possible to set a specific offset (0 by default) and
3465 * a length (all remaining input data starting for the offset by default). If
3466 * there is not enough input data and more data can be received, the function
3467 * yields. If a length is explicitly specified, no more data are
3468 * copied. Otherwise, if no LF is found and more data can be received, this
3469 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003470 *
3471 * From an action, All input data are considered. For a filter, the offset and
3472 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003473 */
3474__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003475{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003476 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003477 struct filter *filter;
3478 size_t l, input, output;
3479 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003480
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003481 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003482 output = co_data(chn);
3483 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003484
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003485 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3486 if (filter && !hlua_filter_from_payload(filter))
3487 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003488
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003489 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003490 if (lua_gettop(L) > 1) {
3491 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3492 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003493 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003494 offset += output;
3495 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003496 lua_pushfstring(L, "offset out of range.");
3497 WILL_LJMP(lua_error(L));
3498 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003499 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003500
3501 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003502 if (lua_gettop(L) == 3) {
3503 len = MAY_LJMP(luaL_checkinteger(L, 3));
3504 if (!len)
3505 goto dup;
3506 if (len == -1)
3507 len = global.tune.bufsize;
3508 if (len < 0) {
3509 lua_pushfstring(L, "length out of range.");
3510 WILL_LJMP(lua_error(L));
3511 }
3512 }
3513
3514 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003515 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003516 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003517 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003518 len = l+1;
3519 goto dup;
3520 }
3521 }
3522
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003523 /* Wait for more data if possible if no line is found and no length was
3524 * specified or not enough data was received.
3525 */
3526 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003527 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3528 /* Yield waiting for more data */
3529 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3530 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003531
3532 /* Return 'nil' if there is no data and the channel can't receive more data */
3533 if (!len) {
3534 lua_pushnil(L);
3535 return -1;
3536 }
3537
3538 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003540 }
3541
3542 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003543 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003544 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003545}
3546
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003547/* [ DEPRECATED ]
3548 *
3549 * Duplicate all input data foud in the channel's buffer. The data are not
3550 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 *
3552 * From an action, All input data are considered. For a filter, the offset and
3553 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003554 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003555__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003556{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003557 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003558 struct filter *filter;
3559 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003560
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003561 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003562 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003563 if (IS_HTX_STRM(chn_strm(chn))) {
3564 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3565 WILL_LJMP(lua_error(L));
3566 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003567
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003568 offset = co_data(chn);
3569 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003570
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003571 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3572 if (filter && !hlua_filter_from_payload(filter))
3573 WILL_LJMP(lua_error(L));
3574
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003575 if (!ci_data(chn) && channel_input_closed(chn)) {
3576 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003577 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003578 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003579
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003580 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003581 return 1;
3582}
3583
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003584/* [ DEPRECATED ]
3585 *
3586 * Get all input data foud in the channel's buffer. The data are removed from
3587 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3588 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589 *
3590 * From an action, All input data are considered. For a filter, the offset and
3591 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003593__LJMP static int hlua_channel_get(lua_State *L)
3594{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003595 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003596 struct filter *filter;
3597 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003598 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003599
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003600 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003601 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3602 if (IS_HTX_STRM(chn_strm(chn))) {
3603 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3604 WILL_LJMP(lua_error(L));
3605 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003606
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003607 offset = co_data(chn);
3608 len = ci_data(chn);
3609
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003610 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3611 if (filter && !hlua_filter_from_payload(filter))
3612 WILL_LJMP(lua_error(L));
3613
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003614 if (!ci_data(chn) && channel_input_closed(chn)) {
3615 lua_pushnil(L);
3616 return 1;
3617 }
3618
3619 ret = _hlua_channel_dup(chn, L, offset, len);
3620 _hlua_channel_delete(chn, offset, ret);
3621 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003622}
3623
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003624/* This functions consumes and returns one line. If the channel is closed,
3625 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003626 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003627 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003628 *
3629 * From an action, All input data are considered. For a filter, the offset and
3630 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003631 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003632__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003633{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003634 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003635 struct filter *filter;
3636 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003637 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003638
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003639 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003640
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003641 offset = co_data(chn);
3642 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003643
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003644 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3645 if (filter && !hlua_filter_from_payload(filter))
3646 WILL_LJMP(lua_error(L));
3647
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003648 if (!ci_data(chn) && channel_input_closed(chn)) {
3649 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003650 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651 }
3652
3653 for (l = 0; l < len; l++) {
3654 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3655 len = l+1;
3656 goto dup;
3657 }
3658 }
3659
3660 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3661 /* Yield waiting for more data */
3662 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3663 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003664
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003665 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003667 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003668 return 1;
3669}
3670
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003671/* [ DEPRECATED ]
3672 *
3673 * Check arguments for the function "hlua_channel_getline_yield".
3674 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003675__LJMP static int hlua_channel_getline(lua_State *L)
3676{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003677 struct channel *chn;
3678
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003679 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003680 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3681 if (IS_HTX_STRM(chn_strm(chn))) {
3682 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3683 WILL_LJMP(lua_error(L));
3684 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003685 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3686}
3687
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688/* Retrieves a given amount of input data at the given offset. By default all
3689 * available input data are returned. The offset may be negactive to start from
3690 * the end of input data. The length may be -1 to set it to the maximum buffer
3691 * size.
3692 */
3693__LJMP static int hlua_channel_get_data(lua_State *L)
3694{
3695 struct channel *chn;
3696
3697 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3698 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3699 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3700 if (IS_HTX_STRM(chn_strm(chn))) {
3701 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3702 WILL_LJMP(lua_error(L));
3703 }
3704 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3705}
3706
3707/* Retrieves a given amount of input data at the given offset. By default all
3708 * available input data are returned. The offset may be negactive to start from
3709 * the end of input data. The length may be -1 to set it to the maximum buffer
3710 * size.
3711 */
3712__LJMP static int hlua_channel_get_line(lua_State *L)
3713{
3714 struct channel *chn;
3715
3716 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3717 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3718 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3719 if (IS_HTX_STRM(chn_strm(chn))) {
3720 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3721 WILL_LJMP(lua_error(L));
3722 }
3723 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3724}
3725
3726/* Appends a string into the input side of channel. It returns the length of the
3727 * written string, or -1 if the channel is closed or if the buffer size is too
3728 * little for the data. 0 may be returned if nothing is copied. This function
3729 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003730 *
3731 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003732 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003733__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003734{
Christopher Faulet23976d92021-08-06 09:59:49 +02003735 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003736 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003737 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003738 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003739 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003740
3741 MAY_LJMP(check_args(L, 2, "append"));
3742 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003743 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003744 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003745 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003746 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003747 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003748
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 offset = co_data(chn);
3750 len = ci_data(chn);
3751
3752 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3753 if (filter && !hlua_filter_from_payload(filter))
3754 WILL_LJMP(lua_error(L));
3755
3756 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3757 if (ret > 0 && filter) {
3758 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3759
3760 flt_update_offsets(filter, chn, ret);
3761 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3762 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003763 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003764 return 1;
3765}
3766
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003767/* Prepends a string into the input side of channel. It returns the length of the
3768 * written string, or -1 if the channel is closed or if the buffer size is too
3769 * little for the data. 0 may be returned if nothing is copied. This function
3770 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003771 *
3772 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003773 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003774__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003775{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003776 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003777 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003778 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003779 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003780 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003781
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003782 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003783 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003784 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3785 if (IS_HTX_STRM(chn_strm(chn))) {
3786 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3787 WILL_LJMP(lua_error(L));
3788 }
3789
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003790 offset = co_data(chn);
3791 len = ci_data(chn);
3792
3793 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3794 if (filter && !hlua_filter_from_payload(filter))
3795 WILL_LJMP(lua_error(L));
3796
3797 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3798 if (ret > 0 && filter) {
3799 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3800
3801 flt_update_offsets(filter, chn, ret);
3802 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3803 }
3804
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003805 lua_pushinteger(L, ret);
3806 return 1;
3807}
3808
3809/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003810 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003811 * returns the length of the written string, or -1 if the channel is closed or
3812 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003813 *
3814 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003815 */
3816__LJMP static int hlua_channel_insert_data(lua_State *L)
3817{
3818 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003819 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003820 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003821 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003822 int ret, offset;
3823
3824 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3825 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3826 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3827 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003828
3829 output = co_data(chn);
3830 input = ci_data(chn);
3831
3832 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3833 if (filter && !hlua_filter_from_payload(filter))
3834 WILL_LJMP(lua_error(L));
3835
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003836 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003837 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003838 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003839 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003840 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003841 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003842 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003843 lua_pushfstring(L, "offset out of range.");
3844 WILL_LJMP(lua_error(L));
3845 }
3846 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003847 if (IS_HTX_STRM(chn_strm(chn))) {
3848 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3849 WILL_LJMP(lua_error(L));
3850 }
3851
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003852 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3853 if (ret > 0 && filter) {
3854 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003855
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003856 flt_update_offsets(filter, chn, ret);
3857 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003858 }
3859
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003860 lua_pushinteger(L, ret);
3861 return 1;
3862}
3863/* Replaces a given amount of input data at the given offset by a string
3864 * content. By default all remaining data are removed (offset = 0 and len =
3865 * -1). It returns the length of the written string, or -1 if the channel is
3866 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003867 *
3868 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003869 */
3870__LJMP static int hlua_channel_set_data(lua_State *L)
3871{
3872 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003873 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003874 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003875 size_t sz, input, output;
3876 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003877
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003878 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3879 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3880 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3881 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003882
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003883 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003884 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003885 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003886 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003887
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003888 output = co_data(chn);
3889 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003890
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003891 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3892 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003893 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003894
3895 offset = output;
3896 if (lua_gettop(L) > 2) {
3897 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3898 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003899 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003900 offset += output;
3901 if (offset < output || offset > input + output) {
3902 lua_pushfstring(L, "offset out of range.");
3903 WILL_LJMP(lua_error(L));
3904 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003905 }
3906
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003907 len = output + input - offset;
3908 if (lua_gettop(L) == 4) {
3909 len = MAY_LJMP(luaL_checkinteger(L, 4));
3910 if (!len)
3911 goto set;
3912 if (len == -1)
3913 len = output + input - offset;
3914 if (len < 0 || offset + len > output + input) {
3915 lua_pushfstring(L, "length out of range.");
3916 WILL_LJMP(lua_error(L));
3917 }
3918 }
3919
3920 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003921 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003922 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003923 lua_pushinteger(L, -1);
3924 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003925 _hlua_channel_delete(chn, offset, len);
3926 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3927 if (filter) {
3928 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3929
3930 len -= (ret > 0 ? ret : 0);
3931 flt_update_offsets(filter, chn, -len);
3932 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3933 }
3934
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003935 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003936 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003937 return 1;
3938}
3939
3940/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003941 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003942 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003943 *
3944 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003945 */
3946__LJMP static int hlua_channel_del_data(lua_State *L)
3947{
3948 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003949 struct filter *filter;
3950 size_t input, output;
3951 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003952
3953 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3954 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3955 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003956
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003957 if (IS_HTX_STRM(chn_strm(chn))) {
3958 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3959 WILL_LJMP(lua_error(L));
3960 }
3961
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003962 output = co_data(chn);
3963 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003964
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003965 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3966 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003967 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003968
3969 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003970 if (lua_gettop(L) > 1) {
3971 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003972 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003973 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003974 offset += output;
3975 if (offset < output || offset > input + output) {
3976 lua_pushfstring(L, "offset out of range.");
3977 WILL_LJMP(lua_error(L));
3978 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003979 }
3980
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003981 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003982 if (lua_gettop(L) == 3) {
3983 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003984 if (!len)
3985 goto end;
3986 if (len == -1)
3987 len = output + input - offset;
3988 if (len < 0 || offset + len > output + input) {
3989 lua_pushfstring(L, "length out of range.");
3990 WILL_LJMP(lua_error(L));
3991 }
3992 }
3993
3994 _hlua_channel_delete(chn, offset, len);
3995 if (filter) {
3996 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3997
3998 flt_update_offsets(filter, chn, -len);
3999 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4000 }
4001
4002 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004003 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02004004 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004005}
4006
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004007/* Append data in the output side of the buffer. This data is immediately
4008 * sent. The function returns the amount of data written. If the buffer
4009 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004010 * if the channel is closed.
4011 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004012__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004013{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004014 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004015 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004016 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004017 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004018 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004019 struct hlua *hlua;
4020
4021 /* Get hlua struct, or NULL if we execute from main lua state */
4022 hlua = hlua_gethlua(L);
4023 if (!hlua) {
4024 lua_pushnil(L);
4025 return 1;
4026 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004027
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004028 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4029 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4030 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004031
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004032 offset = co_data(chn);
4033 len = ci_data(chn);
4034
4035 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4036 if (filter && !hlua_filter_from_payload(filter))
4037 WILL_LJMP(lua_error(L));
4038
4039
Willy Tarreau47860ed2015-03-10 14:07:50 +01004040 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004041 lua_pushinteger(L, -1);
4042 return 1;
4043 }
4044
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004045 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004046 if (len > sz -l) {
4047 if (filter) {
4048 lua_pushinteger(L, -1);
4049 return 1;
4050 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004051 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004052 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004053
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004054 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004055 if (ret == -1) {
4056 lua_pop(L, 1);
4057 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004058 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004059 }
4060 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004061 if (filter) {
4062 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4063
4064
4065 flt_update_offsets(filter, chn, ret);
4066 FLT_OFF(filter, chn) += ret;
4067 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4068 }
4069 else
4070 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004071
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004072 l += ret;
4073 lua_pop(L, 1);
4074 lua_pushinteger(L, l);
4075 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004076
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004077 if (l < sz) {
4078 /* Yield only if the channel's output is not empty.
4079 * Otherwise it means we cannot add more data. */
4080 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004081 return 1;
4082
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004083 /* If we are waiting for space in the response buffer, we
4084 * must set the flag WAKERESWR. This flag required the task
4085 * wake up if any activity is detected on the response buffer.
4086 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004087 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004088 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004089 else
4090 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004091 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004092 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004093
4094 return 1;
4095}
4096
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004097/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004098 * yield the LUA process, and resume it without checking the
4099 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004100 *
4101 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004102 */
4103__LJMP static int hlua_channel_send(lua_State *L)
4104{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004105 struct channel *chn;
4106
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004107 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004108 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4109 if (IS_HTX_STRM(chn_strm(chn))) {
4110 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4111 WILL_LJMP(lua_error(L));
4112 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004113 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004114 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004115}
4116
4117/* This function forward and amount of butes. The data pass from
4118 * the input side of the buffer to the output side, and can be
4119 * forwarded. This function never fails.
4120 *
4121 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004122 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004123 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004124__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004125{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004126 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004127 struct filter *filter;
4128 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004129 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004130 struct hlua *hlua;
4131
4132 /* Get hlua struct, or NULL if we execute from main lua state */
4133 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004134 if (!hlua) {
4135 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004136 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004137 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004138
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004139 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004140 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004141 l = MAY_LJMP(luaL_checkinteger(L, -1));
4142
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004143 offset = co_data(chn);
4144 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004145
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004146 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4147 if (filter && !hlua_filter_from_payload(filter))
4148 WILL_LJMP(lua_error(L));
4149
4150 max = fwd - l;
4151 if (max > len)
4152 max = len;
4153
4154 if (filter) {
4155 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4156
4157 FLT_OFF(filter, chn) += max;
4158 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4159 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4160 }
4161 else
4162 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004163
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004164 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004165 lua_pop(L, 1);
4166 lua_pushinteger(L, l);
4167
4168 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004169 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004170 /* The the input channel or the output channel are closed, we
4171 * must return the amount of data forwarded.
4172 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004173 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004174 return 1;
4175
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004176 /* If we are waiting for space data in the response buffer, we
4177 * must set the flag WAKERESWR. This flag required the task
4178 * wake up if any activity is detected on the response buffer.
4179 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004180 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004181 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004182 else
4183 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004184
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004185 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004186 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004187 }
4188
4189 return 1;
4190}
4191
4192/* Just check the input and prepare the stack for the previous
4193 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004194 *
4195 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004196 */
4197__LJMP static int hlua_channel_forward(lua_State *L)
4198{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004199 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004200
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004201 MAY_LJMP(check_args(L, 2, "forward"));
4202 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4203 if (IS_HTX_STRM(chn_strm(chn))) {
4204 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4205 WILL_LJMP(lua_error(L));
4206 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004207 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004208 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004209}
4210
4211/* Just returns the number of bytes available in the input
4212 * side of the buffer. This function never fails.
4213 */
4214__LJMP static int hlua_channel_get_in_len(lua_State *L)
4215{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004216 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004217 struct filter *filter;
4218 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004219
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004220 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004221 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004222
4223 output = co_data(chn);
4224 input = ci_data(chn);
4225 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4226 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4227 lua_pushinteger(L, input);
4228 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004229 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004230
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004231 lua_pushinteger(L, htx->data - co_data(chn));
4232 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004233 return 1;
4234}
4235
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004236/* Returns true if the channel is full. */
4237__LJMP static int hlua_channel_is_full(lua_State *L)
4238{
4239 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004240
4241 MAY_LJMP(check_args(L, 1, "is_full"));
4242 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004243 /* ignore the reserve, we are not on a producer side (ie in an
4244 * applet).
4245 */
4246 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004247 return 1;
4248}
4249
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004250/* Returns true if the channel may still receive data. */
4251__LJMP static int hlua_channel_may_recv(lua_State *L)
4252{
4253 struct channel *chn;
4254
4255 MAY_LJMP(check_args(L, 1, "may_recv"));
4256 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4257 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4258 return 1;
4259}
4260
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004261/* Returns true if the channel is the response channel. */
4262__LJMP static int hlua_channel_is_resp(lua_State *L)
4263{
4264 struct channel *chn;
4265
4266 MAY_LJMP(check_args(L, 1, "is_resp"));
4267 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4268
4269 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4270 return 1;
4271}
4272
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004273/* Just returns the number of bytes available in the output
4274 * side of the buffer. This function never fails.
4275 */
4276__LJMP static int hlua_channel_get_out_len(lua_State *L)
4277{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004278 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004279 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004280
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004281 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004282 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004283
4284 output = co_data(chn);
4285 input = ci_data(chn);
4286 hlua_channel_filter(L, 1, chn, &output, &input);
4287
4288 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004289 return 1;
4290}
4291
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004292/*
4293 *
4294 *
4295 * Class Fetches
4296 *
4297 *
4298 */
4299
4300/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004301 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004302 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004303__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004304{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004305 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004306}
4307
4308/* This function creates and push in the stack a fetch object according
4309 * with a current TXN.
4310 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004311static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004312{
Willy Tarreau7073c472015-04-06 11:15:40 +02004313 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004314
4315 /* Check stack size. */
4316 if (!lua_checkstack(L, 3))
4317 return 0;
4318
4319 /* Create the object: obj[0] = userdata.
4320 * Note that the base of the Fetches object is the
4321 * transaction object.
4322 */
4323 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004324 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004325 lua_rawseti(L, -2, 0);
4326
Willy Tarreau7073c472015-04-06 11:15:40 +02004327 hsmp->s = txn->s;
4328 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004329 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004330 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004331
4332 /* Pop a class sesison metatable and affect it to the userdata. */
4333 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4334 lua_setmetatable(L, -2);
4335
4336 return 1;
4337}
4338
4339/* This function is an LUA binding. It is called with each sample-fetch.
4340 * It uses closure argument to store the associated sample-fetch. It
4341 * returns only one argument or throws an error. An error is thrown
4342 * only if an error is encountered during the argument parsing. If
4343 * the "sample-fetch" function fails, nil is returned.
4344 */
4345__LJMP static int hlua_run_sample_fetch(lua_State *L)
4346{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004347 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004348 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004349 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004350 int i;
4351 struct sample smp;
4352
4353 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004354 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004355
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004356 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004357 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004358
Thierry FOURNIERca988662015-12-20 18:43:03 +01004359 /* Check execution authorization. */
4360 if (f->use & SMP_USE_HTTP_ANY &&
4361 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4362 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4363 "is not available in Lua services", f->kw);
4364 WILL_LJMP(lua_error(L));
4365 }
4366
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004367 /* Get extra arguments. */
4368 for (i = 0; i < lua_gettop(L) - 1; i++) {
4369 if (i >= ARGM_NBARGS)
4370 break;
4371 hlua_lua2arg(L, i + 2, &args[i]);
4372 }
4373 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004374 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004375
4376 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004377 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004378
4379 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004380 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004381 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004382 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004383 }
4384
4385 /* Initialise the sample. */
4386 memset(&smp, 0, sizeof(smp));
4387
4388 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004389 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004390 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004391 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004392 lua_pushstring(L, "");
4393 else
4394 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004395 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004396 }
4397
4398 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004399 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004400 hlua_smp2lua_str(L, &smp);
4401 else
4402 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004403
4404 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004405 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004406 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004407
4408 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004409 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004410 WILL_LJMP(lua_error(L));
4411 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004412}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004413
4414/*
4415 *
4416 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004417 * Class Converters
4418 *
4419 *
4420 */
4421
4422/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004423 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004424 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004425__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004426{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004427 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004428}
4429
4430/* This function creates and push in the stack a Converters object
4431 * according with a current TXN.
4432 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004433static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004434{
Willy Tarreau7073c472015-04-06 11:15:40 +02004435 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004436
4437 /* Check stack size. */
4438 if (!lua_checkstack(L, 3))
4439 return 0;
4440
4441 /* Create the object: obj[0] = userdata.
4442 * Note that the base of the Converters object is the
4443 * same than the TXN object.
4444 */
4445 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004446 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004447 lua_rawseti(L, -2, 0);
4448
Willy Tarreau7073c472015-04-06 11:15:40 +02004449 hsmp->s = txn->s;
4450 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004451 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004452 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004453
Willy Tarreau87b09662015-04-03 00:22:06 +02004454 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004455 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4456 lua_setmetatable(L, -2);
4457
4458 return 1;
4459}
4460
4461/* This function is an LUA binding. It is called with each converter.
4462 * It uses closure argument to store the associated converter. It
4463 * returns only one argument or throws an error. An error is thrown
4464 * only if an error is encountered during the argument parsing. If
4465 * the converter function function fails, nil is returned.
4466 */
4467__LJMP static int hlua_run_sample_conv(lua_State *L)
4468{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004469 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004470 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004471 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004472 int i;
4473 struct sample smp;
4474
4475 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004476 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004477
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004478 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004479 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004480
4481 /* Get extra arguments. */
4482 for (i = 0; i < lua_gettop(L) - 2; i++) {
4483 if (i >= ARGM_NBARGS)
4484 break;
4485 hlua_lua2arg(L, i + 3, &args[i]);
4486 }
4487 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004488 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004489
4490 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004491 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004492
4493 /* Run the special args checker. */
4494 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4495 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004496 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004497 }
4498
4499 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004500 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004501 if (!hlua_lua2smp(L, 2, &smp)) {
4502 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004503 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004504 }
4505
Willy Tarreau1777ea62016-03-10 16:15:46 +01004506 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4507
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004508 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004509 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004510 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004511 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004512 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004513 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004514 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4515 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004516 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004517 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004518 }
4519
4520 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004521 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004522 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004523 lua_pushstring(L, "");
4524 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004525 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004526 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004527 }
4528
4529 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004530 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004531 hlua_smp2lua_str(L, &smp);
4532 else
4533 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004534 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004535 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004536 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004537
4538 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004539 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004540 WILL_LJMP(lua_error(L));
4541 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004542}
4543
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544/*
4545 *
4546 *
4547 * Class AppletTCP
4548 *
4549 *
4550 */
4551
4552/* Returns a struct hlua_txn if the stack entry "ud" is
4553 * a class stream, otherwise it throws an error.
4554 */
4555__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4556{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004557 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004558}
4559
4560/* This function creates and push in the stack an Applet object
4561 * according with a current TXN.
4562 */
4563static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4564{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004565 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004566 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004567 struct proxy *p;
4568
4569 ALREADY_CHECKED(s);
4570 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004571
4572 /* Check stack size. */
4573 if (!lua_checkstack(L, 3))
4574 return 0;
4575
4576 /* Create the object: obj[0] = userdata.
4577 * Note that the base of the Converters object is the
4578 * same than the TXN object.
4579 */
4580 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004581 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004582 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004583 luactx->appctx = ctx;
4584 luactx->htxn.s = s;
4585 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004586
4587 /* Create the "f" field that contains a list of fetches. */
4588 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004589 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004590 return 0;
4591 lua_settable(L, -3);
4592
4593 /* Create the "sf" field that contains a list of stringsafe fetches. */
4594 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004595 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004596 return 0;
4597 lua_settable(L, -3);
4598
4599 /* Create the "c" field that contains a list of converters. */
4600 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004601 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602 return 0;
4603 lua_settable(L, -3);
4604
4605 /* Create the "sc" field that contains a list of stringsafe converters. */
4606 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004607 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004608 return 0;
4609 lua_settable(L, -3);
4610
4611 /* Pop a class stream metatable and affect it to the table. */
4612 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4613 lua_setmetatable(L, -2);
4614
4615 return 1;
4616}
4617
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004618__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4619{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004620 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004621 struct stream *s;
4622 const char *name;
4623 size_t len;
4624 struct sample smp;
4625
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004626 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4627 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004628
4629 /* It is useles to retrieve the stream, but this function
4630 * runs only in a stream context.
4631 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004632 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004633 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004634 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004635
4636 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004637 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004638 hlua_lua2smp(L, 3, &smp);
4639
4640 /* Store the sample in a variable. */
4641 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004642
4643 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4644 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4645 else
4646 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4647
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004648 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004649}
4650
4651__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4652{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004653 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004654 struct stream *s;
4655 const char *name;
4656 size_t len;
4657 struct sample smp;
4658
4659 MAY_LJMP(check_args(L, 2, "unset_var"));
4660
4661 /* It is useles to retrieve the stream, but this function
4662 * runs only in a stream context.
4663 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004664 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004665 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004666 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004667
4668 /* Unset the variable. */
4669 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004670 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4671 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004672}
4673
4674__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4675{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004676 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004677 struct stream *s;
4678 const char *name;
4679 size_t len;
4680 struct sample smp;
4681
4682 MAY_LJMP(check_args(L, 2, "get_var"));
4683
4684 /* It is useles to retrieve the stream, but this function
4685 * runs only in a stream context.
4686 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004687 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004688 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004689 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004690
4691 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004692 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004693 lua_pushnil(L);
4694 return 1;
4695 }
4696
4697 return hlua_smp2lua(L, &smp);
4698}
4699
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004700__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4701{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004702 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4703 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004704 struct hlua *hlua;
4705
4706 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004707 if (!s->hlua)
4708 return 0;
4709 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004710
4711 MAY_LJMP(check_args(L, 2, "set_priv"));
4712
4713 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004714 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004715
4716 /* Get and store new value. */
4717 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4718 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4719
4720 return 0;
4721}
4722
4723__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4724{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004725 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4726 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004727 struct hlua *hlua;
4728
4729 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004730 if (!s->hlua) {
4731 lua_pushnil(L);
4732 return 1;
4733 }
4734 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004735
4736 /* Push configuration index in the stack. */
4737 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4738
4739 return 1;
4740}
4741
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004742/* If expected data not yet available, it returns a yield. This function
4743 * consumes the data in the buffer. It returns a string containing the
4744 * data. This string can be empty.
4745 */
4746__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4747{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004748 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004749 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004750 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004751 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004752 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004753 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004754 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004755
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004756 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004757 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004758
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004759 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004760 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004761 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004762 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004763 }
4764
4765 /* End of data: commit the total strings and return. */
4766 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004768 return 1;
4769 }
4770
4771 /* Ensure that the block 2 length is usable. */
4772 if (ret == 1)
4773 len2 = 0;
4774
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004775 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004776 luaL_addlstring(&luactx->b, blk1, len1);
4777 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004778
4779 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004780 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004781 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004782 return 1;
4783}
4784
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004785/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004786__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4787{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004788 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004789
4790 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004791 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004792
4793 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4794}
4795
4796/* If expected data not yet available, it returns a yield. This function
4797 * consumes the data in the buffer. It returns a string containing the
4798 * data. This string can be empty.
4799 */
4800__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4801{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004803 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004804 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004805 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004806 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004807 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004808 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004809 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004810
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004811 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004812 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004813
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004814 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004815 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004816 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004817 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004818 }
4819
4820 /* End of data: commit the total strings and return. */
4821 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004822 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004823 return 1;
4824 }
4825
4826 /* Ensure that the block 2 length is usable. */
4827 if (ret == 1)
4828 len2 = 0;
4829
4830 if (len == -1) {
4831
4832 /* If len == -1, catenate all the data avalaile and
4833 * yield because we want to get all the data until
4834 * the end of data stream.
4835 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004836 luaL_addlstring(&luactx->b, blk1, len1);
4837 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004838 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004839 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004840 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004841
4842 } else {
4843
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004844 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004845 if (len1 > len)
4846 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004847 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004848 len -= len1;
4849
4850 /* Copy the second block. */
4851 if (len2 > len)
4852 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004853 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004854 len -= len2;
4855
4856 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004857 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004858
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004859 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004860 if (len > 0) {
4861 lua_pushinteger(L, len);
4862 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004863 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004864 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004865 }
4866
4867 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004868 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004869 return 1;
4870 }
4871
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004872 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004873 hlua_pusherror(L, "Lua: internal error");
4874 WILL_LJMP(lua_error(L));
4875 return 0;
4876}
4877
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004878/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004879__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4880{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004881 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004882 int len = -1;
4883
4884 if (lua_gettop(L) > 2)
4885 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4886 if (lua_gettop(L) >= 2) {
4887 len = MAY_LJMP(luaL_checkinteger(L, 2));
4888 lua_pop(L, 1);
4889 }
4890
4891 /* Confirm or set the required length */
4892 lua_pushinteger(L, len);
4893
4894 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004895 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004896
4897 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4898}
4899
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004900/* Append data in the output side of the buffer. This data is immediately
4901 * sent. The function returns the amount of data written. If the buffer
4902 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004903 * if the channel is closed.
4904 */
4905__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4906{
4907 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004908 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004909 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4910 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004911 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004912 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004913 int max;
4914
4915 /* Get the max amount of data which can write as input in the channel. */
4916 max = channel_recv_max(chn);
4917 if (max > (len - l))
4918 max = len - l;
4919
4920 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004921 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004922
4923 /* update counters. */
4924 l += max;
4925 lua_pop(L, 1);
4926 lua_pushinteger(L, l);
4927
4928 /* If some data is not send, declares the situation to the
4929 * applet, and returns a yield.
4930 */
4931 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004932 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004933 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004934 }
4935
4936 return 1;
4937}
4938
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004939/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004940 * yield the LUA process, and resume it without checking the
4941 * input arguments.
4942 */
4943__LJMP static int hlua_applet_tcp_send(lua_State *L)
4944{
4945 MAY_LJMP(check_args(L, 2, "send"));
4946 lua_pushinteger(L, 0);
4947
4948 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4949}
4950
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004951/*
4952 *
4953 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004954 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004955 *
4956 *
4957 */
4958
4959/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004960 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004961 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004962__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004963{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004964 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004965}
4966
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004967/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004968 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004969 * It relies on the caller to have already reserved the room in ctx->svcctx
4970 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004971 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004972static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004973{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004974 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004976 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004977 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004978 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004979 struct htx *htx;
4980 struct htx_blk *blk;
4981 struct htx_sl *sl;
4982 struct ist path;
4983 unsigned long long len = 0;
4984 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004985 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004986
4987 /* Check stack size. */
4988 if (!lua_checkstack(L, 3))
4989 return 0;
4990
4991 /* Create the object: obj[0] = userdata.
4992 * Note that the base of the Converters object is the
4993 * same than the TXN object.
4994 */
4995 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004996 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004997 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004998 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004999 http_ctx->status = 200; /* Default status code returned. */
5000 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005001 luactx->htxn.s = s;
5002 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005003
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005004 /* Create the "f" field that contains a list of fetches. */
5005 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005006 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005007 return 0;
5008 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005009
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005010 /* Create the "sf" field that contains a list of stringsafe fetches. */
5011 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005012 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005013 return 0;
5014 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005016 /* Create the "c" field that contains a list of converters. */
5017 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005019 return 0;
5020 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005021
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005022 /* Create the "sc" field that contains a list of stringsafe converters. */
5023 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005024 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005025 return 0;
5026 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005027
Christopher Fauleta2097962019-07-15 16:25:33 +02005028 htx = htxbuf(&s->req.buf);
5029 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005030 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005031 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005032
Christopher Fauleta2097962019-07-15 16:25:33 +02005033 /* Stores the request method. */
5034 lua_pushstring(L, "method");
5035 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5036 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037
Christopher Fauleta2097962019-07-15 16:25:33 +02005038 /* Stores the http version. */
5039 lua_pushstring(L, "version");
5040 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5041 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005042
Christopher Fauleta2097962019-07-15 16:25:33 +02005043 /* creates an array of headers. hlua_http_get_headers() crates and push
5044 * the array on the top of the stack.
5045 */
5046 lua_pushstring(L, "headers");
5047 htxn.s = s;
5048 htxn.p = px;
5049 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005050 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005051 return 0;
5052 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005053
Amaury Denoyellec453f952021-07-06 11:40:12 +02005054 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5055 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005056 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005057 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005058
Christopher Fauleta2097962019-07-15 16:25:33 +02005059 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005060 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005061 q = p;
5062 while (q < end && *q != '?')
5063 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005064
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005065 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005066 lua_pushstring(L, "path");
5067 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005068 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005069
Christopher Fauleta2097962019-07-15 16:25:33 +02005070 /* Stores the query string. */
5071 lua_pushstring(L, "qs");
5072 if (*q == '?')
5073 q++;
5074 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005075 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005076 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005077
Christopher Fauleta2097962019-07-15 16:25:33 +02005078 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5079 struct htx_blk *blk = htx_get_blk(htx, pos);
5080 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005081
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005082 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005083 break;
5084 if (type == HTX_BLK_DATA)
5085 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005086 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005087 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005088 len += htx->extra;
5089
5090 /* Stores the request path. */
5091 lua_pushstring(L, "length");
5092 lua_pushinteger(L, len);
5093 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005094
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005095 /* Create an empty array of HTTP request headers. */
5096 lua_pushstring(L, "response");
5097 lua_newtable(L);
5098 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005099
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005100 /* Pop a class stream metatable and affect it to the table. */
5101 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5102 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005103
5104 return 1;
5105}
5106
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005107__LJMP static int hlua_applet_http_set_var(lua_State *L)
5108{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005109 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005110 struct stream *s;
5111 const char *name;
5112 size_t len;
5113 struct sample smp;
5114
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005115 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5116 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005117
5118 /* It is useles to retrieve the stream, but this function
5119 * runs only in a stream context.
5120 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005121 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005122 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005123 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005124
5125 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005126 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005127 hlua_lua2smp(L, 3, &smp);
5128
5129 /* Store the sample in a variable. */
5130 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005131
5132 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5133 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5134 else
5135 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5136
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005137 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005138}
5139
5140__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5141{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005142 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005143 struct stream *s;
5144 const char *name;
5145 size_t len;
5146 struct sample smp;
5147
5148 MAY_LJMP(check_args(L, 2, "unset_var"));
5149
5150 /* It is useles to retrieve the stream, but this function
5151 * runs only in a stream context.
5152 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005153 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005154 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005155 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005156
5157 /* Unset the variable. */
5158 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005159 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5160 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005161}
5162
5163__LJMP static int hlua_applet_http_get_var(lua_State *L)
5164{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005165 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005166 struct stream *s;
5167 const char *name;
5168 size_t len;
5169 struct sample smp;
5170
5171 MAY_LJMP(check_args(L, 2, "get_var"));
5172
5173 /* It is useles to retrieve the stream, but this function
5174 * runs only in a stream context.
5175 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005176 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005177 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005178 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005179
5180 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005181 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005182 lua_pushnil(L);
5183 return 1;
5184 }
5185
5186 return hlua_smp2lua(L, &smp);
5187}
5188
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005189__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5190{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005191 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5192 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005193 struct hlua *hlua;
5194
5195 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005196 if (!s->hlua)
5197 return 0;
5198 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005199
5200 MAY_LJMP(check_args(L, 2, "set_priv"));
5201
5202 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005203 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005204
5205 /* Get and store new value. */
5206 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5207 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5208
5209 return 0;
5210}
5211
5212__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5213{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005214 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5215 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005216 struct hlua *hlua;
5217
5218 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005219 if (!s->hlua) {
5220 lua_pushnil(L);
5221 return 1;
5222 }
5223 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005224
5225 /* Push configuration index in the stack. */
5226 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5227
5228 return 1;
5229}
5230
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005231/* If expected data not yet available, it returns a yield. This function
5232 * consumes the data in the buffer. It returns a string containing the
5233 * data. This string can be empty.
5234 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005235__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005236{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005237 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005238 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005239 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005240 struct htx *htx;
5241 struct htx_blk *blk;
5242 size_t count;
5243 int stop = 0;
5244
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005245 htx = htx_from_buf(&req->buf);
5246 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005247 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005248
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005249 while (count && !stop && blk) {
5250 enum htx_blk_type type = htx_get_blk_type(blk);
5251 uint32_t sz = htx_get_blksz(blk);
5252 struct ist v;
5253 uint32_t vlen;
5254 char *nl;
5255
5256 vlen = sz;
5257 if (vlen > count) {
5258 if (type != HTX_BLK_DATA)
5259 break;
5260 vlen = count;
5261 }
5262
5263 switch (type) {
5264 case HTX_BLK_UNUSED:
5265 break;
5266
5267 case HTX_BLK_DATA:
5268 v = htx_get_blk_value(htx, blk);
5269 v.len = vlen;
5270 nl = istchr(v, '\n');
5271 if (nl != NULL) {
5272 stop = 1;
5273 vlen = nl - v.ptr + 1;
5274 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005275 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005276 break;
5277
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005278 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005279 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005280 stop = 1;
5281 break;
5282
5283 default:
5284 break;
5285 }
5286
Willy Tarreau84240042022-02-28 16:51:23 +01005287 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005288 count -= vlen;
5289 if (sz == vlen)
5290 blk = htx_remove_blk(htx, blk);
5291 else {
5292 htx_cut_data_blk(htx, blk, vlen);
5293 break;
5294 }
5295 }
5296
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005297 /* The message was fully consumed and no more data are expected
5298 * (EOM flag set).
5299 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005300 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005301 stop = 1;
5302
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005303 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005304 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005305 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005306 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005307 }
5308
5309 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005310 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005311 return 1;
5312}
5313
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005314
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005315/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005316__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005317{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005318 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005319
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005320 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005321 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005322
Christopher Fauleta2097962019-07-15 16:25:33 +02005323 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005324}
5325
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005326/* If expected data not yet available, it returns a yield. This function
5327 * consumes the data in the buffer. It returns a string containing the
5328 * data. This string can be empty.
5329 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005330__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005331{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005332 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005333 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005334 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005335 struct htx *htx;
5336 struct htx_blk *blk;
5337 size_t count;
5338 int len;
5339
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005340 htx = htx_from_buf(&req->buf);
5341 len = MAY_LJMP(luaL_checkinteger(L, 2));
5342 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005343 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005344 while (count && len && blk) {
5345 enum htx_blk_type type = htx_get_blk_type(blk);
5346 uint32_t sz = htx_get_blksz(blk);
5347 struct ist v;
5348 uint32_t vlen;
5349
5350 vlen = sz;
5351 if (len > 0 && vlen > len)
5352 vlen = len;
5353 if (vlen > count) {
5354 if (type != HTX_BLK_DATA)
5355 break;
5356 vlen = count;
5357 }
5358
5359 switch (type) {
5360 case HTX_BLK_UNUSED:
5361 break;
5362
5363 case HTX_BLK_DATA:
5364 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005365 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005366 break;
5367
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005368 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005369 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005370 len = 0;
5371 break;
5372
5373 default:
5374 break;
5375 }
5376
Willy Tarreau84240042022-02-28 16:51:23 +01005377 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005378 count -= vlen;
5379 if (len > 0)
5380 len -= vlen;
5381 if (sz == vlen)
5382 blk = htx_remove_blk(htx, blk);
5383 else {
5384 htx_cut_data_blk(htx, blk, vlen);
5385 break;
5386 }
5387 }
5388
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005389 /* The message was fully consumed and no more data are expected
5390 * (EOM flag set).
5391 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005392 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005393 len = 0;
5394
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005395 htx_to_buf(htx, &req->buf);
5396
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005397 /* If we are no other data available, yield waiting for new data. */
5398 if (len) {
5399 if (len > 0) {
5400 lua_pushinteger(L, len);
5401 lua_replace(L, 2);
5402 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005403 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005404 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005405 }
5406
5407 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005408 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005409 return 1;
5410}
5411
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005412/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005413__LJMP static int hlua_applet_http_recv(lua_State *L)
5414{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005415 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005416 int len = -1;
5417
5418 /* Check arguments. */
5419 if (lua_gettop(L) > 2)
5420 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5421 if (lua_gettop(L) >= 2) {
5422 len = MAY_LJMP(luaL_checkinteger(L, 2));
5423 lua_pop(L, 1);
5424 }
5425
Christopher Fauleta2097962019-07-15 16:25:33 +02005426 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005427
Christopher Fauleta2097962019-07-15 16:25:33 +02005428 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005429 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005430
Christopher Fauleta2097962019-07-15 16:25:33 +02005431 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005432}
5433
5434/* Append data in the output side of the buffer. This data is immediately
5435 * sent. The function returns the amount of data written. If the buffer
5436 * cannot contain the data, the function yields. The function returns -1
5437 * if the channel is closed.
5438 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005439__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005440{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005441 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005442 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005443 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444 struct htx *htx = htx_from_buf(&res->buf);
5445 const char *data;
5446 size_t len;
5447 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5448 int max;
5449
Christopher Faulet9060fc02019-07-03 11:39:30 +02005450 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005451 if (!max)
5452 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005453
5454 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5455
5456 /* Get the max amount of data which can write as input in the channel. */
5457 if (max > (len - l))
5458 max = len - l;
5459
5460 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005461 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005462 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005463
5464 /* update counters. */
5465 l += max;
5466 lua_pop(L, 1);
5467 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005468
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469 /* If some data is not send, declares the situation to the
5470 * applet, and returns a yield.
5471 */
5472 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005473 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005474 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005475 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005476 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005477 }
5478
Christopher Fauleta2097962019-07-15 16:25:33 +02005479 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005480 return 1;
5481}
5482
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005483/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005484 * yield the LUA process, and resume it without checking the
5485 * input arguments.
5486 */
5487__LJMP static int hlua_applet_http_send(lua_State *L)
5488{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005489 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005490 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005491
5492 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005493 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005494 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5495 WILL_LJMP(lua_error(L));
5496 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005497
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005498 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005499 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005500
Christopher Fauleta2097962019-07-15 16:25:33 +02005501 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005502}
5503
5504__LJMP static int hlua_applet_http_addheader(lua_State *L)
5505{
5506 const char *name;
5507 int ret;
5508
5509 MAY_LJMP(hlua_checkapplet_http(L, 1));
5510 name = MAY_LJMP(luaL_checkstring(L, 2));
5511 MAY_LJMP(luaL_checkstring(L, 3));
5512
5513 /* Push in the stack the "response" entry. */
5514 ret = lua_getfield(L, 1, "response");
5515 if (ret != LUA_TTABLE) {
5516 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5517 "is expected as an array. %s found", lua_typename(L, ret));
5518 WILL_LJMP(lua_error(L));
5519 }
5520
5521 /* check if the header is already registered if it is not
5522 * the case, register it.
5523 */
5524 ret = lua_getfield(L, -1, name);
5525 if (ret == LUA_TNIL) {
5526
5527 /* Entry not found. */
5528 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5529
5530 /* Insert the new header name in the array in the top of the stack.
5531 * It left the new array in the top of the stack.
5532 */
5533 lua_newtable(L);
5534 lua_pushvalue(L, 2);
5535 lua_pushvalue(L, -2);
5536 lua_settable(L, -4);
5537
5538 } else if (ret != LUA_TTABLE) {
5539
5540 /* corruption error. */
5541 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5542 "is expected as an array. %s found", name, lua_typename(L, ret));
5543 WILL_LJMP(lua_error(L));
5544 }
5545
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005546 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005547 * the header value as new entry.
5548 */
5549 lua_pushvalue(L, 3);
5550 ret = lua_rawlen(L, -2);
5551 lua_rawseti(L, -2, ret + 1);
5552 lua_pushboolean(L, 1);
5553 return 1;
5554}
5555
5556__LJMP static int hlua_applet_http_status(lua_State *L)
5557{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005558 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005559 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005560 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005561 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005562
5563 if (status < 100 || status > 599) {
5564 lua_pushboolean(L, 0);
5565 return 1;
5566 }
5567
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005568 http_ctx->status = status;
5569 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005570 lua_pushboolean(L, 1);
5571 return 1;
5572}
5573
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005574
Christopher Fauleta2097962019-07-15 16:25:33 +02005575__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005576{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005577 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005578 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005579 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005580 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005581 struct htx *htx;
5582 struct htx_sl *sl;
5583 struct h1m h1m;
5584 const char *status, *reason;
5585 const char *name, *value;
5586 size_t nlen, vlen;
5587 unsigned int flags;
5588
5589 /* Send the message at once. */
5590 htx = htx_from_buf(&res->buf);
5591 h1m_init_res(&h1m);
5592
5593 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005594 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5595 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005596 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005597 reason = http_get_reason(http_ctx->status);
5598 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005599 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5600 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5601 }
5602 else {
5603 flags = HTX_SL_F_IS_RESP;
5604 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5605 }
5606 if (!sl) {
5607 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005608 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005609 WILL_LJMP(lua_error(L));
5610 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005611 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005612
5613 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005614 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5615 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005616 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005617 WILL_LJMP(lua_error(L));
5618 }
5619
5620 /* Browse the list of headers. */
5621 lua_pushnil(L);
5622 while(lua_next(L, -2) != 0) {
5623 /* We expect a string as -2. */
5624 if (lua_type(L, -2) != LUA_TSTRING) {
5625 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005626 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005627 lua_typename(L, lua_type(L, -2)));
5628 WILL_LJMP(lua_error(L));
5629 }
5630 name = lua_tolstring(L, -2, &nlen);
5631
5632 /* We expect an array as -1. */
5633 if (lua_type(L, -1) != LUA_TTABLE) {
5634 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 +02005635 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005636 name,
5637 lua_typename(L, lua_type(L, -1)));
5638 WILL_LJMP(lua_error(L));
5639 }
5640
5641 /* Browse the table who is on the top of the stack. */
5642 lua_pushnil(L);
5643 while(lua_next(L, -2) != 0) {
5644 int id;
5645
5646 /* We expect a number as -2. */
5647 if (lua_type(L, -2) != LUA_TNUMBER) {
5648 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 +02005649 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005650 name,
5651 lua_typename(L, lua_type(L, -2)));
5652 WILL_LJMP(lua_error(L));
5653 }
5654 id = lua_tointeger(L, -2);
5655
5656 /* We expect a string as -2. */
5657 if (lua_type(L, -1) != LUA_TSTRING) {
5658 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 +02005659 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005660 name, id,
5661 lua_typename(L, lua_type(L, -1)));
5662 WILL_LJMP(lua_error(L));
5663 }
5664 value = lua_tolstring(L, -1, &vlen);
5665
5666 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005667 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5668 int ret;
5669
5670 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5671 if (ret < 0) {
5672 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5673 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5674 name);
5675 WILL_LJMP(lua_error(L));
5676 }
5677 else if (ret == 0)
5678 goto next; /* Skip it */
5679 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005680 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5681 struct ist v = ist2(value, vlen);
5682 int ret;
5683
5684 ret = h1_parse_cont_len_header(&h1m, &v);
5685 if (ret < 0) {
5686 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005687 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005688 name);
5689 WILL_LJMP(lua_error(L));
5690 }
5691 else if (ret == 0)
5692 goto next; /* Skip it */
5693 }
5694
5695 /* Add a new header */
5696 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5697 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005698 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005699 name);
5700 WILL_LJMP(lua_error(L));
5701 }
5702 next:
5703 /* Remove the array from the stack, and get next element with a remaining string. */
5704 lua_pop(L, 1);
5705 }
5706
5707 /* Remove the array from the stack, and get next element with a remaining string. */
5708 lua_pop(L, 1);
5709 }
5710
5711 if (h1m.flags & H1_MF_CHNK)
5712 h1m.flags &= ~H1_MF_CLEN;
5713 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5714 h1m.flags |= H1_MF_XFER_LEN;
5715
5716 /* Uset HTX start-line flags */
5717 if (h1m.flags & H1_MF_XFER_ENC)
5718 flags |= HTX_SL_F_XFER_ENC;
5719 if (h1m.flags & H1_MF_XFER_LEN) {
5720 flags |= HTX_SL_F_XFER_LEN;
5721 if (h1m.flags & H1_MF_CHNK)
5722 flags |= HTX_SL_F_CHNK;
5723 else if (h1m.flags & H1_MF_CLEN)
5724 flags |= HTX_SL_F_CLEN;
5725 if (h1m.body_len == 0)
5726 flags |= HTX_SL_F_BODYLESS;
5727 }
5728 sl->flags |= flags;
5729
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005730 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005731 * and the status code implies the presence of a message body, we must
5732 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005733 * for the keepalive compliance. If the applet announces a transfer-encoding
5734 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005735 */
5736 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005737 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005738 /* Add a new header */
5739 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5740 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5741 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005742 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005743 WILL_LJMP(lua_error(L));
5744 }
5745 }
5746
5747 /* Finalize headers. */
5748 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5749 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005750 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005751 WILL_LJMP(lua_error(L));
5752 }
5753
5754 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5755 b_reset(&res->buf);
5756 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5757 WILL_LJMP(lua_error(L));
5758 }
5759
5760 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005761 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005762
5763 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005764 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005765 return 0;
5766
5767}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005768/* We will build the status line and the headers of the HTTP response.
5769 * We will try send at once if its not possible, we give back the hand
5770 * waiting for more room.
5771 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005772__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005773{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005774 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005775 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005776 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005777
5778 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005779 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005780 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005781 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005782 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005783}
5784
5785
Christopher Fauleta2097962019-07-15 16:25:33 +02005786__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005787{
Christopher Fauleta2097962019-07-15 16:25:33 +02005788 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005789}
5790
Christopher Fauleta2097962019-07-15 16:25:33 +02005791/*
5792 *
5793 *
5794 * Class HTTP
5795 *
5796 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005797 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005798
5799/* Returns a struct hlua_txn if the stack entry "ud" is
5800 * a class stream, otherwise it throws an error.
5801 */
5802__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005803{
Christopher Fauleta2097962019-07-15 16:25:33 +02005804 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5805}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005806
Christopher Fauleta2097962019-07-15 16:25:33 +02005807/* This function creates and push in the stack a HTTP object
5808 * according with a current TXN.
5809 */
5810static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5811{
5812 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005813
Christopher Fauleta2097962019-07-15 16:25:33 +02005814 /* Check stack size. */
5815 if (!lua_checkstack(L, 3))
5816 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005817
Christopher Fauleta2097962019-07-15 16:25:33 +02005818 /* Create the object: obj[0] = userdata.
5819 * Note that the base of the Converters object is the
5820 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005821 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005822 lua_newtable(L);
5823 htxn = lua_newuserdata(L, sizeof(*htxn));
5824 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005825
5826 htxn->s = txn->s;
5827 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005828 htxn->dir = txn->dir;
5829 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005830
5831 /* Pop a class stream metatable and affect it to the table. */
5832 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5833 lua_setmetatable(L, -2);
5834
5835 return 1;
5836}
5837
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005838/* This function creates and returns an array containing the status-line
5839 * elements. This function does not fails.
5840 */
5841__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5842{
5843 /* Create the table. */
5844 lua_newtable(L);
5845
5846 if (sl->flags & HTX_SL_F_IS_RESP) {
5847 lua_pushstring(L, "version");
5848 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5849 lua_settable(L, -3);
5850 lua_pushstring(L, "code");
5851 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5852 lua_settable(L, -3);
5853 lua_pushstring(L, "reason");
5854 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5855 lua_settable(L, -3);
5856 }
5857 else {
5858 lua_pushstring(L, "method");
5859 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5860 lua_settable(L, -3);
5861 lua_pushstring(L, "uri");
5862 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5863 lua_settable(L, -3);
5864 lua_pushstring(L, "version");
5865 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5866 lua_settable(L, -3);
5867 }
5868 return 1;
5869}
5870
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005871/* This function creates ans returns an array of HTTP headers.
5872 * This function does not fails. It is used as wrapper with the
5873 * 2 following functions.
5874 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005875__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005876{
Christopher Fauleta2097962019-07-15 16:25:33 +02005877 struct htx *htx;
5878 int32_t pos;
5879
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005880 /* Create the table. */
5881 lua_newtable(L);
5882
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005883
Christopher Fauleta2097962019-07-15 16:25:33 +02005884 htx = htxbuf(&msg->chn->buf);
5885 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5886 struct htx_blk *blk = htx_get_blk(htx, pos);
5887 enum htx_blk_type type = htx_get_blk_type(blk);
5888 struct ist n, v;
5889 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005890
Christopher Fauleta2097962019-07-15 16:25:33 +02005891 if (type == HTX_BLK_HDR) {
5892 n = htx_get_blk_name(htx,blk);
5893 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005894 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005895 else if (type == HTX_BLK_EOH)
5896 break;
5897 else
5898 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005899
Christopher Fauleta2097962019-07-15 16:25:33 +02005900 /* Check for existing entry:
5901 * assume that the table is on the top of the stack, and
5902 * push the key in the stack, the function lua_gettable()
5903 * perform the lookup.
5904 */
5905 lua_pushlstring(L, n.ptr, n.len);
5906 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005907
Christopher Fauleta2097962019-07-15 16:25:33 +02005908 switch (lua_type(L, -1)) {
5909 case LUA_TNIL:
5910 /* Table not found, create it. */
5911 lua_pop(L, 1); /* remove the nil value. */
5912 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5913 lua_newtable(L); /* create and push empty table. */
5914 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5915 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5916 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005917 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005918
Christopher Fauleta2097962019-07-15 16:25:33 +02005919 case LUA_TTABLE:
5920 /* Entry found: push the value in the table. */
5921 len = lua_rawlen(L, -1);
5922 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5923 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5924 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5925 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005926
Christopher Fauleta2097962019-07-15 16:25:33 +02005927 default:
5928 /* Other cases are errors. */
5929 hlua_pusherror(L, "internal error during the parsing of headers.");
5930 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005931 }
5932 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005933 return 1;
5934}
5935
5936__LJMP static int hlua_http_req_get_headers(lua_State *L)
5937{
5938 struct hlua_txn *htxn;
5939
5940 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5941 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5942
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005943 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005944 WILL_LJMP(lua_error(L));
5945
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005946 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005947}
5948
5949__LJMP static int hlua_http_res_get_headers(lua_State *L)
5950{
5951 struct hlua_txn *htxn;
5952
5953 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5954 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5955
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005956 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005957 WILL_LJMP(lua_error(L));
5958
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005959 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005960}
5961
5962/* This function replace full header, or just a value in
5963 * the request or in the response. It is a wrapper fir the
5964 * 4 following functions.
5965 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005966__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005967{
5968 size_t name_len;
5969 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5970 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5971 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005972 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005973 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005974
Dragan Dosen26743032019-04-30 15:54:36 +02005975 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005976 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5977
Christopher Fauleta2097962019-07-15 16:25:33 +02005978 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005979 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005980 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005981 return 0;
5982}
5983
5984__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5985{
5986 struct hlua_txn *htxn;
5987
5988 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5989 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5990
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005991 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005992 WILL_LJMP(lua_error(L));
5993
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005994 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005995}
5996
5997__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5998{
5999 struct hlua_txn *htxn;
6000
6001 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
6002 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6003
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006004 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006005 WILL_LJMP(lua_error(L));
6006
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006007 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006008}
6009
6010__LJMP static int hlua_http_req_rep_val(lua_State *L)
6011{
6012 struct hlua_txn *htxn;
6013
6014 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6015 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6016
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006017 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006018 WILL_LJMP(lua_error(L));
6019
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006020 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006021}
6022
6023__LJMP static int hlua_http_res_rep_val(lua_State *L)
6024{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006025 struct hlua_txn *htxn;
6026
6027 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6028 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6029
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006030 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006031 WILL_LJMP(lua_error(L));
6032
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006033 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006034}
6035
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006036/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006037 * It is a wrapper for the 2 following functions.
6038 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006039__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006040{
6041 size_t len;
6042 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006043 struct htx *htx = htxbuf(&msg->chn->buf);
6044 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006045
Christopher Fauleta2097962019-07-15 16:25:33 +02006046 ctx.blk = NULL;
6047 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6048 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006049 return 0;
6050}
6051
6052__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6053{
6054 struct hlua_txn *htxn;
6055
6056 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6057 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6058
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006059 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006060 WILL_LJMP(lua_error(L));
6061
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006062 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006063}
6064
6065__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6066{
6067 struct hlua_txn *htxn;
6068
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006069 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006070 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6071
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006072 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006073 WILL_LJMP(lua_error(L));
6074
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006075 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006076}
6077
6078/* This function adds an header. It is a wrapper used by
6079 * the 2 following functions.
6080 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006081__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006082{
6083 size_t name_len;
6084 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6085 size_t value_len;
6086 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006087 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006088
Christopher Fauleta2097962019-07-15 16:25:33 +02006089 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6090 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006091 return 0;
6092}
6093
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006094__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6095{
6096 struct hlua_txn *htxn;
6097
6098 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6099 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6100
6101 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6102 WILL_LJMP(lua_error(L));
6103
6104 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6105}
6106
6107__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6108{
6109 struct hlua_txn *htxn;
6110
6111 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6112 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6113
6114 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6115 WILL_LJMP(lua_error(L));
6116
6117 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6118}
6119
6120static int hlua_http_req_set_hdr(lua_State *L)
6121{
6122 struct hlua_txn *htxn;
6123
6124 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6125 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6126
6127 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6128 WILL_LJMP(lua_error(L));
6129
6130 hlua_http_del_hdr(L, &htxn->s->txn->req);
6131 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6132}
6133
6134static int hlua_http_res_set_hdr(lua_State *L)
6135{
6136 struct hlua_txn *htxn;
6137
6138 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6139 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6140
6141 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6142 WILL_LJMP(lua_error(L));
6143
6144 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6145 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6146}
6147
6148/* This function set the method. */
6149static int hlua_http_req_set_meth(lua_State *L)
6150{
6151 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6152 size_t name_len;
6153 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6154
6155 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6156 WILL_LJMP(lua_error(L));
6157
6158 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6159 return 1;
6160}
6161
6162/* This function set the method. */
6163static int hlua_http_req_set_path(lua_State *L)
6164{
6165 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6166 size_t name_len;
6167 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6168
6169 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6170 WILL_LJMP(lua_error(L));
6171
6172 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6173 return 1;
6174}
6175
6176/* This function set the query-string. */
6177static int hlua_http_req_set_query(lua_State *L)
6178{
6179 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6180 size_t name_len;
6181 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6182
6183 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6184 WILL_LJMP(lua_error(L));
6185
6186 /* Check length. */
6187 if (name_len > trash.size - 1) {
6188 lua_pushboolean(L, 0);
6189 return 1;
6190 }
6191
6192 /* Add the mark question as prefix. */
6193 chunk_reset(&trash);
6194 trash.area[trash.data++] = '?';
6195 memcpy(trash.area + trash.data, name, name_len);
6196 trash.data += name_len;
6197
6198 lua_pushboolean(L,
6199 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6200 return 1;
6201}
6202
6203/* This function set the uri. */
6204static int hlua_http_req_set_uri(lua_State *L)
6205{
6206 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6207 size_t name_len;
6208 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6209
6210 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6211 WILL_LJMP(lua_error(L));
6212
6213 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6214 return 1;
6215}
6216
6217/* This function set the response code & optionally reason. */
6218static int hlua_http_res_set_status(lua_State *L)
6219{
6220 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6221 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6222 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6223 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6224
6225 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6226 WILL_LJMP(lua_error(L));
6227
6228 http_res_set_status(code, reason, htxn->s);
6229 return 0;
6230}
6231
6232/*
6233 *
6234 *
6235 * Class HTTPMessage
6236 *
6237 *
6238 */
6239
6240/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6241 * otherwise it throws an error.
6242 */
6243__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6244{
6245 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6246}
6247
6248/* Creates and pushes on the stack a HTTP object according with a current TXN.
6249 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006250static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006251{
6252 /* Check stack size. */
6253 if (!lua_checkstack(L, 3))
6254 return 0;
6255
6256 lua_newtable(L);
6257 lua_pushlightuserdata(L, msg);
6258 lua_rawseti(L, -2, 0);
6259
6260 /* Create the "channel" field that contains the request channel object. */
6261 lua_pushstring(L, "channel");
6262 if (!hlua_channel_new(L, msg->chn))
6263 return 0;
6264 lua_rawset(L, -3);
6265
6266 /* Pop a class stream metatable and affect it to the table. */
6267 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6268 lua_setmetatable(L, -2);
6269
6270 return 1;
6271}
6272
6273/* Helper function returning a filter attached to the HTTP message at the
6274 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006275 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006276 * filled with output and input length respectively.
6277 */
6278static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6279{
6280 struct channel *chn = msg->chn;
6281 struct htx *htx = htxbuf(&chn->buf);
6282 struct filter *filter = NULL;
6283
6284 *offset = co_data(msg->chn);
6285 *len = htx->data - co_data(msg->chn);
6286
6287 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6288 filter = lua_touserdata (L, -1);
6289 if (msg->msg_state >= HTTP_MSG_DATA) {
6290 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6291
6292 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6293 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6294 }
6295 }
6296
6297 lua_pop(L, 1);
6298 return filter;
6299}
6300
6301/* Returns true if the channel attached to the HTTP message is the response
6302 * channel.
6303 */
6304__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6305{
6306 struct http_msg *msg;
6307
6308 MAY_LJMP(check_args(L, 1, "is_resp"));
6309 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6310
6311 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6312 return 1;
6313}
6314
6315/* Returns an array containing the elements status-line of the HTTP message. It relies
6316 * on hlua_http_get_stline().
6317 */
6318__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6319{
6320 struct http_msg *msg;
6321 struct htx *htx;
6322 struct htx_sl *sl;
6323
6324 MAY_LJMP(check_args(L, 1, "get_stline"));
6325 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6326
6327 if (msg->msg_state > HTTP_MSG_BODY)
6328 WILL_LJMP(lua_error(L));
6329
6330 htx = htxbuf(&msg->chn->buf);
6331 sl = http_get_stline(htx);
6332 if (!sl)
6333 return 0;
6334 return hlua_http_get_stline(L, sl);
6335}
6336
6337/* Returns an array containing all headers of the HTTP message. it relies on
6338 * hlua_http_get_headers().
6339 */
6340__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6341{
6342 struct http_msg *msg;
6343
6344 MAY_LJMP(check_args(L, 1, "get_headers"));
6345 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6346
6347 if (msg->msg_state > HTTP_MSG_BODY)
6348 WILL_LJMP(lua_error(L));
6349
6350 return hlua_http_get_headers(L, msg);
6351}
6352
6353/* Deletes all occurrences of an header in the HTTP message matching on its
6354 * name. It relies on hlua_http_del_hdr().
6355 */
6356__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6357{
6358 struct http_msg *msg;
6359
6360 MAY_LJMP(check_args(L, 2, "del_header"));
6361 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6362
6363 if (msg->msg_state > HTTP_MSG_BODY)
6364 WILL_LJMP(lua_error(L));
6365
6366 return hlua_http_del_hdr(L, msg);
6367}
6368
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006369/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006370 * message given its name against a regex and replaces it if it matches. It
6371 * relies on hlua_http_rep_hdr().
6372 */
6373__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6374{
6375 struct http_msg *msg;
6376
6377 MAY_LJMP(check_args(L, 4, "rep_header"));
6378 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6379
6380 if (msg->msg_state > HTTP_MSG_BODY)
6381 WILL_LJMP(lua_error(L));
6382
6383 return hlua_http_rep_hdr(L, msg, 1);
6384}
6385
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006386/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006387 * message given its name against a regex and replaces it if it matches. It
6388 * relies on hlua_http_rep_hdr().
6389 */
6390__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6391{
6392 struct http_msg *msg;
6393
6394 MAY_LJMP(check_args(L, 4, "rep_value"));
6395 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6396
6397 if (msg->msg_state > HTTP_MSG_BODY)
6398 WILL_LJMP(lua_error(L));
6399
6400 return hlua_http_rep_hdr(L, msg, 0);
6401}
6402
6403/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6404__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6405{
6406 struct http_msg *msg;
6407
6408 MAY_LJMP(check_args(L, 3, "add_header"));
6409 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6410
6411 if (msg->msg_state > HTTP_MSG_BODY)
6412 WILL_LJMP(lua_error(L));
6413
6414 return hlua_http_add_hdr(L, msg);
6415}
6416
6417/* Add an header in the HTTP message removing existing headers with the same
6418 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6419 */
6420__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6421{
6422 struct http_msg *msg;
6423
6424 MAY_LJMP(check_args(L, 3, "set_header"));
6425 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6426
6427 if (msg->msg_state > HTTP_MSG_BODY)
6428 WILL_LJMP(lua_error(L));
6429
6430 hlua_http_del_hdr(L, msg);
6431 return hlua_http_add_hdr(L, msg);
6432}
6433
6434/* Rewrites the request method. It relies on http_req_replace_stline(). */
6435__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6436{
6437 struct stream *s;
6438 struct http_msg *msg;
6439 const char *name;
6440 size_t name_len;
6441
6442 MAY_LJMP(check_args(L, 2, "set_method"));
6443 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6444 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6445
6446 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6447 WILL_LJMP(lua_error(L));
6448
6449 s = chn_strm(msg->chn);
6450 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6451 return 1;
6452}
6453
6454/* Rewrites the request path. It relies on http_req_replace_stline(). */
6455__LJMP static int hlua_http_msg_set_path(lua_State *L)
6456{
6457 struct stream *s;
6458 struct http_msg *msg;
6459 const char *name;
6460 size_t name_len;
6461
6462 MAY_LJMP(check_args(L, 2, "set_path"));
6463 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6464 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6465
6466 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6467 WILL_LJMP(lua_error(L));
6468
6469 s = chn_strm(msg->chn);
6470 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6471 return 1;
6472}
6473
6474/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6475__LJMP static int hlua_http_msg_set_query(lua_State *L)
6476{
6477 struct stream *s;
6478 struct http_msg *msg;
6479 const char *name;
6480 size_t name_len;
6481
6482 MAY_LJMP(check_args(L, 2, "set_query"));
6483 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6484 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6485
6486 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6487 WILL_LJMP(lua_error(L));
6488
6489 /* Check length. */
6490 if (name_len > trash.size - 1) {
6491 lua_pushboolean(L, 0);
6492 return 1;
6493 }
6494
6495 /* Add the mark question as prefix. */
6496 chunk_reset(&trash);
6497 trash.area[trash.data++] = '?';
6498 memcpy(trash.area + trash.data, name, name_len);
6499 trash.data += name_len;
6500
6501 s = chn_strm(msg->chn);
6502 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6503 return 1;
6504}
6505
6506/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6507__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6508{
6509 struct stream *s;
6510 struct http_msg *msg;
6511 const char *name;
6512 size_t name_len;
6513
6514 MAY_LJMP(check_args(L, 2, "set_uri"));
6515 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6516 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6517
6518 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6519 WILL_LJMP(lua_error(L));
6520
6521 s = chn_strm(msg->chn);
6522 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6523 return 1;
6524}
6525
6526/* Rewrites the response status code. It relies on http_res_set_status(). */
6527__LJMP static int hlua_http_msg_set_status(lua_State *L)
6528{
6529 struct http_msg *msg;
6530 unsigned int code;
6531 const char *reason;
6532 size_t reason_len;
6533
6534 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6535 code = MAY_LJMP(luaL_checkinteger(L, 2));
6536 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6537
6538 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6539 WILL_LJMP(lua_error(L));
6540
6541 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6542 return 1;
6543}
6544
6545/* Returns true if the HTTP message is full. */
6546__LJMP static int hlua_http_msg_is_full(lua_State *L)
6547{
6548 struct http_msg *msg;
6549
6550 MAY_LJMP(check_args(L, 1, "is_full"));
6551 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6552 lua_pushboolean(L, channel_full(msg->chn, 0));
6553 return 1;
6554}
6555
6556/* Returns true if the HTTP message may still receive data. */
6557__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6558{
6559 struct http_msg *msg;
6560 struct htx *htx;
6561
6562 MAY_LJMP(check_args(L, 1, "may_recv"));
6563 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6564 htx = htxbuf(&msg->chn->buf);
6565 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6566 return 1;
6567}
6568
6569/* Returns true if the HTTP message EOM was received */
6570__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6571{
6572 struct http_msg *msg;
6573 struct htx *htx;
6574
6575 MAY_LJMP(check_args(L, 1, "may_recv"));
6576 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6577 htx = htxbuf(&msg->chn->buf);
6578 lua_pushboolean(L, !htx_expect_more(htx));
6579 return 1;
6580}
6581
6582/* Returns the number of bytes available in the input side of the HTTP
6583 * message. This function never fails.
6584 */
6585__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6586{
6587 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006588 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006589
6590 MAY_LJMP(check_args(L, 1, "input"));
6591 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006592 hlua_http_msg_filter(L, 1, msg, &output, &input);
6593 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006594 return 1;
6595}
6596
6597/* Returns the number of bytes available in the output side of the HTTP
6598 * message. This function never fails.
6599 */
6600__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6601{
6602 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006603 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006604
6605 MAY_LJMP(check_args(L, 1, "output"));
6606 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006607 hlua_http_msg_filter(L, 1, msg, &output, &input);
6608 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006609 return 1;
6610}
6611
6612/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6613 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006614 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006615 * block. This function is called during the payload filtering, so the headers
6616 * are already scheduled for output (from the filter point of view).
6617 */
6618static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6619{
6620 struct htx *htx = htxbuf(&msg->chn->buf);
6621 struct htx_blk *blk;
6622 struct htx_ret htxret;
6623 luaL_Buffer b;
6624 int ret = 0;
6625
6626 luaL_buffinit(L, &b);
6627 htxret = htx_find_offset(htx, offset);
6628 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6629 enum htx_blk_type type = htx_get_blk_type(blk);
6630 struct ist v;
6631
6632 switch (type) {
6633 case HTX_BLK_UNUSED:
6634 break;
6635
6636 case HTX_BLK_DATA:
6637 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006638 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006639 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006640
6641 luaL_addlstring(&b, v.ptr, v.len);
6642 ret += v.len;
6643 break;
6644
6645 default:
vishnu0af4bd72021-10-24 06:46:24 +05306646 if (!ret)
6647 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 goto end;
6649 }
6650 offset = 0;
6651 }
6652
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006653end:
vishnu0af4bd72021-10-24 06:46:24 +05306654 if (!ret && (htx->flags & HTX_FL_EOM))
6655 goto no_data;
6656 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006657 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306658
6659 no_data:
6660 /* Remove the empty string and push nil on the stack */
6661 lua_pop(L, 1);
6662 lua_pushnil(L);
6663 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006664}
6665
6666/* Copies the string <str> to the HTTP message <msg> at the offset
6667 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006668 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006669 * the filter context.
6670 */
6671static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6672{
6673 struct htx *htx = htx_from_buf(&msg->chn->buf);
6674 struct htx_ret htxret;
6675 int /*max, */ret = 0;
6676
6677 /* Nothing to do, just return */
6678 if (unlikely(istlen(str) == 0))
6679 goto end;
6680
6681 if (istlen(str) > htx_free_data_space(htx)) {
6682 ret = -1;
6683 goto end;
6684 }
6685
6686 htxret = htx_find_offset(htx, offset);
6687 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6688 if (!htx_add_last_data(htx, str))
6689 goto end;
6690 }
6691 else {
6692 struct ist v = htx_get_blk_value(htx, htxret.blk);
6693 v.ptr += htxret.ret;
6694 v.len = 0;
6695 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6696 goto end;
6697 }
6698 ret = str.len;
6699 if (ret) {
6700 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6701 flt_update_offsets(filter, msg->chn, ret);
6702 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6703 }
6704
6705 end:
6706 htx_to_buf(htx, &msg->chn->buf);
6707 return ret;
6708}
6709
6710/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6711 * position <offset>. It stops on the first non-DATA HTX block. This function is
6712 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006713 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006714 * update the filter context.
6715 */
6716static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6717{
6718 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6719 struct htx *htx = htx_from_buf(&msg->chn->buf);
6720 struct htx_blk *blk;
6721 struct htx_ret htxret;
6722 size_t ret = 0;
6723
6724 /* Be sure <len> is always the amount of DATA to remove */
6725 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006726 /* When htx tail type == HTX_BLK_DATA, no need to take care
6727 * of special blocks like HTX_BLK_EOT.
6728 * We simply truncate after offset
6729 * (truncate targeted blk and discard the following ones)
6730 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 htx_truncate(htx, offset);
6732 ret = len;
6733 goto end;
6734 }
6735
6736 htxret = htx_find_offset(htx, offset);
6737 blk = htxret.blk;
6738 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006739 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006740 struct ist v;
6741
6742 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6743 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006744
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006745 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006746 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006747
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006748 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006749 /* trimming data in blk: discard everything after the offset
6750 * (replace 'v' with 'IST_NULL')
6751 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006752 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006753 if (blk && v.len < len) {
6754 /* In this case, caller wants to keep removing data,
6755 * but we need to spare current blk
6756 * because it was already trimmed
6757 */
6758 blk = htx_get_next_blk(htx, blk);
6759 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006760 len -= v.len;
6761 ret += v.len;
6762 }
6763
6764
6765 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006766 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006767 enum htx_blk_type type = htx_get_blk_type(blk);
6768 uint32_t sz = htx_get_blksz(blk);
6769
6770 switch (type) {
6771 case HTX_BLK_UNUSED:
6772 break;
6773
6774 case HTX_BLK_DATA:
6775 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006776 /* don't discard whole blk, only part of it
6777 * (from the beginning)
6778 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006779 htx_cut_data_blk(htx, blk, len);
6780 ret += len;
6781 goto end;
6782 }
6783 break;
6784
6785 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006786 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 goto end;
6788 }
6789
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006790 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006791 len -= sz;
6792 ret += sz;
6793 blk = htx_remove_blk(htx, blk);
6794 }
6795
6796end:
6797 flt_update_offsets(filter, msg->chn, -ret);
6798 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6799 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6800 * to loose the EOM flag if the message is empty.
6801 */
6802}
6803
6804/* Copies input data found in an HTTP message. Unlike the channel function used
6805 * to duplicate raw data, this one can only be called inside a filter, from
6806 * http_payload callback. So it cannot yield. An exception is returned if it is
6807 * called from another callback. If nothing was copied, a nil value is pushed on
6808 * the stack.
6809 */
6810__LJMP static int hlua_http_msg_get_body(lua_State *L)
6811{
6812 struct http_msg *msg;
6813 struct filter *filter;
6814 size_t output, input;
6815 int offset, len;
6816
6817 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6818 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6819 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6820
6821 if (msg->msg_state < HTTP_MSG_DATA)
6822 WILL_LJMP(lua_error(L));
6823
6824 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6825 if (!filter || !hlua_filter_from_payload(filter))
6826 WILL_LJMP(lua_error(L));
6827
6828 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6829 lua_pushnil(L);
6830 return 1;
6831 }
6832
6833 offset = output;
6834 if (lua_gettop(L) > 1) {
6835 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6836 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006837 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006838 offset += output;
6839 if (offset < output || offset > input + output) {
6840 lua_pushfstring(L, "offset out of range.");
6841 WILL_LJMP(lua_error(L));
6842 }
6843 }
6844 len = output + input - offset;
6845 if (lua_gettop(L) == 3) {
6846 len = MAY_LJMP(luaL_checkinteger(L, 3));
6847 if (!len)
6848 goto dup;
6849 if (len == -1)
6850 len = global.tune.bufsize;
6851 if (len < 0) {
6852 lua_pushfstring(L, "length out of range.");
6853 WILL_LJMP(lua_error(L));
6854 }
6855 }
6856
6857 dup:
6858 _hlua_http_msg_dup(msg, L, offset, len);
6859 return 1;
6860}
6861
6862/* Appends a string to the HTTP message, after all existing DATA blocks but
6863 * before the trailers, if any. It returns the amount of data written or -1 if
6864 * nothing was copied. Unlike the channel function used to append data, this one
6865 * can only be called inside a filter, from http_payload callback. So it cannot
6866 * yield. An exception is returned if it is called from another callback.
6867 */
6868__LJMP static int hlua_http_msg_append(lua_State *L)
6869{
6870 struct http_msg *msg;
6871 struct filter *filter;
6872 const char *str;
6873 size_t offset, len, sz;
6874 int ret;
6875
6876 MAY_LJMP(check_args(L, 2, "append"));
6877 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6878
6879 if (msg->msg_state < HTTP_MSG_DATA)
6880 WILL_LJMP(lua_error(L));
6881
6882 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6883 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6884 if (!filter || !hlua_filter_from_payload(filter))
6885 WILL_LJMP(lua_error(L));
6886
6887 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6888 lua_pushinteger(L, ret);
6889 return 1;
6890}
6891
6892/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6893 * returns the amount of data written or -1 if nothing was copied. Unlike the
6894 * channel function used to prepend data, this one can only be called inside a
6895 * filter, from http_payload callback. So it cannot yield. An exception is
6896 * returned if it is called from another callback.
6897 */
6898__LJMP static int hlua_http_msg_prepend(lua_State *L)
6899{
6900 struct http_msg *msg;
6901 struct filter *filter;
6902 const char *str;
6903 size_t offset, len, sz;
6904 int ret;
6905
6906 MAY_LJMP(check_args(L, 2, "prepend"));
6907 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006908
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006909 if (msg->msg_state < HTTP_MSG_DATA)
6910 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006911
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006912 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6913 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6914 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006915 WILL_LJMP(lua_error(L));
6916
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006917 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6918 lua_pushinteger(L, ret);
6919 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006920}
6921
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006922/* Inserts a string to the HTTP message at a given offset. By default the string
6923 * is appended at the end of DATA blocks. It returns the amount of data written
6924 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6925 * this one can only be called inside a filter, from http_payload callback. So
6926 * it cannot yield. An exception is returned if it is called from another
6927 * callback.
6928 */
6929__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006930{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006931 struct http_msg *msg;
6932 struct filter *filter;
6933 const char *str;
6934 size_t input, output, sz;
6935 int offset;
6936 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006937
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006938 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6939 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006940 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006941
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006942 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006943 WILL_LJMP(lua_error(L));
6944
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006945 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006946 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006947 if (!filter || !hlua_filter_from_payload(filter))
6948 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006949
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006950 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006951 if (lua_gettop(L) > 2) {
6952 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6953 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006954 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006955 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006956 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006957 lua_pushfstring(L, "offset out of range.");
6958 WILL_LJMP(lua_error(L));
6959 }
6960 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006961
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006962 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6963 lua_pushinteger(L, ret);
6964 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006965}
6966
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006967/* Removes a given amount of data from the HTTP message at a given offset. By
6968 * default all DATA blocks are removed. It returns the amount of data
6969 * removed. Unlike the channel function used to remove data, this one can only
6970 * be called inside a filter, from http_payload callback. So it cannot yield. An
6971 * exception is returned if it is called from another callback.
6972 */
6973__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006974{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006975 struct http_msg *msg;
6976 struct filter *filter;
6977 size_t input, output;
6978 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006979
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006980 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006981 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006982 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006983
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006984 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006985 WILL_LJMP(lua_error(L));
6986
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006987 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006988 if (!filter || !hlua_filter_from_payload(filter))
6989 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006990
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006991 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006992 if (lua_gettop(L) > 1) {
6993 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006994 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006995 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006996 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006997 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006998 lua_pushfstring(L, "offset out of range.");
6999 WILL_LJMP(lua_error(L));
7000 }
7001 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007002
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007003 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00007004 if (lua_gettop(L) == 3) {
7005 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007006 if (!len)
7007 goto end;
7008 if (len == -1)
7009 len = output + input - offset;
7010 if (len < 0 || offset + len > output + input) {
7011 lua_pushfstring(L, "length out of range.");
7012 WILL_LJMP(lua_error(L));
7013 }
7014 }
7015
7016 _hlua_http_msg_delete(msg, filter, offset, len);
7017
7018 end:
7019 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007020 return 1;
7021}
7022
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007023/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007024 * all remaining data are removed, accordingly to the filter context. It returns
7025 * the amount of data written or -1 if nothing was copied. Unlike the channel
7026 * function used to replace data, this one can only be called inside a filter,
7027 * from http_payload callback. So it cannot yield. An exception is returned if
7028 * it is called from another callback.
7029 */
7030__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007031{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007032 struct http_msg *msg;
7033 struct filter *filter;
7034 struct htx *htx;
7035 const char *str;
7036 size_t input, output, sz;
7037 int offset, len;
7038 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007039
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007040 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7041 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7042 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7043
7044 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007045 WILL_LJMP(lua_error(L));
7046
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007047 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7048 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7049 if (!filter || !hlua_filter_from_payload(filter))
7050 WILL_LJMP(lua_error(L));
7051
7052 offset = output;
7053 if (lua_gettop(L) > 2) {
7054 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7055 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007056 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007057 offset += output;
7058 if (offset < output || offset > input + output) {
7059 lua_pushfstring(L, "offset out of range.");
7060 WILL_LJMP(lua_error(L));
7061 }
7062 }
7063
7064 len = output + input - offset;
7065 if (lua_gettop(L) == 4) {
7066 len = MAY_LJMP(luaL_checkinteger(L, 4));
7067 if (!len)
7068 goto set;
7069 if (len == -1)
7070 len = output + input - offset;
7071 if (len < 0 || offset + len > output + input) {
7072 lua_pushfstring(L, "length out of range.");
7073 WILL_LJMP(lua_error(L));
7074 }
7075 }
7076
7077 set:
7078 /* Be sure we can copied the string once input data will be removed. */
7079 htx = htx_from_buf(&msg->chn->buf);
7080 if (sz > htx_free_data_space(htx) + len)
7081 lua_pushinteger(L, -1);
7082 else {
7083 _hlua_http_msg_delete(msg, filter, offset, len);
7084 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7085 lua_pushinteger(L, ret);
7086 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007087 return 1;
7088}
7089
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007090/* Prepends data into an HTTP message and forward it, from the filter point of
7091 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7092 * the channel function used to send data, this one can only be called inside a
7093 * filter, from http_payload callback. So it cannot yield. An exception is
7094 * returned if it is called from another callback.
7095 */
7096__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007097{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007098 struct http_msg *msg;
7099 struct filter *filter;
7100 struct htx *htx;
7101 const char *str;
7102 size_t offset, len, sz;
7103 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007104
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007105 MAY_LJMP(check_args(L, 2, "send"));
7106 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7107
7108 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007109 WILL_LJMP(lua_error(L));
7110
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007111 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7112 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7113 if (!filter || !hlua_filter_from_payload(filter))
7114 WILL_LJMP(lua_error(L));
7115
7116 /* Return an error if the channel's output is closed */
7117 if (unlikely(channel_output_closed(msg->chn))) {
7118 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007119 return 1;
7120 }
7121
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007122 htx = htx_from_buf(&msg->chn->buf);
7123 if (sz > htx_free_data_space(htx)) {
7124 lua_pushinteger(L, -1);
7125 return 1;
7126 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007127
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007128 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7129 if (ret > 0) {
7130 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7131
7132 FLT_OFF(filter, msg->chn) += ret;
7133 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7134 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7135 }
7136
7137 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007138 return 1;
7139}
7140
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007141/* Forwards a given amount of bytes. It return -1 if the channel's output is
7142 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7143 * channel function used to forward data, this one can only be called inside a
7144 * filter, from http_payload callback. So it cannot yield. An exception is
7145 * returned if it is called from another callback. All other functions deal with
7146 * DATA block, this one not.
7147*/
7148__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007149{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007150 struct http_msg *msg;
7151 struct filter *filter;
7152 size_t offset, len;
7153 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007154
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007155 MAY_LJMP(check_args(L, 2, "forward"));
7156 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7157
7158 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007159 WILL_LJMP(lua_error(L));
7160
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007161 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7162 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7163 if (!filter || !hlua_filter_from_payload(filter))
7164 WILL_LJMP(lua_error(L));
7165
7166 /* Nothing to do, just return */
7167 if (!fwd)
7168 goto end;
7169
7170 /* Return an error if the channel's output is closed */
7171 if (unlikely(channel_output_closed(msg->chn))) {
7172 ret = -1;
7173 goto end;
7174 }
7175
7176 ret = fwd;
7177 if (ret > len)
7178 ret = len;
7179
7180 if (ret) {
7181 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7182
7183 FLT_OFF(filter, msg->chn) += ret;
7184 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7185 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7186 }
7187
7188 end:
7189 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007190 return 1;
7191}
7192
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007193/* Set EOM flag on the HTX message.
7194 *
7195 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7196 * really know how to do without this feature.
7197 */
7198__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007199{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007200 struct http_msg *msg;
7201 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007202
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007203 MAY_LJMP(check_args(L, 1, "set_eom"));
7204 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7205 htx = htxbuf(&msg->chn->buf);
7206 htx->flags |= HTX_FL_EOM;
7207 return 0;
7208}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007209
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007210/* Unset EOM flag on the HTX message.
7211 *
7212 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7213 * really know how to do without this feature.
7214 */
7215__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7216{
7217 struct http_msg *msg;
7218 struct htx *htx;
7219
7220 MAY_LJMP(check_args(L, 1, "set_eom"));
7221 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7222 htx = htxbuf(&msg->chn->buf);
7223 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007224 return 0;
7225}
7226
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007227/*
7228 *
7229 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007230 * Class HTTPClient
7231 *
7232 *
7233 */
7234__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7235{
7236 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7237}
7238
William Lallemandf77f1de2021-09-28 19:10:38 +02007239
7240/* stops the httpclient and ask it to kill itself */
7241__LJMP static int hlua_httpclient_gc(lua_State *L)
7242{
7243 struct hlua_httpclient *hlua_hc;
7244
7245 MAY_LJMP(check_args(L, 1, "__gc"));
7246
7247 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7248
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007249 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7250 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007251 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007252 hlua_hc->hc = NULL;
7253 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007254
7255 return 0;
7256}
7257
7258
William Lallemand3956c4e2021-09-21 16:25:15 +02007259__LJMP static int hlua_httpclient_new(lua_State *L)
7260{
7261 struct hlua_httpclient *hlua_hc;
7262 struct hlua *hlua;
7263
7264 /* Get hlua struct, or NULL if we execute from main lua state */
7265 hlua = hlua_gethlua(L);
7266 if (!hlua)
7267 return 0;
7268
7269 /* Check stack size. */
7270 if (!lua_checkstack(L, 3)) {
7271 hlua_pusherror(L, "httpclient: full stack");
7272 goto err;
7273 }
7274 /* Create the object: obj[0] = userdata. */
7275 lua_newtable(L);
7276 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7277 lua_rawseti(L, -2, 0);
7278 memset(hlua_hc, 0, sizeof(*hlua_hc));
7279
7280 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7281 if (!hlua_hc->hc)
7282 goto err;
7283
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007284 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007285
William Lallemand3956c4e2021-09-21 16:25:15 +02007286 /* Pop a class stream metatable and affect it to the userdata. */
7287 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7288 lua_setmetatable(L, -2);
7289
7290 return 1;
7291
7292 err:
7293 WILL_LJMP(lua_error(L));
7294 return 0;
7295}
7296
7297
7298/*
7299 * Callback of the httpclient, this callback wakes the lua task up, once the
7300 * httpclient receives some data
7301 *
7302 */
7303
William Lallemandbd5739e2021-10-28 15:41:38 +02007304static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007305{
7306 struct hlua *hlua = hc->caller;
7307
7308 if (!hlua || !hlua->task)
7309 return;
7310
7311 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7312}
7313
7314/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007315 * Fill the lua stack with headers from the httpclient response
7316 * This works the same way as the hlua_http_get_headers() function
7317 */
7318__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7319{
7320 struct http_hdr *hdr;
7321
7322 lua_newtable(L);
7323
William Lallemandef574b22021-10-05 16:19:31 +02007324 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007325 struct ist n, v;
7326 int len;
7327
7328 n = hdr->n;
7329 v = hdr->v;
7330
7331 /* Check for existing entry:
7332 * assume that the table is on the top of the stack, and
7333 * push the key in the stack, the function lua_gettable()
7334 * perform the lookup.
7335 */
7336
7337 lua_pushlstring(L, n.ptr, n.len);
7338 lua_gettable(L, -2);
7339
7340 switch (lua_type(L, -1)) {
7341 case LUA_TNIL:
7342 /* Table not found, create it. */
7343 lua_pop(L, 1); /* remove the nil value. */
7344 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7345 lua_newtable(L); /* create and push empty table. */
7346 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7347 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7348 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7349 break;
7350
7351 case LUA_TTABLE:
7352 /* Entry found: push the value in the table. */
7353 len = lua_rawlen(L, -1);
7354 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7355 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7356 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7357 break;
7358
7359 default:
7360 /* Other cases are errors. */
7361 hlua_pusherror(L, "internal error during the parsing of headers.");
7362 WILL_LJMP(lua_error(L));
7363 }
7364 }
7365 return 1;
7366}
7367
7368/*
William Lallemand746e6f32021-10-06 10:57:44 +02007369 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7370 *
7371 * Caller must free the result
7372 */
7373struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7374{
7375 struct http_hdr hdrs[global.tune.max_http_hdr];
7376 struct http_hdr *result = NULL;
7377 uint32_t hdr_num = 0;
7378
7379 lua_pushnil(L);
7380 while (lua_next(L, -2) != 0) {
7381 struct ist name, value;
7382 const char *n, *v;
7383 size_t nlen, vlen;
7384
7385 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7386 /* Skip element if the key is not a string or if the value is not a table */
7387 goto next_hdr;
7388 }
7389
7390 n = lua_tolstring(L, -2, &nlen);
7391 name = ist2(n, nlen);
7392
7393 /* Loop on header's values */
7394 lua_pushnil(L);
7395 while (lua_next(L, -2)) {
7396 if (!lua_isstring(L, -1)) {
7397 /* Skip the value if it is not a string */
7398 goto next_value;
7399 }
7400
7401 v = lua_tolstring(L, -1, &vlen);
7402 value = ist2(v, vlen);
7403 name = ist2(n, nlen);
7404
7405 hdrs[hdr_num].n = istdup(name);
7406 hdrs[hdr_num].v = istdup(value);
7407
7408 hdr_num++;
7409
7410 next_value:
7411 lua_pop(L, 1);
7412 }
7413
7414 next_hdr:
7415 lua_pop(L, 1);
7416
7417 }
7418
7419 if (hdr_num) {
7420 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007421 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007422 if (!result)
7423 goto skip_headers;
7424 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7425
7426 result[hdr_num].n = IST_NULL;
7427 result[hdr_num].v = IST_NULL;
7428 }
7429
7430skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007431
7432 return result;
7433}
7434
7435
William Lallemandbd5739e2021-10-28 15:41:38 +02007436/*
7437 * For each yield, checks if there is some data in the httpclient and push them
7438 * in the lua buffer, once the httpclient finished its job, push the result on
7439 * the stack
7440 */
7441__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7442{
7443 struct buffer *tr;
7444 int res;
7445 struct hlua *hlua = hlua_gethlua(L);
7446 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7447
7448
7449 tr = get_trash_chunk();
7450
7451 res = httpclient_res_xfer(hlua_hc->hc, tr);
7452 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7453
7454 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7455
7456 luaL_pushresult(&hlua_hc->b);
7457 lua_settable(L, -3);
7458
7459 lua_pushstring(L, "status");
7460 lua_pushinteger(L, hlua_hc->hc->res.status);
7461 lua_settable(L, -3);
7462
7463
7464 lua_pushstring(L, "reason");
7465 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7466 lua_settable(L, -3);
7467
7468 lua_pushstring(L, "headers");
7469 hlua_httpclient_get_headers(L, hlua_hc);
7470 lua_settable(L, -3);
7471
7472 return 1;
7473 }
7474
7475 if (httpclient_data(hlua_hc->hc))
7476 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7477
7478 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7479
7480 return 0;
7481}
7482
7483/*
7484 * Call this when trying to stream a body during a request
7485 */
7486__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7487{
7488 struct hlua *hlua;
7489 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7490 const char *body_str = NULL;
7491 int ret;
7492 int end = 0;
7493 size_t buf_len;
7494 size_t to_send = 0;
7495
7496 hlua = hlua_gethlua(L);
7497
7498 if (!hlua || !hlua->task)
7499 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7500 "'frontend', 'backend' or 'task'"));
7501
7502 ret = lua_getfield(L, -1, "body");
7503 if (ret != LUA_TSTRING)
7504 goto rcv;
7505
7506 body_str = lua_tolstring(L, -1, &buf_len);
7507 lua_pop(L, 1);
7508
Christopher Fauletfc591292022-01-12 14:46:03 +01007509 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007510
7511 if ((hlua_hc->sent + to_send) >= buf_len)
7512 end = 1;
7513
7514 /* the end flag is always set since we are using the whole remaining size */
7515 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7516
7517 if (buf_len > hlua_hc->sent) {
7518 /* still need to process the buffer */
7519 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7520 } else {
7521 goto rcv;
7522 /* we sent the whole request buffer we can recv */
7523 }
7524 return 0;
7525
7526rcv:
7527
7528 /* we return a "res" object */
7529 lua_newtable(L);
7530
William Lallemandbd5739e2021-10-28 15:41:38 +02007531 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007532 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007533
William Lallemand933fe392021-11-04 09:45:58 +01007534 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007535 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7536
7537 return 1;
7538}
William Lallemand746e6f32021-10-06 10:57:44 +02007539
William Lallemand3956c4e2021-09-21 16:25:15 +02007540/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007541 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007542 */
7543
William Lallemanddc2cc902021-10-26 11:43:26 +02007544__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007545{
7546 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007547 struct http_hdr *hdrs = NULL;
7548 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007549 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007550 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007551 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007552 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007553 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007554
7555 hlua = hlua_gethlua(L);
7556
7557 if (!hlua || !hlua->task)
7558 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7559 "'frontend', 'backend' or 'task'"));
7560
William Lallemand746e6f32021-10-06 10:57:44 +02007561 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7562 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7563
William Lallemand4f4f2b72022-02-17 20:00:23 +01007564 hlua_hc = hlua_checkhttpclient(L, 1);
7565
William Lallemand7177a952022-03-03 15:33:12 +01007566 lua_pushnil(L); /* first key */
7567 while (lua_next(L, 2)) {
7568 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7569 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7570 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007571
William Lallemand7177a952022-03-03 15:33:12 +01007572 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7573 if (lua_type(L, -1) != LUA_TSTRING)
7574 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7575 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007576
William Lallemand7177a952022-03-03 15:33:12 +01007577 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7578 if (lua_type(L, -1) != LUA_TNUMBER)
7579 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7580 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007581
William Lallemand7177a952022-03-03 15:33:12 +01007582 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7583 if (lua_type(L, -1) != LUA_TTABLE)
7584 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7585 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007586
William Lallemand7177a952022-03-03 15:33:12 +01007587 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7588 if (lua_type(L, -1) != LUA_TSTRING)
7589 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7590 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007591
William Lallemand7177a952022-03-03 15:33:12 +01007592 } else {
7593 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7594 }
7595 /* removes 'value'; keeps 'key' for next iteration */
7596 lua_pop(L, 1);
7597 }
William Lallemanddec25c32021-10-25 19:48:37 +02007598
William Lallemand746e6f32021-10-06 10:57:44 +02007599 if (!url_str) {
7600 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7601 return 0;
7602 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007603
William Lallemand10a37362022-03-02 16:18:26 +01007604 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007605
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007606 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007607 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007608 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007609
7610 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007611 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7612 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7613 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007614 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007615
William Lallemandbd5739e2021-10-28 15:41:38 +02007616 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007617 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007618 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7619 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007620
William Lallemandbd5739e2021-10-28 15:41:38 +02007621 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007622
William Lallemand746e6f32021-10-06 10:57:44 +02007623 /* free the temporary headers array */
7624 hdrs_i = hdrs;
7625 while (hdrs_i && isttest(hdrs_i->n)) {
7626 istfree(&hdrs_i->n);
7627 istfree(&hdrs_i->v);
7628 hdrs_i++;
7629 }
7630 ha_free(&hdrs);
7631
7632
William Lallemand6137a9e2021-10-26 15:01:53 +02007633 if (ret != ERR_NONE) {
7634 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7635 return 0;
7636 }
7637
William Lallemandc2d3db42022-04-26 11:46:13 +02007638 if (!httpclient_start(hlua_hc->hc))
7639 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007640
William Lallemandbd5739e2021-10-28 15:41:38 +02007641 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007642
William Lallemand3956c4e2021-09-21 16:25:15 +02007643 return 0;
7644}
7645
7646/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007647 * Sends an HTTP HEAD request and wait for a response
7648 *
7649 * httpclient:head(url, headers, payload)
7650 */
7651__LJMP static int hlua_httpclient_head(lua_State *L)
7652{
7653 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7654}
7655
7656/*
7657 * Send an HTTP GET request and wait for a response
7658 *
7659 * httpclient:get(url, headers, payload)
7660 */
7661__LJMP static int hlua_httpclient_get(lua_State *L)
7662{
7663 return hlua_httpclient_send(L, HTTP_METH_GET);
7664
7665}
7666
7667/*
7668 * Sends an HTTP PUT request and wait for a response
7669 *
7670 * httpclient:put(url, headers, payload)
7671 */
7672__LJMP static int hlua_httpclient_put(lua_State *L)
7673{
7674 return hlua_httpclient_send(L, HTTP_METH_PUT);
7675}
7676
7677/*
7678 * Send an HTTP POST request and wait for a response
7679 *
7680 * httpclient:post(url, headers, payload)
7681 */
7682__LJMP static int hlua_httpclient_post(lua_State *L)
7683{
7684 return hlua_httpclient_send(L, HTTP_METH_POST);
7685}
7686
7687
7688/*
7689 * Sends an HTTP DELETE request and wait for a response
7690 *
7691 * httpclient:delete(url, headers, payload)
7692 */
7693__LJMP static int hlua_httpclient_delete(lua_State *L)
7694{
7695 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7696}
7697
7698/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007699 *
7700 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007701 * Class TXN
7702 *
7703 *
7704 */
7705
7706/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007707 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007708 */
7709__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7710{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007711 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007712}
7713
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007714__LJMP static int hlua_set_var(lua_State *L)
7715{
7716 struct hlua_txn *htxn;
7717 const char *name;
7718 size_t len;
7719 struct sample smp;
7720
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007721 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7722 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007723
7724 /* It is useles to retrieve the stream, but this function
7725 * runs only in a stream context.
7726 */
7727 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7728 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7729
7730 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007731 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007732 hlua_lua2smp(L, 3, &smp);
7733
7734 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007735 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007736
7737 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7738 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7739 else
7740 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7741
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007742 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007743}
7744
Christopher Faulet85d79c92016-11-09 16:54:56 +01007745__LJMP static int hlua_unset_var(lua_State *L)
7746{
7747 struct hlua_txn *htxn;
7748 const char *name;
7749 size_t len;
7750 struct sample smp;
7751
7752 MAY_LJMP(check_args(L, 2, "unset_var"));
7753
7754 /* It is useles to retrieve the stream, but this function
7755 * runs only in a stream context.
7756 */
7757 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7758 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7759
7760 /* Unset the variable. */
7761 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007762 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7763 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007764}
7765
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007766__LJMP static int hlua_get_var(lua_State *L)
7767{
7768 struct hlua_txn *htxn;
7769 const char *name;
7770 size_t len;
7771 struct sample smp;
7772
7773 MAY_LJMP(check_args(L, 2, "get_var"));
7774
7775 /* It is useles to retrieve the stream, but this function
7776 * runs only in a stream context.
7777 */
7778 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7779 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7780
Willy Tarreau7560dd42016-03-10 16:28:58 +01007781 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007782 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007783 lua_pushnil(L);
7784 return 1;
7785 }
7786
7787 return hlua_smp2lua(L, &smp);
7788}
7789
Willy Tarreau59551662015-03-10 14:23:13 +01007790__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007791{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007792 struct hlua *hlua;
7793
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007794 MAY_LJMP(check_args(L, 2, "set_priv"));
7795
Willy Tarreau87b09662015-04-03 00:22:06 +02007796 /* It is useles to retrieve the stream, but this function
7797 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007798 */
7799 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007800
7801 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007802 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007803 if (!hlua)
7804 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007805
7806 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007807 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007808
7809 /* Get and store new value. */
7810 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7811 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7812
7813 return 0;
7814}
7815
Willy Tarreau59551662015-03-10 14:23:13 +01007816__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007817{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007818 struct hlua *hlua;
7819
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007820 MAY_LJMP(check_args(L, 1, "get_priv"));
7821
Willy Tarreau87b09662015-04-03 00:22:06 +02007822 /* It is useles to retrieve the stream, but this function
7823 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007824 */
7825 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007826
7827 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007828 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007829 if (!hlua) {
7830 lua_pushnil(L);
7831 return 1;
7832 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007833
7834 /* Push configuration index in the stack. */
7835 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7836
7837 return 1;
7838}
7839
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007840/* Create stack entry containing a class TXN. This function
7841 * return 0 if the stack does not contains free slots,
7842 * otherwise it returns 1.
7843 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007844static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007845{
Willy Tarreaude491382015-04-06 11:04:28 +02007846 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007847
7848 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007849 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007850 return 0;
7851
7852 /* NOTE: The allocation never fails. The failure
7853 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007854 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007855 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007856 /* Create the object: obj[0] = userdata. */
7857 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007858 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007859 lua_rawseti(L, -2, 0);
7860
Willy Tarreaude491382015-04-06 11:04:28 +02007861 htxn->s = s;
7862 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007863 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007864 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007865
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007866 /* Create the "f" field that contains a list of fetches. */
7867 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007868 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007869 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007870 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007871
7872 /* Create the "sf" field that contains a list of stringsafe fetches. */
7873 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007874 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007875 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007876 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007877
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007878 /* Create the "c" field that contains a list of converters. */
7879 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007880 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007881 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007882 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007883
7884 /* Create the "sc" field that contains a list of stringsafe converters. */
7885 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007886 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007887 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007888 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007889
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007890 /* Create the "req" field that contains the request channel object. */
7891 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007892 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007893 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007894 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007895
7896 /* Create the "res" field that contains the response channel object. */
7897 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007898 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007899 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007900 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007901
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007902 /* Creates the HTTP object is the current proxy allows http. */
7903 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007904 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007905 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007906 return 0;
7907 }
7908 else
7909 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007910 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007911
Christopher Faulet78c35472020-02-26 17:14:08 +01007912 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7913 /* HTTPMessage object are created when a lua TXN is created from
7914 * a filter context only
7915 */
7916
7917 /* Creates the HTTP-Request object is the current proxy allows http. */
7918 lua_pushstring(L, "http_req");
7919 if (p->mode == PR_MODE_HTTP) {
7920 if (!hlua_http_msg_new(L, &s->txn->req))
7921 return 0;
7922 }
7923 else
7924 lua_pushnil(L);
7925 lua_rawset(L, -3);
7926
7927 /* Creates the HTTP-Response object is the current proxy allows http. */
7928 lua_pushstring(L, "http_res");
7929 if (p->mode == PR_MODE_HTTP) {
7930 if (!hlua_http_msg_new(L, &s->txn->rsp))
7931 return 0;
7932 }
7933 else
7934 lua_pushnil(L);
7935 lua_rawset(L, -3);
7936 }
7937
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007938 /* Pop a class sesison metatable and affect it to the userdata. */
7939 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7940 lua_setmetatable(L, -2);
7941
7942 return 1;
7943}
7944
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007945__LJMP static int hlua_txn_deflog(lua_State *L)
7946{
7947 const char *msg;
7948 struct hlua_txn *htxn;
7949
7950 MAY_LJMP(check_args(L, 2, "deflog"));
7951 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7952 msg = MAY_LJMP(luaL_checkstring(L, 2));
7953
7954 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7955 return 0;
7956}
7957
7958__LJMP static int hlua_txn_log(lua_State *L)
7959{
7960 int level;
7961 const char *msg;
7962 struct hlua_txn *htxn;
7963
7964 MAY_LJMP(check_args(L, 3, "log"));
7965 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7966 level = MAY_LJMP(luaL_checkinteger(L, 2));
7967 msg = MAY_LJMP(luaL_checkstring(L, 3));
7968
7969 if (level < 0 || level >= NB_LOG_LEVELS)
7970 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7971
7972 hlua_sendlog(htxn->s->be, level, msg);
7973 return 0;
7974}
7975
7976__LJMP static int hlua_txn_log_debug(lua_State *L)
7977{
7978 const char *msg;
7979 struct hlua_txn *htxn;
7980
7981 MAY_LJMP(check_args(L, 2, "Debug"));
7982 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7983 msg = MAY_LJMP(luaL_checkstring(L, 2));
7984 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7985 return 0;
7986}
7987
7988__LJMP static int hlua_txn_log_info(lua_State *L)
7989{
7990 const char *msg;
7991 struct hlua_txn *htxn;
7992
7993 MAY_LJMP(check_args(L, 2, "Info"));
7994 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7995 msg = MAY_LJMP(luaL_checkstring(L, 2));
7996 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7997 return 0;
7998}
7999
8000__LJMP static int hlua_txn_log_warning(lua_State *L)
8001{
8002 const char *msg;
8003 struct hlua_txn *htxn;
8004
8005 MAY_LJMP(check_args(L, 2, "Warning"));
8006 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8007 msg = MAY_LJMP(luaL_checkstring(L, 2));
8008 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
8009 return 0;
8010}
8011
8012__LJMP static int hlua_txn_log_alert(lua_State *L)
8013{
8014 const char *msg;
8015 struct hlua_txn *htxn;
8016
8017 MAY_LJMP(check_args(L, 2, "Alert"));
8018 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8019 msg = MAY_LJMP(luaL_checkstring(L, 2));
8020 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8021 return 0;
8022}
8023
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008024__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8025{
8026 struct hlua_txn *htxn;
8027 int ll;
8028
8029 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8030 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8031 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8032
8033 if (ll < 0 || ll > 7)
8034 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
8035
8036 htxn->s->logs.level = ll;
8037 return 0;
8038}
8039
8040__LJMP static int hlua_txn_set_tos(lua_State *L)
8041{
8042 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008043 int tos;
8044
8045 MAY_LJMP(check_args(L, 2, "set_tos"));
8046 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8047 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8048
Willy Tarreau1a18b542018-12-11 16:37:42 +01008049 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008050 return 0;
8051}
8052
8053__LJMP static int hlua_txn_set_mark(lua_State *L)
8054{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008055 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008056 int mark;
8057
8058 MAY_LJMP(check_args(L, 2, "set_mark"));
8059 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8060 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8061
Lukas Tribus579e3e32019-08-11 18:03:45 +02008062 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008063 return 0;
8064}
8065
Patrick Hemmer268a7072018-05-11 12:52:31 -04008066__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8067{
8068 struct hlua_txn *htxn;
8069
8070 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8071 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8072 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8073 return 0;
8074}
8075
8076__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8077{
8078 struct hlua_txn *htxn;
8079
8080 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8081 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8082 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8083 return 0;
8084}
8085
Christopher Faulet700d9e82020-01-31 12:21:52 +01008086/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008087 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008088 * message and terminate the transaction. It returns 1 on success and 0 on
8089 * error. The Reply must be on top of the stack.
8090 */
8091__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8092{
8093 struct htx *htx;
8094 struct htx_sl *sl;
8095 struct h1m h1m;
8096 const char *status, *reason, *body;
8097 size_t status_len, reason_len, body_len;
8098 int ret, code, flags;
8099
8100 code = 200;
8101 status = "200";
8102 status_len = 3;
8103 ret = lua_getfield(L, -1, "status");
8104 if (ret == LUA_TNUMBER) {
8105 code = lua_tointeger(L, -1);
8106 status = lua_tolstring(L, -1, &status_len);
8107 }
8108 lua_pop(L, 1);
8109
8110 reason = http_get_reason(code);
8111 reason_len = strlen(reason);
8112 ret = lua_getfield(L, -1, "reason");
8113 if (ret == LUA_TSTRING)
8114 reason = lua_tolstring(L, -1, &reason_len);
8115 lua_pop(L, 1);
8116
8117 body = NULL;
8118 body_len = 0;
8119 ret = lua_getfield(L, -1, "body");
8120 if (ret == LUA_TSTRING)
8121 body = lua_tolstring(L, -1, &body_len);
8122 lua_pop(L, 1);
8123
8124 /* Prepare the response before inserting the headers */
8125 h1m_init_res(&h1m);
8126 htx = htx_from_buf(&s->res.buf);
8127 channel_htx_truncate(&s->res, htx);
8128 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8129 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8130 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8131 ist2(status, status_len), ist2(reason, reason_len));
8132 }
8133 else {
8134 flags = HTX_SL_F_IS_RESP;
8135 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8136 ist2(status, status_len), ist2(reason, reason_len));
8137 }
8138 if (!sl)
8139 goto fail;
8140 sl->info.res.status = code;
8141
8142 /* Push in the stack the "headers" entry. */
8143 ret = lua_getfield(L, -1, "headers");
8144 if (ret != LUA_TTABLE)
8145 goto skip_headers;
8146
8147 lua_pushnil(L);
8148 while (lua_next(L, -2) != 0) {
8149 struct ist name, value;
8150 const char *n, *v;
8151 size_t nlen, vlen;
8152
8153 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8154 /* Skip element if the key is not a string or if the value is not a table */
8155 goto next_hdr;
8156 }
8157
8158 n = lua_tolstring(L, -2, &nlen);
8159 name = ist2(n, nlen);
8160 if (isteqi(name, ist("content-length"))) {
8161 /* Always skip content-length header. It will be added
8162 * later with the correct len
8163 */
8164 goto next_hdr;
8165 }
8166
8167 /* Loop on header's values */
8168 lua_pushnil(L);
8169 while (lua_next(L, -2)) {
8170 if (!lua_isstring(L, -1)) {
8171 /* Skip the value if it is not a string */
8172 goto next_value;
8173 }
8174
8175 v = lua_tolstring(L, -1, &vlen);
8176 value = ist2(v, vlen);
8177
8178 if (isteqi(name, ist("transfer-encoding")))
8179 h1_parse_xfer_enc_header(&h1m, value);
8180 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8181 goto fail;
8182
8183 next_value:
8184 lua_pop(L, 1);
8185 }
8186
8187 next_hdr:
8188 lua_pop(L, 1);
8189 }
8190 skip_headers:
8191 lua_pop(L, 1);
8192
8193 /* Update h1m flags: CLEN is set if CHNK is not present */
8194 if (!(h1m.flags & H1_MF_CHNK)) {
8195 const char *clen = ultoa(body_len);
8196
8197 h1m.flags |= H1_MF_CLEN;
8198 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8199 goto fail;
8200 }
8201 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8202 h1m.flags |= H1_MF_XFER_LEN;
8203
8204 /* Update HTX start-line flags */
8205 if (h1m.flags & H1_MF_XFER_ENC)
8206 flags |= HTX_SL_F_XFER_ENC;
8207 if (h1m.flags & H1_MF_XFER_LEN) {
8208 flags |= HTX_SL_F_XFER_LEN;
8209 if (h1m.flags & H1_MF_CHNK)
8210 flags |= HTX_SL_F_CHNK;
8211 else if (h1m.flags & H1_MF_CLEN)
8212 flags |= HTX_SL_F_CLEN;
8213 if (h1m.body_len == 0)
8214 flags |= HTX_SL_F_BODYLESS;
8215 }
8216 sl->flags |= flags;
8217
8218
8219 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008220 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008221 goto fail;
8222
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008223 htx->flags |= HTX_FL_EOM;
8224
Christopher Faulet700d9e82020-01-31 12:21:52 +01008225 /* Now, forward the response and terminate the transaction */
8226 s->txn->status = code;
8227 htx_to_buf(htx, &s->res.buf);
8228 if (!http_forward_proxy_resp(s, 1))
8229 goto fail;
8230
8231 return 1;
8232
8233 fail:
8234 channel_htx_truncate(&s->res, htx);
8235 return 0;
8236}
8237
8238/* Terminate a transaction if called from a lua action. For TCP streams,
8239 * processing is just aborted. Nothing is returned to the client and all
8240 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8241 * is forwarded to the client before terminating the transaction. On success,
8242 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8243 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8244 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008245 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008246__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008247{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008248 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008249 struct stream *s;
8250 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008251
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008252 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008253
Christopher Faulet700d9e82020-01-31 12:21:52 +01008254 /* If the flags NOTERM is set, we cannot terminate the session, so we
8255 * just end the execution of the current lua code. */
8256 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008257 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008258
Christopher Faulet700d9e82020-01-31 12:21:52 +01008259 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008260 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008261 struct channel *req = &s->req;
8262 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008263
Christopher Faulet700d9e82020-01-31 12:21:52 +01008264 channel_auto_read(req);
8265 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008266 channel_erase(req);
8267
Christopher Faulet700d9e82020-01-31 12:21:52 +01008268 channel_auto_read(res);
8269 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008270 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008271
8272 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8273 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008274 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008275
Christopher Faulet700d9e82020-01-31 12:21:52 +01008276 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8277 /* No reply or invalid reply */
8278 s->txn->status = 0;
8279 http_reply_and_close(s, 0, NULL);
8280 }
8281 else {
8282 /* Remove extra args to have the reply on top of the stack */
8283 if (lua_gettop(L) > 2)
8284 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008285
Christopher Faulet700d9e82020-01-31 12:21:52 +01008286 if (!hlua_txn_forward_reply(L, s)) {
8287 if (!(s->flags & SF_ERR_MASK))
8288 s->flags |= SF_ERR_PRXCOND;
8289 lua_pushinteger(L, ACT_RET_ERR);
8290 WILL_LJMP(hlua_done(L));
8291 return 0; /* Never reached */
8292 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008293 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008294
Christopher Faulet700d9e82020-01-31 12:21:52 +01008295 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8296 if (htxn->dir == SMP_OPT_DIR_REQ) {
8297 /* let's log the request time */
8298 s->logs.tv_request = now;
8299 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008300 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008301 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008302
Christopher Faulet700d9e82020-01-31 12:21:52 +01008303 done:
8304 if (!(s->flags & SF_ERR_MASK))
8305 s->flags |= SF_ERR_LOCAL;
8306 if (!(s->flags & SF_FINST_MASK))
8307 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008308
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008309 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8310 lua_pushinteger(L, -1);
8311 else
8312 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008313 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008314 return 0;
8315}
8316
Christopher Faulet700d9e82020-01-31 12:21:52 +01008317/*
8318 *
8319 *
8320 * Class REPLY
8321 *
8322 *
8323 */
8324
8325/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8326 * free slots, the function fails and returns 0;
8327 */
8328static int hlua_txn_reply_new(lua_State *L)
8329{
8330 struct hlua_txn *htxn;
8331 const char *reason, *body = NULL;
8332 int ret, status;
8333
8334 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008335 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008336 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8337 WILL_LJMP(lua_error(L));
8338 }
8339
8340 /* Default value */
8341 status = 200;
8342 reason = http_get_reason(status);
8343
8344 if (lua_istable(L, 2)) {
8345 /* load status and reason from the table argument at index 2 */
8346 ret = lua_getfield(L, 2, "status");
8347 if (ret == LUA_TNIL)
8348 goto reason;
8349 else if (ret != LUA_TNUMBER) {
8350 /* invalid status: ignore the reason */
8351 goto body;
8352 }
8353 status = lua_tointeger(L, -1);
8354
8355 reason:
8356 lua_pop(L, 1); /* restore the stack: remove status */
8357 ret = lua_getfield(L, 2, "reason");
8358 if (ret == LUA_TSTRING)
8359 reason = lua_tostring(L, -1);
8360
8361 body:
8362 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8363 ret = lua_getfield(L, 2, "body");
8364 if (ret == LUA_TSTRING)
8365 body = lua_tostring(L, -1);
8366 lua_pop(L, 1); /* restore the stack: remove body */
8367 }
8368
8369 /* Create the Reply table */
8370 lua_newtable(L);
8371
8372 /* Add status element */
8373 lua_pushstring(L, "status");
8374 lua_pushinteger(L, status);
8375 lua_settable(L, -3);
8376
8377 /* Add reason element */
8378 reason = http_get_reason(status);
8379 lua_pushstring(L, "reason");
8380 lua_pushstring(L, reason);
8381 lua_settable(L, -3);
8382
8383 /* Add body element, nil if undefined */
8384 lua_pushstring(L, "body");
8385 if (body)
8386 lua_pushstring(L, body);
8387 else
8388 lua_pushnil(L);
8389 lua_settable(L, -3);
8390
8391 /* Add headers element */
8392 lua_pushstring(L, "headers");
8393 lua_newtable(L);
8394
8395 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8396 if (lua_istable(L, 2)) {
8397 /* load headers from the table argument at index 2. If it is a table, copy it. */
8398 ret = lua_getfield(L, 2, "headers");
8399 if (ret == LUA_TTABLE) {
8400 /* stack: [ ... <headers:table>, <table> ] */
8401 lua_pushnil(L);
8402 while (lua_next(L, -2) != 0) {
8403 /* stack: [ ... <headers:table>, <table>, k, v] */
8404 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8405 /* invalid value type, skip it */
8406 lua_pop(L, 1);
8407 continue;
8408 }
8409
8410
8411 /* Duplicate the key and swap it with the value. */
8412 lua_pushvalue(L, -2);
8413 lua_insert(L, -2);
8414 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8415
8416 lua_newtable(L);
8417 lua_insert(L, -2);
8418 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8419
8420 if (lua_isstring(L, -1)) {
8421 /* push the value in the inner table */
8422 lua_rawseti(L, -2, 1);
8423 }
8424 else { /* table */
8425 lua_pushnil(L);
8426 while (lua_next(L, -2) != 0) {
8427 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8428 if (!lua_isstring(L, -1)) {
8429 /* invalid value type, skip it*/
8430 lua_pop(L, 1);
8431 continue;
8432 }
8433 /* push the value in the inner table */
8434 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8435 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8436 }
8437 lua_pop(L, 1);
8438 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8439 }
8440
8441 /* push (k,v) on the stack in the headers table:
8442 * stack: [ ... <headers:table>, <table>, k, k, v ]
8443 */
8444 lua_settable(L, -5);
8445 /* stack: [ ... <headers:table>, <table>, k ] */
8446 }
8447 }
8448 lua_pop(L, 1);
8449 }
8450 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8451 lua_settable(L, -3);
8452 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8453
8454 /* Pop a class sesison metatable and affect it to the userdata. */
8455 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8456 lua_setmetatable(L, -2);
8457 return 1;
8458}
8459
8460/* Set the reply status code, and optionally the reason. If no reason is
8461 * provided, the default one corresponding to the status code is used.
8462 */
8463__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8464{
8465 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8466 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8467
8468 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008469 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008470
8471 if (status < 100 || status > 599) {
8472 lua_pushboolean(L, 0);
8473 return 1;
8474 }
8475 if (!reason)
8476 reason = http_get_reason(status);
8477
8478 lua_pushinteger(L, status);
8479 lua_setfield(L, 1, "status");
8480
8481 lua_pushstring(L, reason);
8482 lua_setfield(L, 1, "reason");
8483
8484 lua_pushboolean(L, 1);
8485 return 1;
8486}
8487
8488/* Add a header into the reply object. Each header name is associated to an
8489 * array of values in the "headers" table. If the header name is not found, a
8490 * new entry is created.
8491 */
8492__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8493{
8494 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8495 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8496 int ret;
8497
8498 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008499 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008500
8501 /* Push in the stack the "headers" entry. */
8502 ret = lua_getfield(L, 1, "headers");
8503 if (ret != LUA_TTABLE) {
8504 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8505 WILL_LJMP(lua_error(L));
8506 }
8507
8508 /* check if the header is already registered. If not, register it. */
8509 ret = lua_getfield(L, -1, name);
8510 if (ret == LUA_TNIL) {
8511 /* Entry not found. */
8512 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8513
8514 /* Insert the new header name in the array in the top of the stack.
8515 * It left the new array in the top of the stack.
8516 */
8517 lua_newtable(L);
8518 lua_pushstring(L, name);
8519 lua_pushvalue(L, -2);
8520 lua_settable(L, -4);
8521 }
8522 else if (ret != LUA_TTABLE) {
8523 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8524 WILL_LJMP(lua_error(L));
8525 }
8526
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008527 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008528 * the header value as new entry.
8529 */
8530 lua_pushstring(L, value);
8531 ret = lua_rawlen(L, -2);
8532 lua_rawseti(L, -2, ret + 1);
8533
8534 lua_pushboolean(L, 1);
8535 return 1;
8536}
8537
8538/* Remove all occurrences of a given header name. */
8539__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8540{
8541 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8542 int ret;
8543
8544 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008545 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008546
8547 /* Push in the stack the "headers" entry. */
8548 ret = lua_getfield(L, 1, "headers");
8549 if (ret != LUA_TTABLE) {
8550 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8551 WILL_LJMP(lua_error(L));
8552 }
8553
8554 lua_pushstring(L, name);
8555 lua_pushnil(L);
8556 lua_settable(L, -3);
8557
8558 lua_pushboolean(L, 1);
8559 return 1;
8560}
8561
8562/* Set the reply's body. Overwrite any existing entry. */
8563__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8564{
8565 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8566
8567 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008568 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008569
8570 lua_pushstring(L, payload);
8571 lua_setfield(L, 1, "body");
8572
8573 lua_pushboolean(L, 1);
8574 return 1;
8575}
8576
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008577__LJMP static int hlua_log(lua_State *L)
8578{
8579 int level;
8580 const char *msg;
8581
8582 MAY_LJMP(check_args(L, 2, "log"));
8583 level = MAY_LJMP(luaL_checkinteger(L, 1));
8584 msg = MAY_LJMP(luaL_checkstring(L, 2));
8585
8586 if (level < 0 || level >= NB_LOG_LEVELS)
8587 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8588
8589 hlua_sendlog(NULL, level, msg);
8590 return 0;
8591}
8592
8593__LJMP static int hlua_log_debug(lua_State *L)
8594{
8595 const char *msg;
8596
8597 MAY_LJMP(check_args(L, 1, "debug"));
8598 msg = MAY_LJMP(luaL_checkstring(L, 1));
8599 hlua_sendlog(NULL, LOG_DEBUG, msg);
8600 return 0;
8601}
8602
8603__LJMP static int hlua_log_info(lua_State *L)
8604{
8605 const char *msg;
8606
8607 MAY_LJMP(check_args(L, 1, "info"));
8608 msg = MAY_LJMP(luaL_checkstring(L, 1));
8609 hlua_sendlog(NULL, LOG_INFO, msg);
8610 return 0;
8611}
8612
8613__LJMP static int hlua_log_warning(lua_State *L)
8614{
8615 const char *msg;
8616
8617 MAY_LJMP(check_args(L, 1, "warning"));
8618 msg = MAY_LJMP(luaL_checkstring(L, 1));
8619 hlua_sendlog(NULL, LOG_WARNING, msg);
8620 return 0;
8621}
8622
8623__LJMP static int hlua_log_alert(lua_State *L)
8624{
8625 const char *msg;
8626
8627 MAY_LJMP(check_args(L, 1, "alert"));
8628 msg = MAY_LJMP(luaL_checkstring(L, 1));
8629 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008630 return 0;
8631}
8632
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008633__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008634{
8635 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008636 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008637 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008638 return 0;
8639}
8640
8641__LJMP static int hlua_sleep(lua_State *L)
8642{
8643 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008644 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008645
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008646 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008647
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008648 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008649 wakeup_ms = tick_add(now_ms, delay);
8650 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008651
Willy Tarreau9635e032018-10-16 17:52:55 +02008652 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008653 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008654}
8655
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008656__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008657{
8658 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008659 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008660
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008661 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008662
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008663 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008664 wakeup_ms = tick_add(now_ms, delay);
8665 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008666
Willy Tarreau9635e032018-10-16 17:52:55 +02008667 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008668 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008669}
8670
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008671/* This functionis an LUA binding. it permits to give back
8672 * the hand at the HAProxy scheduler. It is used when the
8673 * LUA processing consumes a lot of time.
8674 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008675__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008676{
8677 return 0;
8678}
8679
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008680__LJMP static int hlua_yield(lua_State *L)
8681{
Willy Tarreau9635e032018-10-16 17:52:55 +02008682 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008683 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008684}
8685
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008686/* This function change the nice of the currently executed
8687 * task. It is used set low or high priority at the current
8688 * task.
8689 */
Willy Tarreau59551662015-03-10 14:23:13 +01008690__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008691{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008692 struct hlua *hlua;
8693 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008694
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008695 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008696 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008697
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008698 /* Get hlua struct, or NULL if we execute from main lua state */
8699 hlua = hlua_gethlua(L);
8700
8701 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008702 if (!hlua || !hlua->task)
8703 return 0;
8704
8705 if (nice < -1024)
8706 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008707 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008708 nice = 1024;
8709
8710 hlua->task->nice = nice;
8711 return 0;
8712}
8713
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +02008714/* safe lua coroutine.create() function:
8715 *
8716 * This is a simple wrapper for coroutine.create() that
8717 * ensures the current hlua state ctx is available from
8718 * the new subroutine state
8719 */
8720__LJMP static int hlua_coroutine_create(lua_State *L)
8721{
8722 lua_State *new; /* new coroutine state */
8723 struct hlua **hlua_store;
8724 struct hlua *hlua = hlua_gethlua(L);
8725
8726 new = lua_newthread(L);
8727 if (!new)
8728 return 0;
8729
8730 hlua_store = lua_getextraspace(new);
8731 /* Expose current hlua ctx on new lua thread
8732 * (hlua_gethlua() will properly return the last "known"
8733 * hlua ctx instead of NULL when it is called from such coroutines)
8734 */
8735 *hlua_store = hlua;
8736
8737 /* new lua thread is on the top of the stack, we
8738 * need to duplicate first stack argument (<f> from coroutine.create(<f>))
8739 * on the top of the stack to be able to use xmove() to move it on the new
8740 * stack
8741 */
8742 lua_pushvalue(L, 1);
8743 /* move <f> function to the new stack */
8744 lua_xmove(L, new, 1);
8745 /* new lua thread is back at the top of the stack */
8746 return 1;
8747}
8748
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008749/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008750 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8751 * return an E_AGAIN signal, the emmiter of this signal must set a
8752 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008753 *
8754 * Task wrapper are longjmp safe because the only one Lua code
8755 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008756 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008757struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008758{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008759 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008760 enum hlua_exec status;
8761
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008762 if (task->tid < 0)
8763 task->tid = tid;
8764
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008765 /* If it is the first call to the task, we must initialize the
8766 * execution timeouts.
8767 */
8768 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008769 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008770
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008771 /* Execute the Lua code. */
8772 status = hlua_ctx_resume(hlua, 1);
8773
8774 switch (status) {
8775 /* finished or yield */
8776 case HLUA_E_OK:
8777 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008778 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008779 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008780 break;
8781
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008782 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008783 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008784 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008785 break;
8786
8787 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008788 case HLUA_E_ETMOUT:
8789 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8790 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008791 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008792 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008793 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008794 case HLUA_E_ERR:
8795 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008796 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008797 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008798 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008799 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008800 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008801 break;
8802 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008803 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008804}
8805
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008806/* This function is an LUA binding that register LUA function to be
8807 * executed after the HAProxy configuration parsing and before the
8808 * HAProxy scheduler starts. This function expect only one LUA
8809 * argument that is a function. This function returns nothing, but
8810 * throws if an error is encountered.
8811 */
8812__LJMP static int hlua_register_init(lua_State *L)
8813{
8814 struct hlua_init_function *init;
8815 int ref;
8816
8817 MAY_LJMP(check_args(L, 1, "register_init"));
8818
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008819 if (hlua_gethlua(L)) {
8820 /* runtime processing */
8821 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8822 }
8823
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008824 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8825
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008826 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008827 if (!init) {
8828 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008829 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008830 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008831
8832 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008833 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008834 return 0;
8835}
8836
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008837/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008838 * executed in parallel of the main HAroxy activity. The task is
8839 * created and it is set in the HAProxy scheduler. It can be called
8840 * from the "init" section, "post init" or during the runtime.
8841 *
8842 * Lua prototype:
8843 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008844 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8845 *
8846 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008847 */
8848static int hlua_register_task(lua_State *L)
8849{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008850 struct hlua *hlua = NULL;
8851 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008852 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008853 int nb_arg;
8854 int it;
8855 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008856 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008857
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008858 nb_arg = lua_gettop(L);
8859 if (nb_arg < 1)
8860 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8861 else if (nb_arg > 5)
8862 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008863
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008864 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008865 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8866
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008867 /* extract optional args (if any) */
8868 it = 0;
8869 while (--nb_arg) {
8870 lua_pushvalue(L, 2 + it);
8871 arg_ref[it] = hlua_ref(L); /* get arg reference */
8872 it += 1;
8873 }
8874 nb_arg = it;
8875
Thierry Fournier75fc0292020-11-28 13:18:56 +01008876 /* Get the reference state. If the reference is NULL, L is the master
8877 * state, otherwise hlua->T is.
8878 */
8879 hlua = hlua_gethlua(L);
8880 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008881 /* we are in runtime processing */
8882 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008883 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008884 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008885 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008886
Willy Tarreaubafbe012017-11-24 17:34:44 +01008887 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008888 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008889 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008890 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008891
Thierry Fournier59f11be2020-11-29 00:37:41 +01008892 /* We are in the common lua state, execute the task anywhere,
8893 * otherwise, inherit the current thread identifier
8894 */
8895 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008896 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008897 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008898 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008899 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008900 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008901
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008902 task->context = hlua;
8903 task->process = hlua_process_task;
8904
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008905 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008906 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008907
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008908 /* Ensure there is enough space on the stack for the function
8909 * plus optional arguments
8910 */
8911 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8912 goto alloc_error;
8913
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008914 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008915 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008916 /* function ref not needed anymore since it was pushed to the substack */
8917 hlua_unref(L, ref);
8918
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008919 hlua->nargs = nb_arg;
8920
8921 /* push optional arguments to the function */
8922 for (it = 0; it < nb_arg; it++) {
8923 /* push arg to the stack */
8924 hlua_pushref(hlua->T, arg_ref[it]);
8925 /* arg ref not needed anymore since it was pushed to the substack */
8926 hlua_unref(L, arg_ref[it]);
8927 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008928
8929 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008930 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008931
8932 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008933
8934 alloc_error:
8935 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008936 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008937 for (it = 0; it < nb_arg; it++) {
8938 hlua_unref(L, arg_ref[it]);
8939 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008940 hlua_ctx_destroy(hlua);
8941 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8942 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008943}
8944
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008945/* called from unsafe location */
8946static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
8947{
8948 /* hlua cleanup */
8949
8950 hlua_lock(hlua_sub->hlua);
8951 /* registry is shared between coroutines */
8952 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
8953 hlua_unlock(hlua_sub->hlua);
8954
8955 hlua_ctx_destroy(hlua_sub->hlua);
8956
8957 /* free */
8958 pool_free(pool_head_hlua_event_sub, hlua_sub);
8959}
8960
8961/* single event handler: hlua ctx is shared between multiple events handlers
8962 * issued from the same subscription. Thus, it is not destroyed when the event
8963 * is processed: it is destroyed when no more events are expected for the
8964 * subscription (ie: when the subscription ends).
8965 *
8966 * Moreover, events are processed sequentially within the subscription:
8967 * one event must be fully processed before another one may be processed.
8968 * This ensures proper consistency for lua event handling from an ordering
8969 * point of view. This is especially useful with server events for example
8970 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
8971 * actions from lua (e.g.: sending emails or making API calls).
8972 *
8973 * Due to this design, each lua event handler is pleased to process the event
8974 * as fast as possible to prevent the event queue from growing up.
8975 * Strictly speaking, there is no runtime limit for the callback function
8976 * (timeout set to default task timeout), but if the event queue goes past
8977 * the limit of unconsumed events an error will be reported and the
8978 * susbscription will pause itself for as long as it takes for the handler to
8979 * catch up (events will be lost as a result).
8980 * If the event handler does not need the sequential ordering and wants to
8981 * process multiple events at a time, it may spawn a new side-task using
8982 * 'core.register_task' to delegate the event handling and make parallel event
8983 * processing within the same subscription set.
8984 */
8985static void hlua_event_handler(struct hlua *hlua)
8986{
8987 enum hlua_exec status;
8988
8989 /* If it is the first call to the task, we must initialize the
8990 * execution timeouts.
8991 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008992 if (!HLUA_IS_RUNNING(hlua))
8993 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01008994
8995 /* make sure to reset the task expiry before each hlua_ctx_resume()
8996 * since the task is re-used for multiple cb function calls
8997 * We couldn't risk to have t->expire pointing to a past date because
8998 * it was set during last function invocation but was never reset since
8999 * (ie: E_AGAIN)
9000 */
9001 hlua->task->expire = TICK_ETERNITY;
9002
9003 /* Execute the Lua code. */
9004 status = hlua_ctx_resume(hlua, 1);
9005
9006 switch (status) {
9007 /* finished or yield */
9008 case HLUA_E_OK:
9009 break;
9010
9011 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
9012 notification_gc(&hlua->com);
9013 hlua->task->expire = hlua->wake_time;
9014 break;
9015
9016 /* finished with error. */
9017 case HLUA_E_ETMOUT:
9018 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
9019 break;
9020
9021 case HLUA_E_ERRMSG:
9022 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
9023 break;
9024
9025 case HLUA_E_ERR:
9026 default:
9027 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
9028 break;
9029 }
9030}
9031
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009032/* This function pushes various arguments such as event type and event data to
9033 * the lua function that will be called to consume the event.
9034 */
9035__LJMP static void hlua_event_hdl_cb_push_args(struct hlua_event_sub *hlua_sub,
9036 struct event_hdl_async_event *e)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009037{
9038 struct hlua *hlua = hlua_sub->hlua;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009039 struct event_hdl_sub_type event = e->type;
9040 void *data = e->data;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009041
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009042 /* push event type */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009043 hlua->nargs = 1;
9044 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009045
9046 /* push event data (according to event type) */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009047 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
9048 struct event_hdl_cb_data_server *e_server = data;
9049 struct proxy *px;
9050 struct server *server;
9051
9052 hlua->nargs += 1;
9053 lua_newtable(hlua->T);
9054 /* Add server name */
9055 lua_pushstring(hlua->T, "name");
9056 lua_pushstring(hlua->T, e_server->safe.name);
9057 lua_settable(hlua->T, -3);
9058 /* Add server puid */
9059 lua_pushstring(hlua->T, "puid");
9060 lua_pushinteger(hlua->T, e_server->safe.puid);
9061 lua_settable(hlua->T, -3);
9062 /* Add server rid */
9063 lua_pushstring(hlua->T, "rid");
9064 lua_pushinteger(hlua->T, e_server->safe.rid);
9065 lua_settable(hlua->T, -3);
9066 /* Add server proxy name */
9067 lua_pushstring(hlua->T, "proxy_name");
9068 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9069 lua_settable(hlua->T, -3);
Aurelien DARRAGON55f84c72023-03-22 17:49:04 +01009070 /* Add server proxy uuid */
9071 lua_pushstring(hlua->T, "proxy_uuid");
9072 lua_pushinteger(hlua->T, e_server->safe.proxy_uuid);
9073 lua_settable(hlua->T, -3);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009074
9075 /* attempt to provide reference server object
9076 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9077 */
Aurelien DARRAGON3d9bf4e2023-03-22 17:46:12 +01009078 px = proxy_find_by_id(e_server->safe.proxy_uuid, PR_CAP_BE, 0);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009079 BUG_ON(!px);
9080 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9081 if (server) {
9082 lua_pushstring(hlua->T, "reference");
9083 hlua_fcn_new_server(hlua->T, server);
9084 lua_settable(hlua->T, -3);
9085 }
9086 }
9087 /* sub mgmt */
9088 hlua->nargs += 1;
9089 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
Aurelien DARRAGON096b3832023-04-20 11:32:46 +02009090
9091 /* when? */
9092 hlua->nargs += 1;
9093 lua_pushinteger(hlua->T, e->when.tv_sec);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009094}
9095
9096/* events runner: if there's an ongoing hlua event handling process, finish it
9097 * then, check if there are new events waiting to be processed
9098 * (events are processed sequentially)
9099 *
9100 * We have a safety measure to warn/guard if the event queue is growing up
9101 * too much due to many events being generated and lua handler is unable to
9102 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9103 * TODO: make it tunable
9104 */
9105static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9106{
9107 struct hlua_event_sub *hlua_sub = context;
9108 struct event_hdl_async_event *event;
9109 const char *error = NULL;
9110
9111 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
9112 const char *trace;
9113
9114 /* We reached the limit of pending events in the queue: we should
9115 * warn the user, and temporarily pause the subscription to give a chance
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009116 * to the handler to catch up? (it also prevents resource shortage since
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009117 * the queue could grow indefinitely otherwise)
9118 * TODO: find a way to inform the handler that it missed some events
9119 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9120 *
9121 * Nonetheless, reaching this limit means that the handler is not fast enough
9122 * and/or that it subscribed to events that happen too frequently and did not
9123 * expect it. This could come from an inadequate design in the user's script.
9124 */
9125 event_hdl_pause(hlua_sub->sub);
9126 hlua_sub->paused = 1;
9127
9128 /* The following Lua calls can fail. */
9129 if (!SET_SAFE_LJMP(hlua_sub->hlua))
9130 trace = NULL;
9131 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9132 /* At this point the execution is safe. */
9133 RESET_SAFE_LJMP(hlua_sub->hlua);
9134
9135 ha_warning("Lua event_hdl: pausing the subscription because the function fails to keep up the pace (%u unconsumed events): %s\n", event_hdl_async_equeue_size(&hlua_sub->equeue), ((trace) ? trace : ""));
9136 }
9137
9138 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9139 /* ongoing hlua event handler, resume it */
9140 hlua_event_handler(hlua_sub->hlua);
9141 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9142 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9143 /* ending event: no more events to come */
9144 event_hdl_async_free_event(event);
9145 task_destroy(task);
9146 hlua_event_subscription_destroy(hlua_sub);
9147 return NULL;
9148 }
9149 /* new event: start processing it */
9150
9151 /* The following Lua calls can fail. */
9152 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9153 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9154 error = lua_tostring(hlua_sub->hlua->T, -1);
9155 else
9156 error = "critical error";
9157 ha_alert("Lua event_hdl: %s.\n", error);
9158 goto skip_event;
9159 }
9160
9161 /* Check stack available size. */
9162 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9163 ha_alert("Lua event_hdl: full stack.\n");
9164 RESET_SAFE_LJMP(hlua_sub->hlua);
9165 goto skip_event;
9166 }
9167
9168 /* Restore the function in the stack. */
9169 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9170
9171 /* push args */
9172 hlua_sub->hlua->nargs = 0;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009173 MAY_LJMP(hlua_event_hdl_cb_push_args(hlua_sub, event));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009174
9175 /* At this point the execution is safe. */
9176 RESET_SAFE_LJMP(hlua_sub->hlua);
9177
9178 /* At this point the event was successfully translated into hlua ctx,
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009179 * or hlua error occurred, so we can safely discard it
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009180 */
9181 event_hdl_async_free_event(event);
9182 event = NULL;
9183
9184 hlua_event_handler(hlua_sub->hlua);
9185 skip_event:
9186 if (event)
9187 event_hdl_async_free_event(event);
9188
9189 }
9190
9191 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9192 /* we just finished the processing of one event..
9193 * check for new events before becoming idle
9194 */
9195 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9196 /* more events to process, make sure the task
9197 * will be resumed ASAP to process pending events
9198 */
9199 task_wakeup(task, TASK_WOKEN_OTHER);
9200 }
9201 else if (hlua_sub->paused) {
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009202 /* empty queue, the handler caught up: resume the subscription */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009203 event_hdl_resume(hlua_sub->sub);
9204 hlua_sub->paused = 0;
9205 }
9206 }
9207
9208 return task;
9209}
9210
9211/* Must be called directly under lua protected/safe environment
9212 * (not from external callback)
9213 * <fcn_ref> should NOT be dropped after the function successfully returns:
9214 * it will be done automatically in hlua_event_subscription_destroy() when the
9215 * subscription ends.
9216 *
9217 * Returns the new subscription on success and NULL on failure (memory error)
9218 */
9219static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9220 int state_id, int fcn_ref)
9221{
9222 struct hlua_event_sub *hlua_sub;
9223 struct task *task = NULL;
9224
9225 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9226 if (!hlua_sub)
9227 goto mem_error;
9228 hlua_sub->task = NULL;
9229 hlua_sub->hlua = NULL;
9230 hlua_sub->paused = 0;
9231 if ((task = task_new_here()) == NULL) {
9232 ha_alert("out of memory while allocating hlua event task");
9233 goto mem_error;
9234 }
9235 task->process = hlua_event_runner;
9236 task->context = hlua_sub;
9237 event_hdl_async_equeue_init(&hlua_sub->equeue);
9238 hlua_sub->task = task;
9239 hlua_sub->fcn_ref = fcn_ref;
9240 hlua_sub->state_id = state_id;
9241 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9242 if (!hlua_sub->hlua)
9243 goto mem_error;
9244 HLUA_INIT(hlua_sub->hlua);
9245 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9246 goto mem_error;
9247
9248 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9249 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9250 task,
9251 hlua_sub,
9252 NULL));
9253 if (!hlua_sub->sub)
9254 goto mem_error;
9255
9256 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9257
9258 mem_error:
9259 if (hlua_sub) {
Tim Duesterhusfe83f582023-04-22 17:47:34 +02009260 task_destroy(hlua_sub->task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009261 if (hlua_sub->hlua)
9262 hlua_ctx_destroy(hlua_sub->hlua);
9263 pool_free(pool_head_hlua_event_sub, hlua_sub);
9264 }
9265
9266 return NULL;
9267}
9268
9269/* looks for an array of strings referring to a composition of event_hdl subscription
9270 * types at <index> in <L> stack
9271 */
9272__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9273{
9274 struct event_hdl_sub_type subscriptions;
9275 const char *msg;
9276
9277 if (lua_type(L, index) != LUA_TTABLE) {
9278 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9279 luaL_argerror(L, index, msg);
9280 }
9281
9282 subscriptions = EVENT_HDL_SUB_NONE;
9283
9284 /* browse the argument as an array. */
9285 lua_pushnil(L);
9286 while (lua_next(L, index) != 0) {
9287 if (lua_type(L, -1) != LUA_TSTRING) {
9288 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9289 luaL_argerror(L, index, msg);
9290 }
9291
9292 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9293 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9294 luaL_argerror(L, index, msg);
9295 }
9296
9297 /* perform subscriptions |= current sub */
9298 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9299
9300 /* pop the current value. */
9301 lua_pop(L, 1);
9302 }
9303
9304 return subscriptions;
9305}
9306
9307/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9308 * the function to prevent LJMP
9309 *
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009310 * If no error occurred, the function returns 1, else it returns 0 and
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009311 * the error message is pushed at the top of the stack
9312 */
9313__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9314{
9315 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9316
9317 /* this function may raise errors */
9318 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9319}
9320static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9321{
9322 if (!lua_checkstack(L, 2))
9323 return 0;
9324 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9325 lua_pushlightuserdata(L, sub);
9326 switch (lua_pcall(L, 1, 1, 0)) {
9327 case LUA_OK:
9328 return 1;
9329 default:
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009330 /* error was caught */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009331 return 0;
9332 }
9333}
9334
9335/* This function is a LUA helper used for registering lua event callbacks.
9336 * It expects an event subscription array and the function to be executed
9337 * when subscribed events occur (stack arguments).
9338 * It can be called from the "init" section, "post init" or during the runtime.
9339 *
9340 * <sub_list> is the subscription list where the subscription will be attempted
9341 *
9342 * Pushes the newly allocated subscription on the stack on success
9343 */
9344__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9345{
9346 struct hlua *hlua;
9347 struct event_hdl_sub *sub;
9348 struct event_hdl_sub_type subscriptions;
9349 int fcn_ref;
9350 int state_id;
9351
9352 MAY_LJMP(check_args(L, 2, "event_sub"));
9353
9354 /* Get the reference state */
9355 hlua = hlua_gethlua(L);
9356 if (hlua)
9357 /* we are in runtime processing, any thread may subscribe to events:
9358 * subscription events will be handled by the thread who performed
9359 * the registration.
9360 */
9361 state_id = hlua->state_id;
9362 else {
9363 /* we are in initialization mode, only thread 0 (actual calling thread)
9364 * may subscribe to events to prevent the same handler (from different lua
9365 * stacks) from being registered multiple times
9366 *
9367 * hlua_state_id == 0: monostack (lua-load)
9368 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9369 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9370 */
9371 if (hlua_state_id > 1)
9372 return 0; /* skip registration */
9373 state_id = hlua_state_id;
9374 }
9375
9376 /* First argument : event subscriptions. */
9377 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9378
9379 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9380 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9381 return 0; /* Never reached */
9382 }
9383
9384 /* Second argument : lua function. */
9385 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9386
9387 /* try to subscribe */
9388 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9389 if (!sub) {
9390 hlua_unref(L, fcn_ref);
9391 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9392 return 0; /* Never reached */
9393 }
9394
9395 /* push the subscription to the stack
9396 *
9397 * Here we use the safe function so that lua errors will be
9398 * handled explicitly to prevent 'sub' from being lost
9399 */
9400 if (!hlua_new_event_sub_safe(L, sub)) {
9401 /* Some events could already be pending in the handler's queue.
9402 * However it is wiser to cancel the subscription since we are unable to
9403 * provide a valid reference to it.
9404 * Pending events will be delivered (unless lua keeps raising errors).
9405 */
9406 event_hdl_unsubscribe(sub); /* cancel the subscription */
9407 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9408 return 0; /* Never reached */
9409 }
9410 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9411
9412 return 1;
9413}
9414
9415/* This function is a LUA wrapper used for registering global lua event callbacks
9416 * The new subscription is pushed onto the stack on success
9417 * Returns the number of arguments pushed to the stack (1 for success)
9418 */
9419__LJMP static int hlua_event_global_sub(lua_State *L)
9420{
9421 /* NULL <sub_list> = global subscription list */
9422 return MAY_LJMP(hlua_event_sub(L, NULL));
9423}
9424
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009425/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9426 * doesn't allow "yield" functions because the HAProxy engine cannot
9427 * resume converters.
9428 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009429static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009430{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009431 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009432 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009433 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009434
Willy Tarreaube508f12016-03-10 11:47:01 +01009435 if (!stream)
9436 return 0;
9437
Willy Tarreau87b09662015-04-03 00:22:06 +02009438 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009439 * Lua context can be not initialized. This behavior
9440 * permits to save performances because a systematic
9441 * Lua initialization cause 5% performances loss.
9442 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009443 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009444 struct hlua *hlua;
9445
9446 hlua = pool_alloc(pool_head_hlua);
9447 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009448 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9449 return 0;
9450 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009451 HLUA_INIT(hlua);
9452 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009453 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009454 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9455 return 0;
9456 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009457 }
9458
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009459 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009460 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009461
9462 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009463 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009464 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9465 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009466 else
9467 error = "critical error";
9468 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009469 return 0;
9470 }
9471
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009472 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009473 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009474 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009475 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009476 return 0;
9477 }
9478
9479 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009480 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009481
9482 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009483 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009484 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009485 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009486 return 0;
9487 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009488 hlua_smp2lua(stream->hlua->T, smp);
9489 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009490
9491 /* push keywords in the stack. */
9492 if (arg_p) {
9493 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009494 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009495 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009496 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009497 return 0;
9498 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009499 hlua_arg2lua(stream->hlua->T, arg_p);
9500 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009501 }
9502 }
9503
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009504 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009505 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009506
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009507 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009508 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009509 }
9510
9511 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009512 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009513 /* finished. */
9514 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009515 /* If the stack is empty, the function fails. */
9516 if (lua_gettop(stream->hlua->T) <= 0)
9517 return 0;
9518
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009519 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009520 hlua_lua2smp(stream->hlua->T, -1, smp);
9521 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009522 return 1;
9523
9524 /* yield. */
9525 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009526 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009527 return 0;
9528
9529 /* finished with error. */
9530 case HLUA_E_ERRMSG:
9531 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009532 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009533 fcn->name, lua_tostring(stream->hlua->T, -1));
9534 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009535 return 0;
9536
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009537 case HLUA_E_ETMOUT:
9538 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9539 return 0;
9540
9541 case HLUA_E_NOMEM:
9542 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9543 return 0;
9544
9545 case HLUA_E_YIELD:
9546 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9547 return 0;
9548
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009549 case HLUA_E_ERR:
9550 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009551 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009552 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009553
9554 default:
9555 return 0;
9556 }
9557}
9558
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009559/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9560 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009561 * resume sample-fetches. This function will be called by the sample
9562 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009563 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009564static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9565 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009566{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009567 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009568 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009569 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009570 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009571
Willy Tarreaube508f12016-03-10 11:47:01 +01009572 if (!stream)
9573 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009574
Willy Tarreau87b09662015-04-03 00:22:06 +02009575 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009576 * Lua context can be not initialized. This behavior
9577 * permits to save performances because a systematic
9578 * Lua initialization cause 5% performances loss.
9579 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009580 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009581 struct hlua *hlua;
9582
9583 hlua = pool_alloc(pool_head_hlua);
9584 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009585 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9586 return 0;
9587 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009588 hlua->T = NULL;
9589 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009590 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009591 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9592 return 0;
9593 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009594 }
9595
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009596 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009597 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009598
9599 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009600 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009601 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9602 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009603 else
9604 error = "critical error";
9605 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009606 return 0;
9607 }
9608
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009609 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009610 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009611 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009612 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009613 return 0;
9614 }
9615
9616 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009617 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009618
9619 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009620 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009621 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009622 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009623 return 0;
9624 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009625 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009626
9627 /* push keywords in the stack. */
9628 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9629 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009630 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009631 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009632 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009633 return 0;
9634 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009635 hlua_arg2lua(stream->hlua->T, arg_p);
9636 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009637 }
9638
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009639 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009640 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009641
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009642 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009643 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009644 }
9645
9646 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009647 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009648 /* finished. */
9649 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009650 /* If the stack is empty, the function fails. */
9651 if (lua_gettop(stream->hlua->T) <= 0)
9652 return 0;
9653
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009654 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009655 hlua_lua2smp(stream->hlua->T, -1, smp);
9656 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009657
9658 /* Set the end of execution flag. */
9659 smp->flags &= ~SMP_F_MAY_CHANGE;
9660 return 1;
9661
9662 /* yield. */
9663 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009664 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009665 return 0;
9666
9667 /* finished with error. */
9668 case HLUA_E_ERRMSG:
9669 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009670 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009671 fcn->name, lua_tostring(stream->hlua->T, -1));
9672 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009673 return 0;
9674
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009675 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009676 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9677 return 0;
9678
9679 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009680 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9681 return 0;
9682
9683 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009684 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9685 return 0;
9686
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009687 case HLUA_E_ERR:
9688 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009689 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009690 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009691
9692 default:
9693 return 0;
9694 }
9695}
9696
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009697/* This function is an LUA binding used for registering
9698 * "sample-conv" functions. It expects a converter name used
9699 * in the haproxy configuration file, and an LUA function.
9700 */
9701__LJMP static int hlua_register_converters(lua_State *L)
9702{
9703 struct sample_conv_kw_list *sck;
9704 const char *name;
9705 int ref;
9706 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009707 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009708 struct sample_conv *sc;
9709 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009710
9711 MAY_LJMP(check_args(L, 2, "register_converters"));
9712
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009713 if (hlua_gethlua(L)) {
9714 /* runtime processing */
9715 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9716 }
9717
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009718 /* First argument : converter name. */
9719 name = MAY_LJMP(luaL_checkstring(L, 1));
9720
9721 /* Second argument : lua function. */
9722 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9723
Thierry Fournierf67442e2020-11-28 20:41:07 +01009724 /* Check if the converter is already registered */
9725 trash = get_trash_chunk();
9726 chunk_printf(trash, "lua.%s", name);
9727 sc = find_sample_conv(trash->area, trash->data);
9728 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009729 fcn = sc->private;
9730 if (fcn->function_ref[hlua_state_id] != -1) {
9731 ha_warning("Trying to register converter 'lua.%s' more than once. "
9732 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009733 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009734 }
9735 fcn->function_ref[hlua_state_id] = ref;
9736 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009737 }
9738
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009739 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009740 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009741 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009742 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009743 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009744 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009745 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009746
9747 /* Fill fcn. */
9748 fcn->name = strdup(name);
9749 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009750 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009751 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009752
9753 /* List head */
9754 sck->list.n = sck->list.p = NULL;
9755
9756 /* converter keyword. */
9757 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009758 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009759 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009760 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009761
9762 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9763 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009764 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 +01009765 sck->kw[0].val_args = NULL;
9766 sck->kw[0].in_type = SMP_T_STR;
9767 sck->kw[0].out_type = SMP_T_STR;
9768 sck->kw[0].private = fcn;
9769
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009770 /* Register this new converter */
9771 sample_register_convs(sck);
9772
9773 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009774
9775 alloc_error:
9776 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009777 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +02009778 ha_free(&sck);
9779 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9780 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009781}
9782
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009783/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009784 * "sample-fetch" functions. It expects a converter name used
9785 * in the haproxy configuration file, and an LUA function.
9786 */
9787__LJMP static int hlua_register_fetches(lua_State *L)
9788{
9789 const char *name;
9790 int ref;
9791 int len;
9792 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009793 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009794 struct sample_fetch *sf;
9795 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009796
9797 MAY_LJMP(check_args(L, 2, "register_fetches"));
9798
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009799 if (hlua_gethlua(L)) {
9800 /* runtime processing */
9801 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
9802 }
9803
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009804 /* First argument : sample-fetch name. */
9805 name = MAY_LJMP(luaL_checkstring(L, 1));
9806
9807 /* Second argument : lua function. */
9808 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9809
Thierry Fournierf67442e2020-11-28 20:41:07 +01009810 /* Check if the sample-fetch is already registered */
9811 trash = get_trash_chunk();
9812 chunk_printf(trash, "lua.%s", name);
9813 sf = find_sample_fetch(trash->area, trash->data);
9814 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009815 fcn = sf->private;
9816 if (fcn->function_ref[hlua_state_id] != -1) {
9817 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9818 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009819 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +01009820 }
9821 fcn->function_ref[hlua_state_id] = ref;
9822 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009823 }
9824
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009825 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009826 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009827 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009828 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009829 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009830 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009831 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009832
9833 /* Fill fcn. */
9834 fcn->name = strdup(name);
9835 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009836 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009837 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009838
9839 /* List head */
9840 sfk->list.n = sfk->list.p = NULL;
9841
9842 /* sample-fetch keyword. */
9843 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009844 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009845 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009846 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009847
9848 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9849 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009850 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 +01009851 sfk->kw[0].val_args = NULL;
9852 sfk->kw[0].out_type = SMP_T_STR;
9853 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9854 sfk->kw[0].val = 0;
9855 sfk->kw[0].private = fcn;
9856
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009857 /* Register this new fetch. */
9858 sample_register_fetches(sfk);
9859
9860 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009861
9862 alloc_error:
9863 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01009864 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +02009865 ha_free(&sfk);
9866 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9867 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009868}
9869
Christopher Faulet501465d2020-02-26 14:54:16 +01009870/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009871 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009872__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009873{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009874 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009875 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02009876 int wakeup_ms; // tick value
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009877
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009878 /* Get hlua struct, or NULL if we execute from main lua state */
9879 hlua = hlua_gethlua(L);
9880 if (!hlua) {
9881 return 0;
9882 }
9883
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009884 MAY_LJMP(check_args(L, 1, "wake_time"));
9885
9886 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9887 wakeup_ms = tick_add(now_ms, delay);
9888 hlua->wake_time = wakeup_ms;
9889 return 0;
9890}
9891
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009892/* This function is a wrapper to execute each LUA function declared as an action
9893 * wrapper during the initialisation period. This function may return any
9894 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9895 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9896 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009897 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009898static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009899 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009900{
9901 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009902 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009903 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009904 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009905
9906 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009907 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9908 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9909 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9910 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009911 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009912 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009913 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009914 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009915
Willy Tarreau87b09662015-04-03 00:22:06 +02009916 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009917 * Lua context can be not initialized. This behavior
9918 * permits to save performances because a systematic
9919 * Lua initialization cause 5% performances loss.
9920 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009921 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009922 struct hlua *hlua;
9923
9924 hlua = pool_alloc(pool_head_hlua);
9925 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009926 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009927 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009928 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009929 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009930 HLUA_INIT(hlua);
9931 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009932 if (!hlua_ctx_init(s->hlua, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn), s->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009933 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009934 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009935 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009936 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009937 }
9938
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009939 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009940 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009941
9942 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009943 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009944 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9945 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009946 else
9947 error = "critical error";
9948 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009949 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009950 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009951 }
9952
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009953 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009954 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009955 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009956 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009957 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009958 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009959 }
9960
9961 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009962 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009963
Willy Tarreau87b09662015-04-03 00:22:06 +02009964 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009965 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009966 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009967 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009968 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009969 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009970 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009971 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009972
9973 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009974 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009975 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009976 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009977 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009978 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009979 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009980 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009981 lua_pushstring(s->hlua->T, *arg);
9982 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009983 }
9984
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009985 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009986 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009987
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009988 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009989 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009990 }
9991
9992 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009993 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009994 /* finished. */
9995 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009996 /* Catch the return value */
9997 if (lua_gettop(s->hlua->T) > 0)
9998 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009999
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010000 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +020010001 if (act_ret == ACT_RET_YIELD) {
10002 if (flags & ACT_OPT_FINAL)
10003 goto err_yield;
10004
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010005 if (dir == SMP_OPT_DIR_REQ)
10006 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10007 s->hlua->wake_time);
10008 else
10009 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10010 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010011 }
10012 goto end;
10013
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010014 /* yield. */
10015 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +010010016 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010017 if (dir == SMP_OPT_DIR_REQ)
10018 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10019 s->hlua->wake_time);
10020 else
10021 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10022 s->hlua->wake_time);
10023
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010024 /* Some actions can be wake up when a "write" event
10025 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010026 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010027 */
Christopher Faulet51fa3582019-07-26 14:54:52 +020010028 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010029 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010030 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010031 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010032 act_ret = ACT_RET_YIELD;
10033 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010034
10035 /* finished with error. */
10036 case HLUA_E_ERRMSG:
10037 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010038 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010039 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010040 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010041 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010042
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010043 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010044 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010045 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010046
10047 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010048 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010049 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010050
10051 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +020010052 err_yield:
10053 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010054 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010055 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010056 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010057
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010058 case HLUA_E_ERR:
10059 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010060 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010061 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010062
10063 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010064 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010065 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010066
10067 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010068 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010069 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010070 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010071}
10072
Willy Tarreau144f84a2021-03-02 16:09:26 +010010073struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010074{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010075 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010076
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010077 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010078 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010079 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010080}
10081
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010082static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010083{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010084 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010085 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010086 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010087 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010088 struct task *task;
10089 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010090 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010091
Willy Tarreaubafbe012017-11-24 17:34:44 +010010092 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010093 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010094 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010095 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010096 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010097 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010098 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010099 tcp_ctx->hlua = hlua;
10100 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010101
10102 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010103 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010104 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010105 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010106 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010107 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010108 }
10109 task->nice = 0;
10110 task->context = ctx;
10111 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010112 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010113
10114 /* In the execution wrappers linked with a stream, the
10115 * Lua context can be not initialized. This behavior
10116 * permits to save performances because a systematic
10117 * Lua initialization cause 5% performances loss.
10118 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010119 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010120 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010121 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010122 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010123 }
10124
10125 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010126 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010127
10128 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010129 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010130 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10131 error = lua_tostring(hlua->T, -1);
10132 else
10133 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010134 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010135 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010136 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010137 }
10138
10139 /* Check stack available size. */
10140 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010141 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010142 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010143 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010144 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010145 }
10146
10147 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010148 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010149
10150 /* Create and and push object stream in the stack. */
10151 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010152 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010153 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010154 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010155 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010156 }
10157 hlua->nargs = 1;
10158
10159 /* push keywords in the stack. */
10160 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10161 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010162 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010163 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010164 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010165 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010166 }
10167 lua_pushstring(hlua->T, *arg);
10168 hlua->nargs++;
10169 }
10170
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010171 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010172
10173 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010174 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010175 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010176
Christopher Fauletc9929382022-05-12 11:52:27 +020010177 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010178}
10179
Willy Tarreau60409db2019-08-21 14:14:50 +020010180void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010181{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010182 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010183 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010184 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010185 struct act_rule *rule = ctx->rule;
10186 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010187 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010188
Christopher Faulet31572222023-03-31 11:13:48 +020010189 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10190 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010191
Christopher Faulet31572222023-03-31 11:13:48 +020010192 /* The applet execution is already done. */
10193 if (tcp_ctx->flags & APPLET_DONE)
10194 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010195
10196 /* Execute the function. */
10197 switch (hlua_ctx_resume(hlua, 1)) {
10198 /* finished. */
10199 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010200 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010201 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10202 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010203
10204 /* yield. */
10205 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010206 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010207 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010208 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010209
10210 /* finished with error. */
10211 case HLUA_E_ERRMSG:
10212 /* Display log. */
10213 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010214 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010215 lua_pop(hlua->T, 1);
10216 goto error;
10217
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010218 case HLUA_E_ETMOUT:
10219 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010220 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010221 goto error;
10222
10223 case HLUA_E_NOMEM:
10224 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010225 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010226 goto error;
10227
10228 case HLUA_E_YIELD: /* unexpected */
10229 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010230 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010231 goto error;
10232
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010233 case HLUA_E_ERR:
10234 /* Display log. */
10235 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010236 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010237 goto error;
10238
10239 default:
10240 goto error;
10241 }
10242
Christopher Faulet31572222023-03-31 11:13:48 +020010243out:
10244 /* eat the whole request */
10245 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10246 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010247
Christopher Faulet31572222023-03-31 11:13:48 +020010248error:
10249 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010250 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010251 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010252}
10253
10254static void hlua_applet_tcp_release(struct appctx *ctx)
10255{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010256 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10257
10258 task_destroy(tcp_ctx->task);
10259 tcp_ctx->task = NULL;
10260 hlua_ctx_destroy(tcp_ctx->hlua);
10261 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010262}
10263
Christopher Fauletc9929382022-05-12 11:52:27 +020010264/* The function returns 0 if the initialisation is complete or -1 if
10265 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010266 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010267static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010268{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010269 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010270 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010271 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010272 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010273 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010274 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010275 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010276 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010277
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010278 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010279 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010280 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010281 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010282 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010283 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010284 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010285 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010286 http_ctx->hlua = hlua;
10287 http_ctx->left_bytes = -1;
10288 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010289
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010290 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010291 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010292
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010293 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010294 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010295 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010296 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010297 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010298 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010299 }
10300 task->nice = 0;
10301 task->context = ctx;
10302 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010303 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010304
10305 /* In the execution wrappers linked with a stream, the
10306 * Lua context can be not initialized. This behavior
10307 * permits to save performances because a systematic
10308 * Lua initialization cause 5% performances loss.
10309 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010310 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010311 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010312 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010313 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010314 }
10315
10316 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010317 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010318
10319 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010320 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010321 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10322 error = lua_tostring(hlua->T, -1);
10323 else
10324 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010325 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010326 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010327 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010328 }
10329
10330 /* Check stack available size. */
10331 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010332 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010333 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010334 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010335 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010336 }
10337
10338 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010339 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010340
10341 /* Create and and push object stream in the stack. */
10342 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010343 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010344 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010345 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010346 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010347 }
10348 hlua->nargs = 1;
10349
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010350 /* push keywords in the stack. */
10351 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10352 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010353 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010354 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010355 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010356 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010357 }
10358 lua_pushstring(hlua->T, *arg);
10359 hlua->nargs++;
10360 }
10361
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010362 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010363
10364 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010365 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010366
Christopher Fauletc9929382022-05-12 11:52:27 +020010367 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010368}
10369
Willy Tarreau60409db2019-08-21 14:14:50 +020010370void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010371{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010372 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010373 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010374 struct stream *strm = __sc_strm(sc);
10375 struct channel *req = sc_oc(sc);
10376 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010377 struct act_rule *rule = ctx->rule;
10378 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010379 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010380 struct htx *req_htx, *res_htx;
10381
10382 res_htx = htx_from_buf(&res->buf);
10383
Christopher Faulet31572222023-03-31 11:13:48 +020010384 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10385 goto out;
10386
10387 /* The applet execution is already done. */
10388 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010389 goto out;
10390
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010391 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010392 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010393 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010394 goto out;
10395 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010396
10397 /* Set the currently running flag. */
10398 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010399 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010400 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010401 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010402 goto out;
10403 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010404 }
10405
Christopher Faulet31572222023-03-31 11:13:48 +020010406 /* Execute the function. */
10407 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010408 /* finished. */
10409 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010410 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010411 break;
10412
10413 /* yield. */
10414 case HLUA_E_AGAIN:
10415 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010416 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010417 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010418
10419 /* finished with error. */
10420 case HLUA_E_ERRMSG:
10421 /* Display log. */
10422 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010423 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010424 lua_pop(hlua->T, 1);
10425 goto error;
10426
10427 case HLUA_E_ETMOUT:
10428 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010429 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010430 goto error;
10431
10432 case HLUA_E_NOMEM:
10433 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010434 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010435 goto error;
10436
10437 case HLUA_E_YIELD: /* unexpected */
10438 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010439 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010440 goto error;
10441
10442 case HLUA_E_ERR:
10443 /* Display log. */
10444 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010445 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010446 goto error;
10447
10448 default:
10449 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010450 }
10451
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010452 if (http_ctx->flags & APPLET_DONE) {
10453 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010454 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010455
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010456 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010457 goto error;
10458
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010459 /* no more data are expected. If the response buffer is empty
10460 * for a chunked message, be sure to add something (EOT block in
10461 * this case) to have something to send. It is important to be
10462 * sure the EOM flags will be handled by the endpoint.
10463 */
10464 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10465 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +020010466 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010467 goto out;
10468 }
10469 channel_add_input(res, 1);
10470 }
10471
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010472 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010473 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010474 strm->txn->status = http_ctx->status;
10475 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010476 }
10477
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010478 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010479 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010480 /* eat the whole request */
10481 if (co_data(req)) {
10482 req_htx = htx_from_buf(&req->buf);
10483 co_htx_skip(req, req_htx, co_data(req));
10484 htx_to_buf(req_htx, &req->buf);
10485 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010486 return;
10487
10488 error:
10489
10490 /* If we are in HTTP mode, and we are not send any
10491 * data, return a 500 server error in best effort:
10492 * if there is no room available in the buffer,
10493 * just close the connection.
10494 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010495 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010496 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010497
10498 channel_erase(res);
10499 res->buf.data = b_data(err);
10500 memcpy(res->buf.area, b_head(err), b_data(err));
10501 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010502 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010503 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010504 }
Christopher Faulet31572222023-03-31 11:13:48 +020010505 else
10506 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10507
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010508 if (!(strm->flags & SF_ERR_MASK))
10509 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010510 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010511 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010512}
10513
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010514static void hlua_applet_http_release(struct appctx *ctx)
10515{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010516 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10517
10518 task_destroy(http_ctx->task);
10519 http_ctx->task = NULL;
10520 hlua_ctx_destroy(http_ctx->hlua);
10521 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010522}
10523
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010524/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010525 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010526 *
10527 * This function can fail with an abort() due to an Lua critical error.
10528 * We are in the configuration parsing process of HAProxy, this abort() is
10529 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010530 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010531static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10532 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010533{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010534 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010535 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010536
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010537 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010538 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010539 if (!rule->arg.hlua_rule) {
10540 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010541 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010542 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010543
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010544 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010545 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10546 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010547 if (!rule->arg.hlua_rule->args) {
10548 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010549 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010550 }
10551
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010552 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010553 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010554
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010555 /* Expect some arguments */
10556 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010557 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010558 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010559 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010560 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010561 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010562 if (!rule->arg.hlua_rule->args[i]) {
10563 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010564 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010565 }
10566 (*cur_arg)++;
10567 }
10568 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010569
Thierry FOURNIER42148732015-09-02 17:17:33 +020010570 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010571 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010572 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010573
10574 error:
10575 if (rule->arg.hlua_rule) {
10576 if (rule->arg.hlua_rule->args) {
10577 for (i = 0; i < fcn->nargs; i++)
10578 ha_free(&rule->arg.hlua_rule->args[i]);
10579 ha_free(&rule->arg.hlua_rule->args);
10580 }
10581 ha_free(&rule->arg.hlua_rule);
10582 }
10583 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010584}
10585
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010586static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10587 struct act_rule *rule, char **err)
10588{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010589 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010590
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010591 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010592 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010593 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010594 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010595 * the call of this analyzer.
10596 */
10597 if (rule->from != ACT_F_HTTP_REQ) {
10598 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10599 return ACT_RET_PRS_ERR;
10600 }
10601
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010602 /* Memory for the rule. */
10603 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10604 if (!rule->arg.hlua_rule) {
10605 memprintf(err, "out of memory error");
10606 return ACT_RET_PRS_ERR;
10607 }
10608
10609 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010610 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010611
10612 /* TODO: later accept arguments. */
10613 rule->arg.hlua_rule->args = NULL;
10614
10615 /* Add applet pointer in the rule. */
10616 rule->applet.obj_type = OBJ_TYPE_APPLET;
10617 rule->applet.name = fcn->name;
10618 rule->applet.init = hlua_applet_http_init;
10619 rule->applet.fct = hlua_applet_http_fct;
10620 rule->applet.release = hlua_applet_http_release;
10621 rule->applet.timeout = hlua_timeout_applet;
10622
10623 return ACT_RET_PRS_OK;
10624}
10625
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010626/* This function is an LUA binding used for registering
10627 * "sample-conv" functions. It expects a converter name used
10628 * in the haproxy configuration file, and an LUA function.
10629 */
10630__LJMP static int hlua_register_action(lua_State *L)
10631{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010632 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010633 const char *name;
10634 int ref;
10635 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010636 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010637 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010638 struct buffer *trash;
10639 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010640
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010641 /* Initialise the number of expected arguments at 0. */
10642 nargs = 0;
10643
10644 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10645 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010646
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010647 if (hlua_gethlua(L)) {
10648 /* runtime processing */
10649 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10650 }
10651
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010652 /* First argument : converter name. */
10653 name = MAY_LJMP(luaL_checkstring(L, 1));
10654
10655 /* Second argument : environment. */
10656 if (lua_type(L, 2) != LUA_TTABLE)
10657 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10658
10659 /* Third argument : lua function. */
10660 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10661
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010662 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010663 if (lua_gettop(L) >= 4)
10664 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10665
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010666 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010667 lua_pushnil(L);
10668 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010669 if (lua_type(L, -1) != LUA_TSTRING) {
10670 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010671 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010672 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010673
Thierry Fournierf67442e2020-11-28 20:41:07 +010010674 /* Check if action exists */
10675 trash = get_trash_chunk();
10676 chunk_printf(trash, "lua.%s", name);
10677 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10678 akw = tcp_req_cont_action(trash->area);
10679 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10680 akw = tcp_res_cont_action(trash->area);
10681 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10682 akw = action_http_req_custom(trash->area);
10683 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10684 akw = action_http_res_custom(trash->area);
10685 } else {
10686 akw = NULL;
10687 }
10688 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010689 fcn = akw->private;
10690 if (fcn->function_ref[hlua_state_id] != -1) {
10691 ha_warning("Trying to register action 'lua.%s' more than once. "
10692 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010693 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010694 }
10695 fcn->function_ref[hlua_state_id] = ref;
10696
10697 /* pop the environment string. */
10698 lua_pop(L, 1);
10699 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010700 }
10701
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010702 /* Check required environment. Only accepted "http" or "tcp". */
10703 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010704 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010705 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010706 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010707 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010708 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010709 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010710
10711 /* Fill fcn. */
10712 fcn->name = strdup(name);
10713 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010714 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010715 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010716
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010717 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010718 fcn->nargs = nargs;
10719
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010720 /* List head */
10721 akl->list.n = akl->list.p = NULL;
10722
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010723 /* action keyword. */
10724 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010725 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010726 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010727 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010728
10729 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10730
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010731 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010732 akl->kw[0].private = fcn;
10733 akl->kw[0].parse = action_register_lua;
10734
10735 /* select the action registering point. */
10736 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10737 tcp_req_cont_keywords_register(akl);
10738 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10739 tcp_res_cont_keywords_register(akl);
10740 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10741 http_req_keywords_register(akl);
10742 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10743 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010744 else {
10745 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010746 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010747 if (akl)
10748 ha_free((char **)&(akl->kw[0].kw));
10749 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010750 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010751 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10752 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010753 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010754
10755 /* pop the environment string. */
10756 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010757
10758 /* reset for next loop */
10759 akl = NULL;
10760 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010761 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010762 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010763
10764 alloc_error:
10765 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010766 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010767 ha_free(&akl);
10768 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10769 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010770}
10771
10772static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10773 struct act_rule *rule, char **err)
10774{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010775 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010776
Christopher Faulet280f85b2019-07-15 15:02:04 +020010777 if (px->mode == PR_MODE_HTTP) {
10778 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010779 return ACT_RET_PRS_ERR;
10780 }
10781
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010782 /* Memory for the rule. */
10783 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10784 if (!rule->arg.hlua_rule) {
10785 memprintf(err, "out of memory error");
10786 return ACT_RET_PRS_ERR;
10787 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010788
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010789 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010790 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010791
10792 /* TODO: later accept arguments. */
10793 rule->arg.hlua_rule->args = NULL;
10794
10795 /* Add applet pointer in the rule. */
10796 rule->applet.obj_type = OBJ_TYPE_APPLET;
10797 rule->applet.name = fcn->name;
10798 rule->applet.init = hlua_applet_tcp_init;
10799 rule->applet.fct = hlua_applet_tcp_fct;
10800 rule->applet.release = hlua_applet_tcp_release;
10801 rule->applet.timeout = hlua_timeout_applet;
10802
10803 return 0;
10804}
10805
10806/* This function is an LUA binding used for registering
10807 * "sample-conv" functions. It expects a converter name used
10808 * in the haproxy configuration file, and an LUA function.
10809 */
10810__LJMP static int hlua_register_service(lua_State *L)
10811{
10812 struct action_kw_list *akl;
10813 const char *name;
10814 const char *env;
10815 int ref;
10816 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010817 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010818 struct buffer *trash;
10819 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010820
10821 MAY_LJMP(check_args(L, 3, "register_service"));
10822
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010823 if (hlua_gethlua(L)) {
10824 /* runtime processing */
10825 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
10826 }
10827
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010828 /* First argument : converter name. */
10829 name = MAY_LJMP(luaL_checkstring(L, 1));
10830
10831 /* Second argument : environment. */
10832 env = MAY_LJMP(luaL_checkstring(L, 2));
10833
10834 /* Third argument : lua function. */
10835 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10836
Thierry Fournierf67442e2020-11-28 20:41:07 +010010837 /* Check for service already registered */
10838 trash = get_trash_chunk();
10839 chunk_printf(trash, "lua.%s", name);
10840 akw = service_find(trash->area);
10841 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010842 fcn = akw->private;
10843 if (fcn->function_ref[hlua_state_id] != -1) {
10844 ha_warning("Trying to register service 'lua.%s' more than once. "
10845 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010846 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010847 }
10848 fcn->function_ref[hlua_state_id] = ref;
10849 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010850 }
10851
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010852 /* Allocate and fill the sample fetch keyword struct. */
10853 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10854 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010855 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010856 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010857 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010858 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010859
10860 /* Fill fcn. */
10861 len = strlen("<lua.>") + strlen(name) + 1;
10862 fcn->name = calloc(1, len);
10863 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010864 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010865 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010866 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010867
10868 /* List head */
10869 akl->list.n = akl->list.p = NULL;
10870
10871 /* converter keyword. */
10872 len = strlen("lua.") + strlen(name) + 1;
10873 akl->kw[0].kw = calloc(1, len);
10874 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010875 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010876
10877 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10878
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010879 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010880 if (strcmp(env, "tcp") == 0)
10881 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010882 else if (strcmp(env, "http") == 0)
10883 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010884 else {
10885 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010886 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010887 if (akl)
10888 ha_free((char **)&(akl->kw[0].kw));
10889 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010890 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010891 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010892 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010893
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010894 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010895 akl->kw[0].private = fcn;
10896
10897 /* End of array. */
10898 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10899
10900 /* Register this new converter */
10901 service_keywords_register(akl);
10902
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010903 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010904
10905 alloc_error:
10906 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010907 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020010908 ha_free(&akl);
10909 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10910 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010911}
10912
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010913/* This function initialises Lua cli handler. It copies the
10914 * arguments in the Lua stack and create channel IO objects.
10915 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010916static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010917{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010918 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010919 struct hlua *hlua;
10920 struct hlua_function *fcn;
10921 int i;
10922 const char *error;
10923
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010924 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010925 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010926
Willy Tarreaubafbe012017-11-24 17:34:44 +010010927 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010928 if (!hlua) {
10929 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010930 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010931 }
10932 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010933 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010934
10935 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010936 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010937 * applet_http. It is absolutely compatible.
10938 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010939 ctx->task = task_new_here();
10940 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010941 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010942 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010943 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010944 ctx->task->nice = 0;
10945 ctx->task->context = appctx;
10946 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010947
10948 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010949 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010950 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010951 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010952 }
10953
10954 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010955 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010956 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10957 error = lua_tostring(hlua->T, -1);
10958 else
10959 error = "critical error";
10960 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10961 goto error;
10962 }
10963
10964 /* Check stack available size. */
10965 if (!lua_checkstack(hlua->T, 2)) {
10966 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10967 goto error;
10968 }
10969
10970 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010971 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010972
10973 /* Once the arguments parsed, the CLI is like an AppletTCP,
10974 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010975 */
10976 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10977 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10978 goto error;
10979 }
10980 hlua->nargs = 1;
10981
10982 /* push keywords in the stack. */
10983 for (i = 0; *args[i]; i++) {
10984 /* Check stack available size. */
10985 if (!lua_checkstack(hlua->T, 1)) {
10986 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10987 goto error;
10988 }
10989 lua_pushstring(hlua->T, args[i]);
10990 hlua->nargs++;
10991 }
10992
10993 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010994 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010995
10996 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010997 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010998
10999 /* It's ok */
11000 return 0;
11001
11002 /* It's not ok. */
11003error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011004 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011005 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011006 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011007 return 1;
11008}
11009
11010static int hlua_cli_io_handler_fct(struct appctx *appctx)
11011{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011012 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011013 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020011014 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011015 struct hlua_function *fcn;
11016
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011017 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020011018 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011019 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011020
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011021 /* Execute the function. */
11022 switch (hlua_ctx_resume(hlua, 1)) {
11023
11024 /* finished. */
11025 case HLUA_E_OK:
11026 return 1;
11027
11028 /* yield. */
11029 case HLUA_E_AGAIN:
11030 /* We want write. */
11031 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020011032 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011033 /* Set the timeout. */
11034 if (hlua->wake_time != TICK_ETERNITY)
11035 task_schedule(hlua->task, hlua->wake_time);
11036 return 0;
11037
11038 /* finished with error. */
11039 case HLUA_E_ERRMSG:
11040 /* Display log. */
11041 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
11042 fcn->name, lua_tostring(hlua->T, -1));
11043 lua_pop(hlua->T, 1);
11044 return 1;
11045
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011046 case HLUA_E_ETMOUT:
11047 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
11048 fcn->name);
11049 return 1;
11050
11051 case HLUA_E_NOMEM:
11052 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
11053 fcn->name);
11054 return 1;
11055
11056 case HLUA_E_YIELD: /* unexpected */
11057 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
11058 fcn->name);
11059 return 1;
11060
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011061 case HLUA_E_ERR:
11062 /* Display log. */
11063 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11064 fcn->name);
11065 return 1;
11066
11067 default:
11068 return 1;
11069 }
11070
11071 return 1;
11072}
11073
11074static void hlua_cli_io_release_fct(struct appctx *appctx)
11075{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011076 struct hlua_cli_ctx *ctx = appctx->svcctx;
11077
11078 hlua_ctx_destroy(ctx->hlua);
11079 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011080}
11081
11082/* This function is an LUA binding used for registering
11083 * new keywords in the cli. It expects a list of keywords
11084 * which are the "path". It is limited to 5 keywords. A
11085 * description of the command, a function to be executed
11086 * for the parsing and a function for io handlers.
11087 */
11088__LJMP static int hlua_register_cli(lua_State *L)
11089{
11090 struct cli_kw_list *cli_kws;
11091 const char *message;
11092 int ref_io;
11093 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011094 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011095 int index;
11096 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011097 struct buffer *trash;
11098 const char *kw[5];
11099 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011100 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011101 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011102
11103 MAY_LJMP(check_args(L, 3, "register_cli"));
11104
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011105 if (hlua_gethlua(L)) {
11106 /* runtime processing */
11107 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11108 }
11109
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011110 /* First argument : an array of maximum 5 keywords. */
11111 if (!lua_istable(L, 1))
11112 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11113
11114 /* Second argument : string with contextual message. */
11115 message = MAY_LJMP(luaL_checkstring(L, 2));
11116
11117 /* Third and fourth argument : lua function. */
11118 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11119
Thierry Fournierf67442e2020-11-28 20:41:07 +010011120 /* Check for CLI service already registered */
11121 trash = get_trash_chunk();
11122 index = 0;
11123 lua_pushnil(L);
11124 memset(kw, 0, sizeof(kw));
11125 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011126 if (index >= CLI_PREFIX_KW_NB) {
11127 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011128 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 +010011129 }
11130 if (lua_type(L, -1) != LUA_TSTRING) {
11131 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011132 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011133 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011134 kw[index] = lua_tostring(L, -1);
11135 if (index == 0)
11136 chunk_printf(trash, "%s", kw[index]);
11137 else
11138 chunk_appendf(trash, " %s", kw[index]);
11139 index++;
11140 lua_pop(L, 1);
11141 }
11142 cli_kw = cli_find_kw_exact((char **)kw);
11143 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011144 fcn = cli_kw->private;
11145 if (fcn->function_ref[hlua_state_id] != -1) {
11146 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11147 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011148 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011149 }
11150 fcn->function_ref[hlua_state_id] = ref_io;
11151 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011152 }
11153
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011154 /* Allocate and fill the sample fetch keyword struct. */
11155 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011156 if (!cli_kws) {
11157 errmsg = "Lua out of memory error.";
11158 goto error;
11159 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011160 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011161 if (!fcn) {
11162 errmsg = "Lua out of memory error.";
11163 goto error;
11164 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011165
11166 /* Fill path. */
11167 index = 0;
11168 lua_pushnil(L);
11169 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011170 if (index >= 5) {
11171 errmsg = "1st argument must be a table with a maximum of 5 entries";
11172 goto error;
11173 }
11174 if (lua_type(L, -1) != LUA_TSTRING) {
11175 errmsg = "1st argument must be a table filled with strings";
11176 goto error;
11177 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011178 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011179 if (!cli_kws->kw[0].str_kw[index]) {
11180 errmsg = "Lua out of memory error.";
11181 goto error;
11182 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011183 index++;
11184 lua_pop(L, 1);
11185 }
11186
11187 /* Copy help message. */
11188 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011189 if (!cli_kws->kw[0].usage) {
11190 errmsg = "Lua out of memory error.";
11191 goto error;
11192 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011193
11194 /* Fill fcn io handler. */
11195 len = strlen("<lua.cli>") + 1;
11196 for (i = 0; i < index; i++)
11197 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11198 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011199 if (!fcn->name) {
11200 errmsg = "Lua out of memory error.";
11201 goto error;
11202 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011203
11204 end = fcn->name;
11205 len = 8;
11206 memcpy(end, "<lua.cli", len);
11207 end += len;
11208
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011209 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011210 *(end++) = '.';
11211 len = strlen(cli_kws->kw[0].str_kw[i]);
11212 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11213 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011214 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011215 *(end++) = '>';
11216 *(end++) = 0;
11217
Thierry Fournierc7492592020-11-28 23:57:24 +010011218 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011219
11220 /* Fill last entries. */
11221 cli_kws->kw[0].private = fcn;
11222 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11223 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11224 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11225
11226 /* Register this new converter */
11227 cli_register_kw(cli_kws);
11228
11229 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011230
11231 error:
11232 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011233 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011234 if (cli_kws) {
11235 for (i = 0; i < index; i++)
11236 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11237 ha_free((char **)&(cli_kws->kw[0].usage));
11238 }
11239 ha_free(&cli_kws);
11240 WILL_LJMP(luaL_error(L, errmsg));
11241 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011242}
11243
Christopher Faulet69c581a2021-05-31 08:54:04 +020011244static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11245{
11246 struct hlua_flt_config *conf = fconf->conf;
11247 lua_State *L;
11248 int error, pos, state_id, flt_ref;
11249
11250 state_id = reg_flt_to_stack_id(conf->reg);
11251 L = hlua_states[state_id];
11252 pos = lua_gettop(L);
11253
11254 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011255 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011256
11257 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011258 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011259
11260 /* Duplicate the filter class so each filter will have its own copy */
11261 lua_newtable(L);
11262 lua_pushnil(L);
11263
11264 while (lua_next(L, pos+2)) {
11265 lua_pushvalue(L, -2);
11266 lua_insert(L, -2);
11267 lua_settable(L, -4);
11268 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011269 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011270
11271 /* Remove the original lua filter class from the stack */
11272 lua_pop(L, 1);
11273
11274 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011275 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011276
11277 /* extra args are pushed in a table */
11278 lua_newtable(L);
11279 for (pos = 0; conf->args[pos]; pos++) {
11280 /* Check stack available size. */
11281 if (!lua_checkstack(L, 1)) {
11282 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11283 goto error;
11284 }
11285 lua_pushstring(L, conf->args[pos]);
11286 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11287 }
11288
11289 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11290 switch (error) {
11291 case LUA_OK:
11292 /* replace the filter ref */
11293 conf->ref[state_id] = flt_ref;
11294 break;
11295 case LUA_ERRRUN:
11296 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11297 goto error;
11298 case LUA_ERRMEM:
11299 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11300 goto error;
11301 case LUA_ERRERR:
11302 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11303 goto error;
11304#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11305 case LUA_ERRGCMM:
11306 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11307 goto error;
11308#endif
11309 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011310 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011311 goto error;
11312 }
11313
11314 lua_settop(L, 0);
11315 return 0;
11316
11317 error:
11318 lua_settop(L, 0);
11319 return -1;
11320}
11321
11322static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11323{
11324 struct hlua_flt_config *conf = fconf->conf;
11325 lua_State *L;
11326 int state_id;
11327
11328 if (!conf)
11329 return;
11330
11331 state_id = reg_flt_to_stack_id(conf->reg);
11332 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011333 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011334}
11335
11336static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11337{
11338 struct hlua_flt_config *conf = fconf->conf;
11339 int state_id = reg_flt_to_stack_id(conf->reg);
11340
11341 /* Rely on per-thread init for global scripts */
11342 if (!state_id)
11343 return hlua_filter_init_per_thread(px, fconf);
11344 return 0;
11345}
11346
11347static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11348{
11349
11350 if (fconf->conf) {
11351 struct hlua_flt_config *conf = fconf->conf;
11352 int state_id = reg_flt_to_stack_id(conf->reg);
11353 int pos;
11354
11355 /* Rely on per-thread deinit for global scripts */
11356 if (!state_id)
11357 hlua_filter_deinit_per_thread(px, fconf);
11358
11359 for (pos = 0; conf->args[pos]; pos++)
11360 free(conf->args[pos]);
11361 free(conf->args);
11362 }
11363 ha_free(&fconf->conf);
11364 ha_free((char **)&fconf->id);
11365 ha_free(&fconf->ops);
11366}
11367
11368static int hlua_filter_new(struct stream *s, struct filter *filter)
11369{
11370 struct hlua_flt_config *conf = FLT_CONF(filter);
11371 struct hlua_flt_ctx *flt_ctx = NULL;
11372 int ret = 1;
11373
11374 /* In the execution wrappers linked with a stream, the
11375 * Lua context can be not initialized. This behavior
11376 * permits to save performances because a systematic
11377 * Lua initialization cause 5% performances loss.
11378 */
11379 if (!s->hlua) {
11380 struct hlua *hlua;
11381
11382 hlua = pool_alloc(pool_head_hlua);
11383 if (!hlua) {
11384 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11385 conf->reg->name);
11386 ret = 0;
11387 goto end;
11388 }
11389 HLUA_INIT(hlua);
11390 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011391 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011392 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11393 conf->reg->name);
11394 ret = 0;
11395 goto end;
11396 }
11397 }
11398
11399 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11400 if (!flt_ctx) {
11401 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11402 conf->reg->name);
11403 ret = 0;
11404 goto end;
11405 }
11406 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11407 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11408 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11409 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11410 conf->reg->name);
11411 ret = 0;
11412 goto end;
11413 }
11414 HLUA_INIT(flt_ctx->hlua[0]);
11415 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011416 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11417 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011418 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11419 conf->reg->name);
11420 ret = 0;
11421 goto end;
11422 }
11423
11424 if (!HLUA_IS_RUNNING(s->hlua)) {
11425 /* The following Lua calls can fail. */
11426 if (!SET_SAFE_LJMP(s->hlua)) {
11427 const char *error;
11428
11429 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11430 error = lua_tostring(s->hlua->T, -1);
11431 else
11432 error = "critical error";
11433 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11434 ret = 0;
11435 goto end;
11436 }
11437
11438 /* Check stack size. */
11439 if (!lua_checkstack(s->hlua->T, 1)) {
11440 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011441 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011442 ret = 0;
11443 goto end;
11444 }
11445
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011446 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011447 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11448 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11449 conf->reg->name);
11450 RESET_SAFE_LJMP(s->hlua);
11451 ret = 0;
11452 goto end;
11453 }
11454 lua_insert(s->hlua->T, -2);
11455
11456 /* Push the copy on the stack */
11457 s->hlua->nargs = 1;
11458
11459 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011460 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011461
11462 /* At this point the execution is safe. */
11463 RESET_SAFE_LJMP(s->hlua);
11464 }
11465
11466 switch (hlua_ctx_resume(s->hlua, 0)) {
11467 case HLUA_E_OK:
11468 /* Nothing returned or not a table, ignore the filter for current stream */
11469 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11470 ret = 0;
11471 goto end;
11472 }
11473
11474 /* Attached the filter pointer to the ctx */
11475 lua_pushstring(s->hlua->T, "__filter");
11476 lua_pushlightuserdata(s->hlua->T, filter);
11477 lua_settable(s->hlua->T, -3);
11478
11479 /* Save a ref on the filter ctx */
11480 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011481 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011482 filter->ctx = flt_ctx;
11483 break;
11484 case HLUA_E_ERRMSG:
11485 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11486 ret = -1;
11487 goto end;
11488 case HLUA_E_ETMOUT:
11489 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11490 ret = 0;
11491 goto end;
11492 case HLUA_E_NOMEM:
11493 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11494 ret = 0;
11495 goto end;
11496 case HLUA_E_AGAIN:
11497 case HLUA_E_YIELD:
11498 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11499 " are not allowed from 'new' function.\n", conf->reg->name);
11500 ret = 0;
11501 goto end;
11502 case HLUA_E_ERR:
11503 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11504 ret = 0;
11505 goto end;
11506 default:
11507 ret = 0;
11508 goto end;
11509 }
11510
11511 end:
11512 if (s->hlua)
11513 lua_settop(s->hlua->T, 0);
11514 if (ret <= 0) {
11515 if (flt_ctx) {
11516 hlua_ctx_destroy(flt_ctx->hlua[0]);
11517 hlua_ctx_destroy(flt_ctx->hlua[1]);
11518 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11519 }
11520 }
11521 return ret;
11522}
11523
11524static void hlua_filter_delete(struct stream *s, struct filter *filter)
11525{
11526 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11527
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011528 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011529 hlua_ctx_destroy(flt_ctx->hlua[0]);
11530 hlua_ctx_destroy(flt_ctx->hlua[1]);
11531 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11532 filter->ctx = NULL;
11533}
11534
Christopher Faulet9f55a502020-02-25 15:21:02 +010011535static int hlua_filter_from_payload(struct filter *filter)
11536{
11537 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11538
11539 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11540}
11541
Christopher Fauletc404f112020-02-26 15:03:09 +010011542static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11543 int dir, unsigned int flags)
11544{
11545 struct hlua *flt_hlua;
11546 struct hlua_flt_config *conf = FLT_CONF(filter);
11547 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11548 unsigned int hflags = HLUA_TXN_FLT_CTX;
11549 int ret = 1;
11550
11551 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11552 if (!flt_hlua)
11553 goto end;
11554
11555 if (!HLUA_IS_RUNNING(flt_hlua)) {
11556 int extra_idx = lua_gettop(flt_hlua->T);
11557
11558 /* The following Lua calls can fail. */
11559 if (!SET_SAFE_LJMP(flt_hlua)) {
11560 const char *error;
11561
11562 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11563 error = lua_tostring(flt_hlua->T, -1);
11564 else
11565 error = "critical error";
11566 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11567 goto end;
11568 }
11569
11570 /* Check stack size. */
11571 if (!lua_checkstack(flt_hlua->T, 3)) {
11572 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11573 RESET_SAFE_LJMP(flt_hlua);
11574 goto end;
11575 }
11576
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011577 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011578 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11579 RESET_SAFE_LJMP(flt_hlua);
11580 goto end;
11581 }
11582 lua_insert(flt_hlua->T, -2);
11583
11584 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11585 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11586 RESET_SAFE_LJMP(flt_hlua);
11587 goto end;
11588 }
11589 flt_hlua->nargs = 2;
11590
11591 if (flags & HLUA_FLT_CB_ARG_CHN) {
11592 if (dir == SMP_OPT_DIR_REQ)
11593 lua_getfield(flt_hlua->T, -1, "req");
11594 else
11595 lua_getfield(flt_hlua->T, -1, "res");
11596 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11597 lua_pushstring(flt_hlua->T, "__filter");
11598 lua_pushlightuserdata(flt_hlua->T, filter);
11599 lua_settable(flt_hlua->T, -3);
11600 }
11601 flt_hlua->nargs++;
11602 }
11603 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011604 if (dir == SMP_OPT_DIR_REQ)
11605 lua_getfield(flt_hlua->T, -1, "http_req");
11606 else
11607 lua_getfield(flt_hlua->T, -1, "http_res");
11608 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11609 lua_pushstring(flt_hlua->T, "__filter");
11610 lua_pushlightuserdata(flt_hlua->T, filter);
11611 lua_settable(flt_hlua->T, -3);
11612 }
11613 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011614 }
11615
11616 /* Check stack size. */
11617 if (!lua_checkstack(flt_hlua->T, 1)) {
11618 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11619 RESET_SAFE_LJMP(flt_hlua);
11620 goto end;
11621 }
11622
11623 while (extra_idx--) {
11624 lua_pushvalue(flt_hlua->T, 1);
11625 lua_remove(flt_hlua->T, 1);
11626 flt_hlua->nargs++;
11627 }
11628
11629 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011630 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010011631
11632 /* At this point the execution is safe. */
11633 RESET_SAFE_LJMP(flt_hlua);
11634 }
11635
11636 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11637 case HLUA_E_OK:
11638 /* Catch the return value if it required */
11639 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11640 ret = lua_tointeger(flt_hlua->T, -1);
11641 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11642 }
11643
11644 /* Set timeout in the required channel. */
11645 if (flt_hlua->wake_time != TICK_ETERNITY) {
11646 if (dir == SMP_OPT_DIR_REQ)
11647 s->req.analyse_exp = flt_hlua->wake_time;
11648 else
11649 s->res.analyse_exp = flt_hlua->wake_time;
11650 }
11651 break;
11652 case HLUA_E_AGAIN:
11653 /* Set timeout in the required channel. */
11654 if (flt_hlua->wake_time != TICK_ETERNITY) {
11655 if (dir == SMP_OPT_DIR_REQ)
11656 s->req.analyse_exp = flt_hlua->wake_time;
11657 else
11658 s->res.analyse_exp = flt_hlua->wake_time;
11659 }
11660 /* Some actions can be wake up when a "write" event
11661 * is detected on a response channel. This is useful
11662 * only for actions targeted on the requests.
11663 */
11664 if (HLUA_IS_WAKERESWR(flt_hlua))
11665 s->res.flags |= CF_WAKE_WRITE;
11666 if (HLUA_IS_WAKEREQWR(flt_hlua))
11667 s->req.flags |= CF_WAKE_WRITE;
11668 ret = 0;
11669 goto end;
11670 case HLUA_E_ERRMSG:
11671 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11672 ret = -1;
11673 goto end;
11674 case HLUA_E_ETMOUT:
11675 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11676 goto end;
11677 case HLUA_E_NOMEM:
11678 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11679 goto end;
11680 case HLUA_E_YIELD:
11681 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11682 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11683 goto end;
11684 case HLUA_E_ERR:
11685 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11686 goto end;
11687 default:
11688 goto end;
11689 }
11690
11691
11692 end:
11693 return ret;
11694}
11695
11696static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11697{
11698 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11699
11700 flt_ctx->flags = 0;
11701 return hlua_filter_callback(s, filter, "start_analyze",
11702 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11703 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11704}
11705
11706static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11707{
11708 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11709
11710 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11711 return hlua_filter_callback(s, filter, "end_analyze",
11712 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11713 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11714}
11715
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011716static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11717{
11718 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11719
11720 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11721 return hlua_filter_callback(s, filter, "http_headers",
11722 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11723 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11724}
11725
11726static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11727 unsigned int offset, unsigned int len)
11728{
11729 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11730 struct hlua *flt_hlua;
11731 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11732 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11733 int ret;
11734
11735 flt_hlua = flt_ctx->hlua[idx];
11736 flt_ctx->cur_off[idx] = offset;
11737 flt_ctx->cur_len[idx] = len;
11738 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11739 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11740 if (ret != -1) {
11741 ret = flt_ctx->cur_len[idx];
11742 if (lua_gettop(flt_hlua->T) > 0) {
11743 ret = lua_tointeger(flt_hlua->T, -1);
11744 if (ret > flt_ctx->cur_len[idx])
11745 ret = flt_ctx->cur_len[idx];
11746 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11747 }
11748 }
11749 return ret;
11750}
11751
11752static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11753{
11754 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11755
11756 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11757 return hlua_filter_callback(s, filter, "http_end",
11758 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11759 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11760}
11761
Christopher Fauletc404f112020-02-26 15:03:09 +010011762static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11763 unsigned int offset, unsigned int len)
11764{
11765 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11766 struct hlua *flt_hlua;
11767 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11768 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11769 int ret;
11770
11771 flt_hlua = flt_ctx->hlua[idx];
11772 flt_ctx->cur_off[idx] = offset;
11773 flt_ctx->cur_len[idx] = len;
11774 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11775 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11776 if (ret != -1) {
11777 ret = flt_ctx->cur_len[idx];
11778 if (lua_gettop(flt_hlua->T) > 0) {
11779 ret = lua_tointeger(flt_hlua->T, -1);
11780 if (ret > flt_ctx->cur_len[idx])
11781 ret = flt_ctx->cur_len[idx];
11782 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11783 }
11784 }
11785 return ret;
11786}
11787
Christopher Faulet69c581a2021-05-31 08:54:04 +020011788static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11789 struct flt_conf *fconf, char **err, void *private)
11790{
11791 struct hlua_reg_filter *reg_flt = private;
11792 lua_State *L;
11793 struct hlua_flt_config *conf = NULL;
11794 const char *flt_id = NULL;
11795 int state_id, pos, flt_flags = 0;
11796 struct flt_ops *hlua_flt_ops = NULL;
11797
11798 state_id = reg_flt_to_stack_id(reg_flt);
11799 L = hlua_states[state_id];
11800
11801 /* Initialize the filter ops with default callbacks */
11802 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011803 if (!hlua_flt_ops)
11804 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011805 hlua_flt_ops->init = hlua_filter_init;
11806 hlua_flt_ops->deinit = hlua_filter_deinit;
11807 if (state_id) {
11808 /* Set per-thread callback if script is loaded per-thread */
11809 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11810 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11811 }
11812 hlua_flt_ops->attach = hlua_filter_new;
11813 hlua_flt_ops->detach = hlua_filter_delete;
11814
11815 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011816 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011817
Christopher Fauletc404f112020-02-26 15:03:09 +010011818 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11819 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11820 lua_pop(L, 1);
11821 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11822 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11823 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011824 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11825 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11826 lua_pop(L, 1);
11827 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11828 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11829 lua_pop(L, 1);
11830 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11831 hlua_flt_ops->http_end = hlua_filter_http_end;
11832 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011833 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11834 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11835 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011836
11837 /* Get id and flags of the filter class */
11838 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11839 flt_id = lua_tostring(L, -1);
11840 lua_pop(L, 1);
11841 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11842 flt_flags = lua_tointeger(L, -1);
11843 lua_pop(L, 1);
11844
11845 /* Create the filter config */
11846 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011847 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011848 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011849 conf->reg = reg_flt;
11850
11851 /* duplicate args */
11852 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11853 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011854 if (!conf->args)
11855 goto error;
11856 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011857 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011858 if (!conf->args[pos])
11859 goto error;
11860 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011861 conf->args[pos] = NULL;
11862 *cur_arg += pos + 1;
11863
Christopher Fauletc86bb872021-08-13 08:33:57 +020011864 if (flt_id) {
11865 fconf->id = strdup(flt_id);
11866 if (!fconf->id)
11867 goto error;
11868 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011869 fconf->flags = flt_flags;
11870 fconf->conf = conf;
11871 fconf->ops = hlua_flt_ops;
11872
11873 lua_settop(L, 0);
11874 return 0;
11875
11876 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011877 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011878 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011879 if (conf && conf->args) {
11880 for (pos = 0; conf->args[pos]; pos++)
11881 free(conf->args[pos]);
11882 free(conf->args);
11883 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011884 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011885 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011886 lua_settop(L, 0);
11887 return -1;
11888}
11889
Christopher Fauletc404f112020-02-26 15:03:09 +010011890__LJMP static int hlua_register_data_filter(lua_State *L)
11891{
11892 struct filter *filter;
11893 struct channel *chn;
11894
11895 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11896 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11897 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11898
11899 lua_getfield(L, 1, "__filter");
11900 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11901 filter = lua_touserdata (L, -1);
11902 lua_pop(L, 1);
11903
11904 register_data_filter(chn_strm(chn), chn, filter);
11905 return 1;
11906}
11907
11908__LJMP static int hlua_unregister_data_filter(lua_State *L)
11909{
11910 struct filter *filter;
11911 struct channel *chn;
11912
11913 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11914 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11915 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11916
11917 lua_getfield(L, 1, "__filter");
11918 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11919 filter = lua_touserdata (L, -1);
11920 lua_pop(L, 1);
11921
11922 unregister_data_filter(chn_strm(chn), chn, filter);
11923 return 1;
11924}
11925
Christopher Faulet69c581a2021-05-31 08:54:04 +020011926/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011927 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011928 * parse configuration arguments.
11929 */
11930__LJMP static int hlua_register_filter(lua_State *L)
11931{
11932 struct buffer *trash;
11933 struct flt_kw_list *fkl;
11934 struct flt_kw *fkw;
11935 const char *name;
11936 struct hlua_reg_filter *reg_flt= NULL;
11937 int flt_ref, fun_ref;
11938 int len;
11939
11940 MAY_LJMP(check_args(L, 3, "register_filter"));
11941
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011942 if (hlua_gethlua(L)) {
11943 /* runtime processing */
11944 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
11945 }
11946
Christopher Faulet69c581a2021-05-31 08:54:04 +020011947 /* First argument : filter name. */
11948 name = MAY_LJMP(luaL_checkstring(L, 1));
11949
11950 /* Second argument : The filter class */
11951 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11952
11953 /* Third argument : lua function. */
11954 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11955
11956 trash = get_trash_chunk();
11957 chunk_printf(trash, "lua.%s", name);
11958 fkw = flt_find_kw(trash->area);
11959 if (fkw != NULL) {
11960 reg_flt = fkw->private;
11961 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11962 ha_warning("Trying to register filter 'lua.%s' more than once. "
11963 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011964 if (reg_flt->flt_ref[hlua_state_id] != -1)
11965 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
11966 if (reg_flt->fun_ref[hlua_state_id] != -1)
11967 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011968 }
11969 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11970 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11971 return 0;
11972 }
11973
11974 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11975 if (!fkl)
11976 goto alloc_error;
11977 fkl->scope = "HLUA";
11978
11979 reg_flt = new_hlua_reg_filter(name);
11980 if (!reg_flt)
11981 goto alloc_error;
11982
11983 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11984 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11985
11986 /* The filter keyword */
11987 len = strlen("lua.") + strlen(name) + 1;
11988 fkl->kw[0].kw = calloc(1, len);
11989 if (!fkl->kw[0].kw)
11990 goto alloc_error;
11991
11992 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11993
11994 fkl->kw[0].parse = hlua_filter_parse_fct;
11995 fkl->kw[0].private = reg_flt;
11996 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11997
11998 /* Register this new filter */
11999 flt_register_keywords(fkl);
12000
12001 return 0;
12002
12003 alloc_error:
12004 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012005 hlua_unref(L, flt_ref);
12006 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012007 ha_free(&fkl);
12008 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
12009 return 0; /* Never reached */
12010}
12011
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012012static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012013 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012014 char **err, unsigned int *timeout)
12015{
12016 const char *error;
12017
12018 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020012019 if (error == PARSE_TIME_OVER) {
12020 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
12021 args[1], args[0]);
12022 return -1;
12023 }
12024 else if (error == PARSE_TIME_UNDER) {
12025 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
12026 args[1], args[0]);
12027 return -1;
12028 }
12029 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012030 memprintf(err, "%s: invalid timeout", args[0]);
12031 return -1;
12032 }
12033 return 0;
12034}
12035
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012036static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
12037 const struct proxy *defpx, const char *file, int line,
12038 char **err)
12039{
12040 return hlua_read_timeout(args, section_type, curpx, defpx,
12041 file, line, err, &hlua_timeout_burst);
12042}
12043
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012044static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012045 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012046 char **err)
12047{
12048 return hlua_read_timeout(args, section_type, curpx, defpx,
12049 file, line, err, &hlua_timeout_session);
12050}
12051
12052static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012053 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012054 char **err)
12055{
12056 return hlua_read_timeout(args, section_type, curpx, defpx,
12057 file, line, err, &hlua_timeout_task);
12058}
12059
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012060static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012061 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012062 char **err)
12063{
12064 return hlua_read_timeout(args, section_type, curpx, defpx,
12065 file, line, err, &hlua_timeout_applet);
12066}
12067
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012068static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012069 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012070 char **err)
12071{
12072 char *error;
12073
12074 hlua_nb_instruction = strtoll(args[1], &error, 10);
12075 if (*error != '\0') {
12076 memprintf(err, "%s: invalid number", args[0]);
12077 return -1;
12078 }
12079 return 0;
12080}
12081
Willy Tarreau32f61e22015-03-18 17:54:59 +010012082static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012083 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012084 char **err)
12085{
12086 char *error;
12087
12088 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012089 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012090 return -1;
12091 }
12092 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12093 if (*error != '\0') {
12094 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12095 return -1;
12096 }
12097 return 0;
12098}
12099
12100
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012101/* This function is called by the main configuration key "lua-load". It loads and
12102 * execute an lua file during the parsing of the HAProxy configuration file. It is
12103 * the main lua entry point.
12104 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012105 * This function runs with the HAProxy keywords API. It returns -1 if an error
12106 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012107 *
12108 * In some error case, LUA set an error message in top of the stack. This function
12109 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012110 *
12111 * This function can fail with an abort() due to an Lua critical error.
12112 * We are in the configuration parsing process of HAProxy, this abort() is
12113 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012114 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012115static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012116{
12117 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012118 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012119
12120 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012121 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012122 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020012123 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012124 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012125 return -1;
12126 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012127
12128 /* Push args in the Lua stack, except the first one which is the filename */
12129 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012130 /* Check stack size. */
12131 if (!lua_checkstack(L, 1)) {
12132 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12133 return -1;
12134 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012135 lua_pushstring(L, args[nargs]);
12136 }
12137 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012138
12139 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012140 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012141 switch (error) {
12142 case LUA_OK:
12143 break;
12144 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012145 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012146 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012147 return -1;
12148 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012149 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012150 return -1;
12151 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012152 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012153 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012154 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012155#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012156 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012157 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012158 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012159 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012160#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012161 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012162 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012163 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012164 return -1;
12165 }
12166
12167 return 0;
12168}
12169
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012170static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012171 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012172 char **err)
12173{
12174 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012175 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012176 return -1;
12177 }
12178
Thierry Fournier59f11be2020-11-29 00:37:41 +010012179 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012180 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012181 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012182 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012183}
12184
Thierry Fournier59f11be2020-11-29 00:37:41 +010012185static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012186 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012187 char **err)
12188{
12189 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012190 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012191
12192 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012193 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012194 return -1;
12195 }
12196
12197 if (per_thread_load == NULL) {
12198 /* allocate the first entry large enough to store the final NULL */
12199 per_thread_load = calloc(1, sizeof(*per_thread_load));
12200 if (per_thread_load == NULL) {
12201 memprintf(err, "out of memory error");
12202 return -1;
12203 }
12204 }
12205
12206 /* count used entries */
12207 for (len = 0; per_thread_load[len] != NULL; len++)
12208 ;
12209
12210 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12211 if (per_thread_load == NULL) {
12212 memprintf(err, "out of memory error");
12213 return -1;
12214 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012215 per_thread_load[len + 1] = NULL;
12216
Thierry Fournierae6b5682022-09-19 09:04:16 +020012217 /* count args excepting the first, allocate array and copy args */
12218 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012219 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012220 if (per_thread_load[len] == NULL) {
12221 memprintf(err, "out of memory error");
12222 return -1;
12223 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012224 for (i = 1; *(args[i]) != 0; i++) {
12225 per_thread_load[len][i - 1] = strdup(args[i]);
12226 if (per_thread_load[len][i - 1] == NULL) {
12227 memprintf(err, "out of memory error");
12228 return -1;
12229 }
12230 }
12231 per_thread_load[len][i - 1] = strdup("");
12232 if (per_thread_load[len][i - 1] == NULL) {
12233 memprintf(err, "out of memory error");
12234 return -1;
12235 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012236
12237 /* loading for thread 1 only */
12238 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012239 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012240 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012241}
12242
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012243/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12244 * in the given <ctx>.
12245 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012246static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012247{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012248 lua_getglobal(L, "package"); /* push package variable */
12249 lua_pushstring(L, path); /* push given path */
12250 lua_pushstring(L, ";"); /* push semicolon */
12251 lua_getfield(L, -3, type); /* push old path */
12252 lua_concat(L, 3); /* concatenate to new path */
12253 lua_setfield(L, -2, type); /* store new path */
12254 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012255
12256 return 0;
12257}
12258
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012259static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012260 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012261 char **err)
12262{
12263 char *path;
12264 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012265 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012266 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012267
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012268 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012269 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012270 }
12271
12272 if (!(*args[1])) {
12273 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012274 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012275 }
12276 path = args[1];
12277
12278 if (*args[2]) {
12279 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12280 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012281 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012282 }
12283 type = args[2];
12284 }
12285
Thierry Fournier59f11be2020-11-29 00:37:41 +010012286 p = calloc(1, sizeof(*p));
12287 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012288 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012289 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012290 }
12291 p->path = strdup(path);
12292 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012293 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012294 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012295 }
12296 p->type = strdup(type);
12297 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012298 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012299 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012300 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012301 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012302
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012303 /* Handle the global state and the per-thread state for the first
12304 * thread. The remaining threads will be initialized based on
12305 * prepend_path_list.
12306 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012307 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012308 lua_State *L = hlua_states[i];
12309 const char *error;
12310
12311 if (setjmp(safe_ljmp_env) != 0) {
12312 lua_atpanic(L, hlua_panic_safe);
12313 if (lua_type(L, -1) == LUA_TSTRING)
12314 error = lua_tostring(L, -1);
12315 else
12316 error = "critical error";
12317 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12318 exit(1);
12319 } else {
12320 lua_atpanic(L, hlua_panic_ljmp);
12321 }
12322
12323 hlua_prepend_path(L, type, path);
12324
12325 lua_atpanic(L, hlua_panic_safe);
12326 }
12327
Thierry Fournier59f11be2020-11-29 00:37:41 +010012328 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012329
12330err2:
12331 free(p->type);
12332 free(p->path);
12333err:
12334 free(p);
12335 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012336}
12337
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012338/* configuration keywords declaration */
12339static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012340 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012341 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012342 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012343 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12344 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012345 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012346 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012347 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012348 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012349 { 0, NULL, NULL },
12350}};
12351
Willy Tarreau0108d902018-11-25 19:14:37 +010012352INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12353
William Lallemand52139182022-03-30 15:05:42 +020012354#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012355
William Lallemand30fcca12022-03-30 12:03:12 +020012356/*
12357 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12358 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12359 * difference is that the yield in lua and for the CLI is not handled the same
12360 * way.
12361 */
12362__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12363{
12364 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12365 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12366 struct ckch_inst *ckchi = *lua_ckchi;
12367 struct ckch_store *old_ckchs = lua_ckchs[0];
12368 struct ckch_store *new_ckchs = lua_ckchs[1];
12369 struct hlua *hlua;
12370 char *err = NULL;
12371 int y = 1;
12372
12373 hlua = hlua_gethlua(L);
12374
12375 /* get the first ckchi to copy */
12376 if (ckchi == NULL)
12377 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12378
12379 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12380 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12381 struct ckch_inst *new_inst;
12382
12383 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12384 if (y % 10 == 0) {
12385
12386 *lua_ckchi = ckchi;
12387
12388 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12389 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12390 }
12391
12392 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12393 goto error;
12394
12395 /* link the new ckch_inst to the duplicate */
12396 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12397 y++;
12398 }
12399
12400 /* The generation is finished, we can insert everything */
12401 ckch_store_replace(old_ckchs, new_ckchs);
12402
12403 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12404
12405 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12406
12407 return 0;
12408
12409error:
12410 ckch_store_free(new_ckchs);
12411 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12412 WILL_LJMP(luaL_error(L, "%s", err));
12413 free(err);
12414
12415 return 0;
12416}
12417
12418/*
12419 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12420 * from the table in parameter.
12421 *
12422 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12423 * means it does not need to have a transaction since everything is done in the
12424 * same function.
12425 *
12426 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12427 *
12428 */
12429__LJMP static int hlua_ckch_set(lua_State *L)
12430{
12431 struct hlua *hlua;
12432 struct ckch_inst **lua_ckchi;
12433 struct ckch_store **lua_ckchs;
12434 struct ckch_store *old_ckchs = NULL;
12435 struct ckch_store *new_ckchs = NULL;
12436 int errcode = 0;
12437 char *err = NULL;
12438 struct cert_exts *cert_ext = NULL;
12439 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012440 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012441 int ret;
12442
12443 if (lua_type(L, -1) != LUA_TTABLE)
12444 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12445
12446 hlua = hlua_gethlua(L);
12447
12448 /* FIXME: this should not return an error but should come back later */
12449 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12450 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12451
12452 ret = lua_getfield(L, -1, "filename");
12453 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012454 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012455 errcode |= ERR_ALERT | ERR_FATAL;
12456 goto end;
12457 }
12458 filename = (char *)lua_tostring(L, -1);
12459
12460
12461 /* look for the filename in the tree */
12462 old_ckchs = ckchs_lookup(filename);
12463 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012464 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012465 errcode |= ERR_ALERT | ERR_FATAL;
12466 goto end;
12467 }
12468 /* TODO: handle extra_files_noext */
12469
12470 new_ckchs = ckchs_dup(old_ckchs);
12471 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012472 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012473 errcode |= ERR_ALERT | ERR_FATAL;
12474 goto end;
12475 }
12476
William Lallemand52ddd992022-11-22 11:51:53 +010012477 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012478
12479 /* loop on the field in the table, which have the same name as the
12480 * possible extensions of files */
12481 lua_pushnil(L);
12482 while (lua_next(L, 1)) {
12483 int i;
12484 const char *field = lua_tostring(L, -2);
12485 char *payload = (char *)lua_tostring(L, -1);
12486
12487 if (!field || strcmp(field, "filename") == 0) {
12488 lua_pop(L, 1);
12489 continue;
12490 }
12491
12492 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12493 if (strcmp(field, cert_exts[i].ext) == 0) {
12494 cert_ext = &cert_exts[i];
12495 break;
12496 }
12497 }
12498
12499 /* this is the default type, the field is not supported */
12500 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012501 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012502 errcode |= ERR_ALERT | ERR_FATAL;
12503 goto end;
12504 }
12505
12506 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012507 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012508 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012509 errcode |= ERR_ALERT | ERR_FATAL;
12510 goto end;
12511 }
12512 lua_pop(L, 1);
12513 }
12514
12515 /* store the pointers on the lua stack */
12516 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12517 lua_ckchs[0] = old_ckchs;
12518 lua_ckchs[1] = new_ckchs;
12519 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12520 *lua_ckchi = NULL;
12521
12522 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12523 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12524
12525end:
12526 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12527
12528 if (errcode & ERR_CODE) {
12529 ckch_store_free(new_ckchs);
12530 WILL_LJMP(luaL_error(L, "%s", err));
12531 }
12532 free(err);
12533
12534 return 0;
12535}
12536
William Lallemand52139182022-03-30 15:05:42 +020012537#else
12538
12539__LJMP static int hlua_ckch_set(lua_State *L)
12540{
12541 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12542
12543 return 0;
12544}
12545#endif /* ! USE_OPENSSL */
12546
12547
12548
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012549/* This function can fail with an abort() due to an Lua critical error.
12550 * We are in the initialisation process of HAProxy, this abort() is
12551 * tolerated.
12552 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012553int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012554{
12555 struct hlua_init_function *init;
12556 const char *msg;
12557 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012558 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012559 const char *kind;
12560 const char *trace;
12561 int return_status = 1;
12562#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12563 int nres;
12564#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012565
Willy Tarreaucdb53462020-12-02 12:12:00 +010012566 /* disable memory limit checks if limit is not set */
12567 if (!hlua_global_allocator.limit)
12568 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12569
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012570 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012571 if (setjmp(safe_ljmp_env) != 0) {
12572 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012573 if (lua_type(L, -1) == LUA_TSTRING)
12574 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012575 else
12576 error = "critical error";
12577 fprintf(stderr, "Lua post-init: %s.\n", error);
12578 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012579 } else {
12580 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012581 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012582
Thierry Fournierc7492592020-11-28 23:57:24 +010012583 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012584 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012585 /* function ref should be released right away since it was pushed
12586 * on the stack and will not be used anymore
12587 */
12588 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012589
12590#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012591 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012592#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012593 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012594#endif
12595 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012596 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012597
12598 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012599 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012600 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012601
12602 case LUA_ERRERR:
12603 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012604 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012605 case LUA_ERRRUN:
12606 if (!kind)
12607 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012608 msg = lua_tostring(L, -1);
12609 lua_settop(L, 0); /* Empty the stack. */
12610 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012611 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012612 if (msg)
12613 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12614 else
12615 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12616 return_status = 0;
12617 break;
12618
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012619 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012620 /* Unknown error */
12621 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012622 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012623 case LUA_YIELD:
12624 /* yield is not configured at this step, this state doesn't happen */
12625 if (!kind)
12626 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012627 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012628 case LUA_ERRMEM:
12629 if (!kind)
12630 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012631 lua_settop(L, 0);
12632 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012633 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012634 ha_alert("Lua init: %s: %s\n", kind, trace);
12635 return_status = 0;
12636 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012637 }
Thierry Fournier670db242020-11-28 10:49:59 +010012638 if (!return_status)
12639 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012640 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012641
12642 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012643 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012644}
12645
Thierry Fournierb8cef172020-11-28 15:37:17 +010012646int hlua_post_init()
12647{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012648 int ret;
12649 int i;
12650 int errors;
12651 char *err = NULL;
12652 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012653 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012654
Willy Tarreaub1310492021-08-30 09:35:18 +020012655#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012656 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012657 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012658 int saved_used_backed = global.ssl_used_backend;
12659 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012660 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012661 global.ssl_used_backend = saved_used_backed;
12662 }
12663#endif
12664
Thierry Fournierc7492592020-11-28 23:57:24 +010012665 /* Perform post init of common thread */
12666 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012667 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012668 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12669 if (ret == 0)
12670 return 0;
12671
12672 /* init remaining lua states and load files */
12673 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12674
12675 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012676 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012677
12678 /* Init lua state */
12679 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12680
12681 /* Load lua files */
12682 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12683 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12684 if (ret != 0) {
12685 ha_alert("Lua init: %s\n", err);
12686 return 0;
12687 }
12688 }
12689 }
12690
12691 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012692 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012693
12694 /* Execute post init for all states */
12695 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12696
12697 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012698 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012699
12700 /* run post init */
12701 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12702 if (ret == 0)
12703 return 0;
12704 }
12705
12706 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012707 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012708
12709 /* control functions registering. Each function must have:
12710 * - only the function_ref[0] set positive and all other to -1
12711 * - only the function_ref[0] set to -1 and all other positive
12712 * This ensure a same reference is not used both in shared
12713 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012714 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012715 * complicated to found for the end user.
12716 */
12717 errors = 0;
12718 list_for_each_entry(fcn, &referenced_functions, l) {
12719 ret = 0;
12720 for (i = 1; i < global.nbthread + 1; i++) {
12721 if (fcn->function_ref[i] == -1)
12722 ret--;
12723 else
12724 ret++;
12725 }
12726 if (abs(ret) != global.nbthread) {
12727 ha_alert("Lua function '%s' is not referenced in all thread. "
12728 "Expect function in all thread or in none thread.\n", fcn->name);
12729 errors++;
12730 continue;
12731 }
12732
12733 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012734 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12735 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012736 "exclusive.\n", fcn->name);
12737 errors++;
12738 }
12739 }
12740
Christopher Faulet69c581a2021-05-31 08:54:04 +020012741 /* Do the same with registered filters */
12742 list_for_each_entry(reg_flt, &referenced_filters, l) {
12743 ret = 0;
12744 for (i = 1; i < global.nbthread + 1; i++) {
12745 if (reg_flt->flt_ref[i] == -1)
12746 ret--;
12747 else
12748 ret++;
12749 }
12750 if (abs(ret) != global.nbthread) {
12751 ha_alert("Lua filter '%s' is not referenced in all thread. "
12752 "Expect function in all thread or in none thread.\n", reg_flt->name);
12753 errors++;
12754 continue;
12755 }
12756
12757 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12758 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12759 "and per-thread Lua context (through lua-load-per-thread). these two context "
12760 "exclusive.\n", fcn->name);
12761 errors++;
12762 }
12763 }
12764
12765
Thierry Fournier59f11be2020-11-29 00:37:41 +010012766 if (errors > 0)
12767 return 0;
12768
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012769 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012770 * -1 in order to have probably a segfault if someone use it
12771 */
12772 hlua_state_id = -1;
12773
12774 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012775}
12776
Willy Tarreau32f61e22015-03-18 17:54:59 +010012777/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12778 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12779 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012780 * allocation. <nsize> is the requested new size. A new allocation is
12781 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010012782 * zero. This one verifies that the limits are respected but is optimized
12783 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012784 *
12785 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
12786 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
12787 * that and will simply allocate zero as if it were the result of malloc(0),
12788 * so mapping this onto realloc() will lead to memory leaks on non-glibc
12789 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010012790 */
12791static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
12792{
12793 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010012794 size_t limit, old, new;
12795
12796 /* a limit of ~0 means unlimited and boot complete, so there's no need
12797 * for accounting anymore.
12798 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012799 if (likely(~zone->limit == 0)) {
12800 if (!nsize)
12801 ha_free(&ptr);
12802 else
12803 ptr = realloc(ptr, nsize);
12804 return ptr;
12805 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010012806
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012807 if (!ptr)
12808 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012809
Willy Tarreaucdb53462020-12-02 12:12:00 +010012810 /* enforce strict limits across all threads */
12811 limit = zone->limit;
12812 old = _HA_ATOMIC_LOAD(&zone->allocated);
12813 do {
12814 new = old + nsize - osize;
12815 if (unlikely(nsize && limit && new > limit))
12816 return NULL;
12817 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012818
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012819 if (!nsize)
12820 ha_free(&ptr);
12821 else
12822 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012823
12824 if (unlikely(!ptr && nsize)) // failed
12825 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12826
12827 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012828 return ptr;
12829}
12830
Thierry Fournierecb83c22020-11-28 15:49:44 +010012831/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012832 * We are in the initialisation process of HAProxy, this abort() is
12833 * tolerated.
12834 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012835lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012836{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012837 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012838 int idx;
12839 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012840 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012841 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012842 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012843 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012844 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012845 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012846
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012847 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012848 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012849
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012850 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012851 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012852 *context = NULL;
12853
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012854 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012855 * the Lua function can fail with an abort. We are in the initialisation
12856 * process of HAProxy, this abort() is tolerated.
12857 */
12858
Thierry Fournier3c539322020-11-28 16:05:05 +010012859 /* Call post initialisation function in safe environment. */
12860 if (setjmp(safe_ljmp_env) != 0) {
12861 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012862 if (lua_type(L, -1) == LUA_TSTRING)
12863 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012864 else
12865 error_msg = "critical error";
12866 fprintf(stderr, "Lua init: %s.\n", error_msg);
12867 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012868 } else {
12869 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012870 }
12871
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012872 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012873 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012874#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12875#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12876#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012877 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012878#endif
12879#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012880 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012881#endif
12882#undef HLUA_PREPEND_PATH_TOSTRING
12883#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012884
Thierry Fournier59f11be2020-11-29 00:37:41 +010012885 /* Apply configured prepend path */
12886 list_for_each_entry(pp, &prepend_path_list, l)
12887 hlua_prepend_path(L, pp->type, pp->path);
12888
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012889 /*
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +020012890 * Override some lua functions.
12891 *
12892 */
12893
12894 /* push our "safe" coroutine.create() function */
12895 lua_getglobal(L, "coroutine");
12896 lua_pushcclosure(L, hlua_coroutine_create, 0);
12897 lua_setfield(L, -2, "create");
12898
12899 /*
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012900 *
12901 * Create "core" object.
12902 *
12903 */
12904
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012905 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012906 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012907
Thierry Fournierecb83c22020-11-28 15:49:44 +010012908 /* set the thread id */
12909 hlua_class_const_int(L, "thread", thread_num);
12910
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012911 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012912 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012913 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012914
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012915 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012916 hlua_class_function(L, "register_init", hlua_register_init);
12917 hlua_class_function(L, "register_task", hlua_register_task);
12918 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12919 hlua_class_function(L, "register_converters", hlua_register_converters);
12920 hlua_class_function(L, "register_action", hlua_register_action);
12921 hlua_class_function(L, "register_service", hlua_register_service);
12922 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012923 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012924 hlua_class_function(L, "yield", hlua_yield);
12925 hlua_class_function(L, "set_nice", hlua_set_nice);
12926 hlua_class_function(L, "sleep", hlua_sleep);
12927 hlua_class_function(L, "msleep", hlua_msleep);
12928 hlua_class_function(L, "add_acl", hlua_add_acl);
12929 hlua_class_function(L, "del_acl", hlua_del_acl);
12930 hlua_class_function(L, "set_map", hlua_set_map);
12931 hlua_class_function(L, "del_map", hlua_del_map);
12932 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012933 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010012934 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012935 hlua_class_function(L, "log", hlua_log);
12936 hlua_class_function(L, "Debug", hlua_log_debug);
12937 hlua_class_function(L, "Info", hlua_log_info);
12938 hlua_class_function(L, "Warning", hlua_log_warning);
12939 hlua_class_function(L, "Alert", hlua_log_alert);
12940 hlua_class_function(L, "done", hlua_done);
12941 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012942
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012943 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012944
12945 /*
12946 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012947 * Create "act" object.
12948 *
12949 */
12950
12951 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012952 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012953
12954 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012955 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12956 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12957 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12958 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12959 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12960 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12961 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12962 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012963
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012964 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012965
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012966 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012967
12968 /*
12969 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012970 * Create "Filter" object.
12971 *
12972 */
12973
12974 /* This table entry is the object "filter" base. */
12975 lua_newtable(L);
12976
12977 /* push flags and constants */
12978 hlua_class_const_int(L, "CONTINUE", 1);
12979 hlua_class_const_int(L, "WAIT", 0);
12980 hlua_class_const_int(L, "ERROR", -1);
12981
12982 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12983
Christopher Fauletc404f112020-02-26 15:03:09 +010012984 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12985 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12986 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12987
Christopher Faulet69c581a2021-05-31 08:54:04 +020012988 lua_setglobal(L, "filter");
12989
12990 /*
12991 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012992 * Register class Map
12993 *
12994 */
12995
12996 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012997 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012998
12999 /* register pattern types. */
13000 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013001 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013002 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013003 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013004 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013005 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013006
13007 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013008 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013009
13010 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013011 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013012
Ilya Shipitsind4259502020-04-08 01:07:56 +050013013 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013014 lua_pushstring(L, "__index");
13015 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013016
13017 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013018 hlua_class_function(L, "lookup", hlua_map_lookup);
13019 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013020
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013021 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013022
Thierry Fournier45e78d72016-02-19 18:34:46 +010013023 /* Register previous table in the registry with reference and named entry.
13024 * The function hlua_register_metatable() pops the stack, so we
13025 * previously create a copy of the table.
13026 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013027 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
13028 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013029
13030 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013031 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013032
13033 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013034 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013035
13036 /*
13037 *
William Lallemand30fcca12022-03-30 12:03:12 +020013038 * Register "CertCache" class
13039 *
13040 */
13041
13042 /* Create and fill the metatable. */
13043 lua_newtable(L);
13044 /* Register */
13045 hlua_class_function(L, "set", hlua_ckch_set);
13046 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
13047
13048 /*
13049 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013050 * Register class Channel
13051 *
13052 */
13053
13054 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013055 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013056
Ilya Shipitsind4259502020-04-08 01:07:56 +050013057 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013058 lua_pushstring(L, "__index");
13059 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013060
13061 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013062 hlua_class_function(L, "data", hlua_channel_get_data);
13063 hlua_class_function(L, "line", hlua_channel_get_line);
13064 hlua_class_function(L, "set", hlua_channel_set_data);
13065 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013066 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013067 hlua_class_function(L, "prepend", hlua_channel_prepend);
13068 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013069 hlua_class_function(L, "send", hlua_channel_send);
13070 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013071 hlua_class_function(L, "input", hlua_channel_get_in_len);
13072 hlua_class_function(L, "output", hlua_channel_get_out_len);
13073 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013074 hlua_class_function(L, "is_full", hlua_channel_is_full);
13075 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013076
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013077 /* Deprecated API */
13078 hlua_class_function(L, "get", hlua_channel_get);
13079 hlua_class_function(L, "dup", hlua_channel_dup);
13080 hlua_class_function(L, "getline", hlua_channel_getline);
13081 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13082 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13083
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013084 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013085
13086 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013087 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013088
13089 /*
13090 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013091 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013092 *
13093 */
13094
13095 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013096 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013097
Ilya Shipitsind4259502020-04-08 01:07:56 +050013098 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013099 lua_pushstring(L, "__index");
13100 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013101
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013102 /* Browse existing fetches and create the associated
13103 * object method.
13104 */
13105 sf = NULL;
13106 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013107 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13108 * by an underscore.
13109 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013110 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013111 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013112 if (*p == '.' || *p == '-' || *p == '+')
13113 *p = '_';
13114
13115 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013116 lua_pushstring(L, trash.area);
13117 lua_pushlightuserdata(L, sf);
13118 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13119 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013120 }
13121
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013122 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013123
13124 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013125 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013126
13127 /*
13128 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013129 * Register class Converters
13130 *
13131 */
13132
13133 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013134 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013135
13136 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013137 lua_pushstring(L, "__index");
13138 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013139
13140 /* Browse existing converters and create the associated
13141 * object method.
13142 */
13143 sc = NULL;
13144 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013145 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13146 * by an underscore.
13147 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013148 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013149 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013150 if (*p == '.' || *p == '-' || *p == '+')
13151 *p = '_';
13152
13153 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013154 lua_pushstring(L, trash.area);
13155 lua_pushlightuserdata(L, sc);
13156 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13157 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013158 }
13159
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013160 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013161
13162 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013163 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013164
13165 /*
13166 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013167 * Register class HTTP
13168 *
13169 */
13170
13171 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013172 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013173
Ilya Shipitsind4259502020-04-08 01:07:56 +050013174 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013175 lua_pushstring(L, "__index");
13176 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013177
13178 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013179 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13180 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13181 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13182 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13183 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13184 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13185 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13186 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13187 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13188 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013189
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013190 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13191 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13192 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13193 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13194 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13195 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13196 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013197
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013198 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013199
13200 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013201 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013202
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013203 /*
13204 *
13205 * Register class HTTPMessage
13206 *
13207 */
13208
13209 /* Create and fill the metatable. */
13210 lua_newtable(L);
13211
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013212 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013213 lua_pushstring(L, "__index");
13214 lua_newtable(L);
13215
13216 /* Register Lua functions. */
13217 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13218 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13219 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13220 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13221 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13222 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13223 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13224 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13225 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13226 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13227 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13228 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13229 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13230 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13231 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13232 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13233 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13234 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13235
13236 hlua_class_function(L, "body", hlua_http_msg_get_body);
13237 hlua_class_function(L, "set", hlua_http_msg_set_data);
13238 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13239 hlua_class_function(L, "append", hlua_http_msg_append);
13240 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13241 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13242 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13243 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13244
13245 hlua_class_function(L, "send", hlua_http_msg_send);
13246 hlua_class_function(L, "forward", hlua_http_msg_forward);
13247
13248 lua_rawset(L, -3);
13249
13250 /* Register previous table in the registry with reference and named entry. */
13251 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013252
13253 /*
13254 *
13255 * Register class HTTPClient
13256 *
13257 */
13258
13259 /* Create and fill the metatable. */
13260 lua_newtable(L);
13261 lua_pushstring(L, "__index");
13262 lua_newtable(L);
13263 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013264 hlua_class_function(L, "head", hlua_httpclient_head);
13265 hlua_class_function(L, "put", hlua_httpclient_put);
13266 hlua_class_function(L, "post", hlua_httpclient_post);
13267 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013268 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013269 /* Register the garbage collector entry. */
13270 lua_pushstring(L, "__gc");
13271 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13272 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13273
William Lallemand3956c4e2021-09-21 16:25:15 +020013274
13275
13276 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013277 /*
13278 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013279 * Register class AppletTCP
13280 *
13281 */
13282
13283 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013284 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013285
Ilya Shipitsind4259502020-04-08 01:07:56 +050013286 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013287 lua_pushstring(L, "__index");
13288 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013289
13290 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013291 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13292 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13293 hlua_class_function(L, "send", hlua_applet_tcp_send);
13294 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13295 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13296 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13297 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13298 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013299
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013300 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013301
13302 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013303 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013304
13305 /*
13306 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013307 * Register class AppletHTTP
13308 *
13309 */
13310
13311 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013312 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013313
Ilya Shipitsind4259502020-04-08 01:07:56 +050013314 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013315 lua_pushstring(L, "__index");
13316 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013317
13318 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013319 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13320 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13321 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13322 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13323 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13324 hlua_class_function(L, "getline", hlua_applet_http_getline);
13325 hlua_class_function(L, "receive", hlua_applet_http_recv);
13326 hlua_class_function(L, "send", hlua_applet_http_send);
13327 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13328 hlua_class_function(L, "set_status", hlua_applet_http_status);
13329 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013330
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013331 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013332
13333 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013334 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013335
13336 /*
13337 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013338 * Register class TXN
13339 *
13340 */
13341
13342 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013343 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013344
Ilya Shipitsind4259502020-04-08 01:07:56 +050013345 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013346 lua_pushstring(L, "__index");
13347 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013348
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013349 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013350 hlua_class_function(L, "set_priv", hlua_set_priv);
13351 hlua_class_function(L, "get_priv", hlua_get_priv);
13352 hlua_class_function(L, "set_var", hlua_set_var);
13353 hlua_class_function(L, "unset_var", hlua_unset_var);
13354 hlua_class_function(L, "get_var", hlua_get_var);
13355 hlua_class_function(L, "done", hlua_txn_done);
13356 hlua_class_function(L, "reply", hlua_txn_reply_new);
13357 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13358 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13359 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13360 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13361 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13362 hlua_class_function(L, "deflog", hlua_txn_deflog);
13363 hlua_class_function(L, "log", hlua_txn_log);
13364 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13365 hlua_class_function(L, "Info", hlua_txn_log_info);
13366 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13367 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013368
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013369 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013370
13371 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013372 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013373
13374 /*
13375 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013376 * Register class reply
13377 *
13378 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013379 lua_newtable(L);
13380 lua_pushstring(L, "__index");
13381 lua_newtable(L);
13382 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13383 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13384 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13385 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13386 lua_settable(L, -3); /* Sets the __index entry. */
13387 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013388
13389
13390 /*
13391 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013392 * Register class Socket
13393 *
13394 */
13395
13396 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013397 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013398
Ilya Shipitsind4259502020-04-08 01:07:56 +050013399 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013400 lua_pushstring(L, "__index");
13401 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013402
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013403#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013404 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013405#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013406 hlua_class_function(L, "connect", hlua_socket_connect);
13407 hlua_class_function(L, "send", hlua_socket_send);
13408 hlua_class_function(L, "receive", hlua_socket_receive);
13409 hlua_class_function(L, "close", hlua_socket_close);
13410 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13411 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13412 hlua_class_function(L, "setoption", hlua_socket_setoption);
13413 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013414
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013415 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013416
13417 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013418 lua_pushstring(L, "__gc");
13419 lua_pushcclosure(L, hlua_socket_gc, 0);
13420 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013421
13422 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013423 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013424
Thierry Fournieraafc7772020-12-04 11:47:47 +010013425 lua_atpanic(L, hlua_panic_safe);
13426
13427 return L;
13428}
13429
13430void hlua_init(void) {
13431 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013432 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013433#ifdef USE_OPENSSL
13434 struct srv_kw *kw;
13435 int tmp_error;
13436 char *error;
13437 char *args[] = { /* SSL client configuration. */
13438 "ssl",
13439 "verify",
13440 "none",
13441 NULL
13442 };
13443#endif
13444
13445 /* Init post init function list head */
13446 for (i = 0; i < MAX_THREADS + 1; i++)
13447 LIST_INIT(&hlua_init_functions[i]);
13448
13449 /* Init state for common/shared lua parts */
13450 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013451 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013452 hlua_states[0] = hlua_init_state(0);
13453
13454 /* Init state 1 for thread 0. We have at least one thread. */
13455 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013456 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013457 hlua_states[1] = hlua_init_state(1);
13458
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013459 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013460 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013461 if (!socket_proxy) {
13462 fprintf(stderr, "Lua init: %s\n", errmsg);
13463 exit(1);
13464 }
13465 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013466
13467 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013468 socket_tcp = new_server(socket_proxy);
13469 if (!socket_tcp) {
13470 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13471 exit(1);
13472 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013473
13474#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013475 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013476 socket_ssl = new_server(socket_proxy);
13477 if (!socket_ssl) {
13478 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13479 exit(1);
13480 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013481
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013482 socket_ssl->use_ssl = 1;
13483 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013484
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013485 for (i = 0; args[i] != NULL; i++) {
13486 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013487 /*
13488 *
13489 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013490 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013491 * features like client certificates and ssl_verify.
13492 *
13493 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013494 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013495 if (tmp_error != 0) {
13496 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13497 abort(); /* This must be never arrives because the command line
13498 not editable by the user. */
13499 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013500 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013501 }
13502 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013503#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013504
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013505}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013506
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013507static void hlua_deinit()
13508{
Willy Tarreau186f3762020-12-04 11:48:12 +010013509 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013510 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13511
13512 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13513 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013514
13515 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13516 if (hlua_states[thr])
13517 lua_close(hlua_states[thr]);
13518 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013519
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013520 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013521
Willy Tarreau0f143af2021-03-05 10:41:48 +010013522#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013523 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013524#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013525
13526 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013527}
13528
13529REGISTER_POST_DEINIT(hlua_deinit);
13530
Willy Tarreau80713382018-11-26 10:19:54 +010013531static void hlua_register_build_options(void)
13532{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013533 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013534
Willy Tarreaubb57d942016-12-21 19:04:56 +010013535 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13536 hap_register_build_opts(ptr, 1);
13537}
Willy Tarreau80713382018-11-26 10:19:54 +010013538
13539INITCALL0(STG_REGISTER, hlua_register_build_options);