blob: 34672267537fa3de262f5f8380633058c0f48872 [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>
68
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 */
155void lua_take_global_lock()
156{
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
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Christopher Fauletd09cc512021-03-24 14:48:45 +0100501__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200502{
503 lua_Debug ar;
504 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200505 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200508 /* Fill fields:
509 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
510 * 'l': fills in the field currentline;
511 * 'n': fills in the field name and namewhat;
512 * 't': fills in the field istailcall;
513 */
514 lua_getinfo(L, "Slnt", &ar);
515
Willy Tarreau5c143402022-06-19 17:35:53 +0200516 /* skip these empty entries, usually they come from deep C functions */
517 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
518 continue;
519
520 /* Add separator */
521 if (b_data(msg))
522 chunk_appendf(msg, "%s", sep);
523
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 /* Append code localisation */
525 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100526 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200527 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100528 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200529
530 /*
531 * Get function name
532 *
533 * if namewhat is no empty, name is defined.
534 * what contains "Lua" for Lua function, "C" for C function,
535 * or "main" for main code.
536 */
537 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100544 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200545
546 else /* nothing left... */
547 chunk_appendf(msg, "?");
548
549
550 /* Display tailed call */
551 if (ar.istailcall)
552 chunk_appendf(msg, " ...");
553 }
554
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200555 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200556}
557
558
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559/* This function check the number of arguments available in the
560 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500561 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100562 */
563__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
564{
565 if (lua_gettop(L) == nb)
566 return;
567 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
568}
569
Mark Lakes22154b42018-01-29 14:38:40 -0800570/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100571 * and the line number where the error is encountered.
572 */
573static int hlua_pusherror(lua_State *L, const char *fmt, ...)
574{
575 va_list argp;
576 va_start(argp, fmt);
577 luaL_where(L, 1);
578 lua_pushvfstring(L, fmt, argp);
579 va_end(argp);
580 lua_concat(L, 2);
581 return 1;
582}
583
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584/* This functions is used with sample fetch and converters. It
585 * converts the HAProxy configuration argument in a lua stack
586 * values.
587 *
588 * It takes an array of "arg", and each entry of the array is
589 * converted and pushed in the LUA stack.
590 */
591static int hlua_arg2lua(lua_State *L, const struct arg *arg)
592{
593 switch (arg->type) {
594 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 case ARGT_TIME:
596 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100597 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 break;
599
600 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200601 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case ARGT_IPV4:
605 case ARGT_IPV6:
606 case ARGT_MSK4:
607 case ARGT_MSK6:
608 case ARGT_FE:
609 case ARGT_BE:
610 case ARGT_TAB:
611 case ARGT_SRV:
612 case ARGT_USR:
613 case ARGT_MAP:
614 default:
615 lua_pushnil(L);
616 break;
617 }
618 return 1;
619}
620
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500621/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500623 * with sample fetch wrappers. The input arguments are given to the
624 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100625 */
626static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
627{
628 switch (lua_type(L, ud)) {
629
630 case LUA_TNUMBER:
631 case LUA_TBOOLEAN:
632 arg->type = ARGT_SINT;
633 arg->data.sint = lua_tointeger(L, ud);
634 break;
635
636 case LUA_TSTRING:
637 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200638 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200639 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200640 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200641 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643
644 case LUA_TUSERDATA:
645 case LUA_TNIL:
646 case LUA_TTABLE:
647 case LUA_TFUNCTION:
648 case LUA_TTHREAD:
649 case LUA_TLIGHTUSERDATA:
650 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200651 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 break;
653 }
654 return 1;
655}
656
657/* the following functions are used to convert a struct sample
658 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500659 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100660 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100661static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200663 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100665 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200666 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 break;
668
669 case SMP_T_BIN:
670 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200671 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 break;
673
674 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200675 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
677 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
678 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
679 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
680 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
681 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
682 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
683 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
684 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200685 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100686 break;
687 default:
688 lua_pushnil(L);
689 break;
690 }
691 break;
692
693 case SMP_T_IPV4:
694 case SMP_T_IPV6:
695 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200696 if (sample_casts[smp->data.type][SMP_T_STR] &&
697 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200698 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100699 else
700 lua_pushnil(L);
701 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100702 default:
703 lua_pushnil(L);
704 break;
705 }
706 return 1;
707}
708
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709/* the following functions are used to convert a struct sample
710 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500711 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100712 */
713static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
714{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200715 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716
717 case SMP_T_BIN:
718 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200719 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100720 break;
721
722 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200723 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100724 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
725 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
726 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
727 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
728 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
729 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
730 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
731 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
732 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200733 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100734 break;
735 default:
736 lua_pushstring(L, "");
737 break;
738 }
739 break;
740
741 case SMP_T_SINT:
742 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100743 case SMP_T_IPV4:
744 case SMP_T_IPV6:
745 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 if (sample_casts[smp->data.type][SMP_T_STR] &&
747 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100749 else
750 lua_pushstring(L, "");
751 break;
752 default:
753 lua_pushstring(L, "");
754 break;
755 }
756 return 1;
757}
758
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100759/* the following functions are used to convert an Lua type in a
760 * struct sample. This is useful to provide data from a converter
761 * to the LUA code.
762 */
763static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
764{
765 switch (lua_type(L, ud)) {
766
767 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200768 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200769 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770 break;
771
772
773 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200774 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200775 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200779 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200781 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200782 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200783 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200784 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786
787 case LUA_TUSERDATA:
788 case LUA_TNIL:
789 case LUA_TTABLE:
790 case LUA_TFUNCTION:
791 case LUA_TTHREAD:
792 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200793 case LUA_TNONE:
794 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200795 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200796 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100797 break;
798 }
799 return 1;
800}
801
Ilya Shipitsind4259502020-04-08 01:07:56 +0500802/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800803 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100805 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500806 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200807 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100809__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100810 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811{
812 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200813 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100814 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200815 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200816 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200817 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200818 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100819
820 idx = 0;
821 min_arg = ARGM(mask);
822 mask >>= ARGM_BITS;
823
824 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200825 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 /* Check for mandatory arguments. */
828 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100829 if (idx < min_arg) {
830
831 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 if (idx > 0) {
833 msg = "Mandatory argument expected";
834 goto error;
835 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836
837 /* If first argument have a certain type, some default values
838 * may be used. See the function smp_resolve_args().
839 */
840 switch (mask & ARGT_MASK) {
841
842 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 if (!(p->cap & PR_CAP_FE)) {
844 msg = "Mandatory argument expected";
845 goto error;
846 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 argp[idx].data.prx = p;
848 argp[idx].type = ARGT_FE;
849 argp[idx+1].type = ARGT_STOP;
850 break;
851
852 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200853 if (!(p->cap & PR_CAP_BE)) {
854 msg = "Mandatory argument expected";
855 goto error;
856 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100857 argp[idx].data.prx = p;
858 argp[idx].type = ARGT_BE;
859 argp[idx+1].type = ARGT_STOP;
860 break;
861
862 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +0200863 if (!p->table) {
864 msg = "Mandatory argument expected";
865 goto error;
866 }
867 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 argp[idx].type = ARGT_TAB;
869 argp[idx+1].type = ARGT_STOP;
870 break;
871
872 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200873 msg = "Mandatory argument expected";
874 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100875 break;
876 }
877 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200878 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 }
880
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500881 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 if ((mask & ARGT_MASK) == ARGT_STOP &&
883 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200884 msg = "Last argument expected";
885 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100886 }
887
888 if ((mask & ARGT_MASK) == ARGT_STOP &&
889 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100891 }
892
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 /* Convert some argument types. All string in argp[] are for not
894 * duplicated yet.
895 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100896 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100897 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200898 if (argp[idx].type != ARGT_SINT) {
899 msg = "integer expected";
900 goto error;
901 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100902 argp[idx].type = ARGT_SINT;
903 break;
904
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200906 if (argp[idx].type != ARGT_SINT) {
907 msg = "integer expected";
908 goto error;
909 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200910 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100911 break;
912
913 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200914 if (argp[idx].type != ARGT_SINT) {
915 msg = "integer expected";
916 goto error;
917 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200918 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100919 break;
920
921 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200922 if (argp[idx].type != ARGT_STR) {
923 msg = "string expected";
924 goto error;
925 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200926 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200927 if (!argp[idx].data.prx) {
928 msg = "frontend doesn't exist";
929 goto error;
930 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100931 argp[idx].type = ARGT_FE;
932 break;
933
934 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200935 if (argp[idx].type != ARGT_STR) {
936 msg = "string expected";
937 goto error;
938 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200939 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200940 if (!argp[idx].data.prx) {
941 msg = "backend doesn't exist";
942 goto error;
943 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100944 argp[idx].type = ARGT_BE;
945 break;
946
947 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200948 if (argp[idx].type != ARGT_STR) {
949 msg = "string expected";
950 goto error;
951 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200952 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200953 if (!argp[idx].data.t) {
954 msg = "table doesn't exist";
955 goto error;
956 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100957 argp[idx].type = ARGT_TAB;
958 break;
959
960 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200961 if (argp[idx].type != ARGT_STR) {
962 msg = "string expected";
963 goto error;
964 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200965 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100966 if (sname) {
967 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200969 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200970 if (!px) {
971 msg = "backend doesn't exist";
972 goto error;
973 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100974 }
975 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200976 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100979 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200980 if (!argp[idx].data.srv) {
981 msg = "server doesn't exist";
982 goto error;
983 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100984 argp[idx].type = ARGT_SRV;
985 break;
986
987 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200988 if (argp[idx].type != ARGT_STR) {
989 msg = "string expected";
990 goto error;
991 }
992 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
993 msg = "invalid IPv4 address";
994 goto error;
995 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100996 argp[idx].type = ARGT_IPV4;
997 break;
998
999 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001000 if (argp[idx].type == ARGT_SINT)
1001 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1002 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001003 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1004 msg = "invalid IPv4 mask";
1005 goto error;
1006 }
1007 }
1008 else {
1009 msg = "integer or string expected";
1010 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001011 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001012 argp[idx].type = ARGT_MSK4;
1013 break;
1014
1015 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001016 if (argp[idx].type != ARGT_STR) {
1017 msg = "string expected";
1018 goto error;
1019 }
1020 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1021 msg = "invalid IPv6 address";
1022 goto error;
1023 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 argp[idx].type = ARGT_IPV6;
1025 break;
1026
1027 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001028 if (argp[idx].type == ARGT_SINT)
1029 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1030 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001031 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1032 msg = "invalid IPv6 mask";
1033 goto error;
1034 }
1035 }
1036 else {
1037 msg = "integer or string expected";
1038 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001039 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001040 argp[idx].type = ARGT_MSK6;
1041 break;
1042
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001043 case ARGT_REG:
1044 if (argp[idx].type != ARGT_STR) {
1045 msg = "string expected";
1046 goto error;
1047 }
1048 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1049 if (!reg) {
1050 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1051 argp[idx].data.str.area, err);
1052 free(err);
1053 goto error;
1054 }
1055 argp[idx].type = ARGT_REG;
1056 argp[idx].data.reg = reg;
1057 break;
1058
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001059 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001060 if (argp[idx].type != ARGT_STR) {
1061 msg = "string expected";
1062 goto error;
1063 }
1064 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001065 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001066 ul = p->uri_auth->userlist;
1067 else
1068 ul = auth_find_userlist(argp[idx].data.str.area);
1069
1070 if (!ul) {
1071 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1072 goto error;
1073 }
1074 argp[idx].type = ARGT_USR;
1075 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001076 break;
1077
1078 case ARGT_STR:
1079 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1080 msg = "unable to duplicate string arg";
1081 goto error;
1082 }
1083 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001084 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001085
Christopher Fauletd25d9262020-08-06 11:04:46 +02001086 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001087 msg = "type not yet supported";
1088 goto error;
1089 break;
1090
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001091 }
1092
1093 /* Check for type of argument. */
1094 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001095 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1096 arg_type_names[(mask & ARGT_MASK)],
1097 arg_type_names[argp[idx].type & ARGT_MASK]);
1098 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001099 }
1100
1101 /* Next argument. */
1102 mask >>= ARGT_BITS;
1103 idx++;
1104 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 return 0;
1106
1107 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001108 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001109 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001110 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1111 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001112}
1113
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001115 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001116 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117 *
1118 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 * - hlua_sethlua : create the association between hlua context and lua_state.
1120 */
1121static inline struct hlua *hlua_gethlua(lua_State *L)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua = lua_getextraspace(L);
1124 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126static inline void hlua_sethlua(struct hlua *hlua)
1127{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001128 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1129 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001130}
1131
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001132/* Will return a non-NULL string indicating the Lua call trace if the caller
1133 * currently is executing from within a Lua function. One line per entry will
1134 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1135 * Lua function is not detected, NULL is returned.
1136 */
1137const char *hlua_show_current_location(const char *pfx)
1138{
1139 lua_State *L;
1140 lua_Debug ar;
1141
1142 /* global or per-thread stack initializing ? */
1143 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1144 return hlua_traceback(L, pfx);
1145
1146 /* per-thread stack running ? */
1147 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1148 return hlua_traceback(L, pfx);
1149
1150 /* global stack running ? */
1151 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1152 return hlua_traceback(L, pfx);
1153
1154 return NULL;
1155}
1156
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001157/* This function is used to send logs. It try to send on screen (stderr)
1158 * and on the default syslog server.
1159 */
1160static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1161{
1162 struct tm tm;
1163 char *p;
1164
1165 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001166 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001167 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001168 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001169 /* Break the message if exceed the buffer size. */
1170 *(p-4) = ' ';
1171 *(p-3) = '.';
1172 *(p-2) = '.';
1173 *(p-1) = '.';
1174 break;
1175 }
Willy Tarreau90807112020-02-25 08:16:33 +01001176 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001177 *p = *msg;
1178 else
1179 *p = '.';
1180 }
1181 *p = '\0';
1182
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001183 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001184 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001185 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1186 return;
1187
Willy Tarreaua678b432015-08-28 10:14:59 +02001188 get_localtime(date.tv_sec, &tm);
1189 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001190 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001191 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001192 fflush(stderr);
1193 }
1194}
1195
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196/* This function just ensure that the yield will be always
1197 * returned with a timeout and permit to set some flags
1198 */
1199__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001200 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001201{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001202 struct hlua *hlua;
1203
1204 /* Get hlua struct, or NULL if we execute from main lua state */
1205 hlua = hlua_gethlua(L);
1206 if (!hlua) {
1207 return;
1208 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
1210 /* Set the wake timeout. If timeout is required, we set
1211 * the expiration time.
1212 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001213 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001215 hlua->flags |= flags;
1216
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001217 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001218 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001219}
1220
Willy Tarreau87b09662015-04-03 00:22:06 +02001221/* This function initialises the Lua environment stored in the stream.
1222 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001223 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001224 *
1225 * This function is particular. it initialises a new Lua thread. If the
1226 * initialisation fails (example: out of memory error), the lua function
1227 * throws an error (longjmp).
1228 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001230 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001231 * threads appear, the safe environment set a lock to ensure only one
1232 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001233 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001234 *
1235 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001237 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001238 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001239 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001240 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001241 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001242 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001243int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001244{
1245 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001246 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001247 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001248 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001249 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001250 LIST_INIT(&lua->com);
William Lallemandbb581422022-10-20 10:57:28 +02001251 LIST_INIT(&lua->hc_list);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001252 if (!already_safe) {
1253 if (!SET_SAFE_LJMP_PARENT(lua)) {
1254 lua->Tref = LUA_REFNIL;
1255 return 0;
1256 }
1257 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001258 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001259 if (!lua->T) {
1260 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001261 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001262 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001263 return 0;
1264 }
1265 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001266 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001267 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001268 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001269 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001270 return 1;
1271}
1272
William Lallemandbb581422022-10-20 10:57:28 +02001273/* kill all associated httpclient to this hlua task */
1274static void hlua_httpclient_destroy_all(struct hlua *hlua)
1275{
1276 struct hlua_httpclient *hlua_hc, *back;
1277
1278 list_for_each_entry_safe(hlua_hc, back, &hlua->hc_list, by_hlua) {
1279 if (hlua_hc->hc)
1280 httpclient_stop_and_destroy(hlua_hc->hc);
1281 hlua_hc->hc = NULL;
William Lallemand94dbfed2022-12-08 11:11:36 +01001282 LIST_DEL_INIT(&hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02001283 }
1284}
1285
1286
Willy Tarreau87b09662015-04-03 00:22:06 +02001287/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001288 * is destroyed. The destroy also the memory context. The struct "lua"
1289 * is not freed.
1290 */
1291void hlua_ctx_destroy(struct hlua *lua)
1292{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001293 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001294 return;
1295
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001296 if (!lua->T)
1297 goto end;
1298
William Lallemandbb581422022-10-20 10:57:28 +02001299 /* clean all running httpclient */
1300 hlua_httpclient_destroy_all(lua);
1301
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001302 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001303 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001304
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001305 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001306 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001307 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001308 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001309
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001310 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001311 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001312 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001313 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001314 /* Forces a garbage collecting process. If the Lua program is finished
1315 * without error, we run the GC on the thread pointer. Its freed all
1316 * the unused memory.
1317 * If the thread is finnish with an error or is currently yielded,
1318 * it seems that the GC applied on the thread doesn't clean anything,
1319 * so e run the GC on the main thread.
1320 * NOTE: maybe this action locks all the Lua threads untiml the en of
1321 * the garbage collection.
1322 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001323 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001324 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001325 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001326 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001327 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001328 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001329
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001330 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001331
1332end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001333 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001334}
1335
1336/* This function is used to restore the Lua context when a coroutine
1337 * fails. This function copy the common memory between old coroutine
1338 * and the new coroutine. The old coroutine is destroyed, and its
1339 * replaced by the new coroutine.
1340 * If the flag "keep_msg" is set, the last entry of the old is assumed
1341 * as string error message and it is copied in the new stack.
1342 */
1343static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1344{
1345 lua_State *T;
1346 int new_ref;
1347
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001348 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001349 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001350 if (!T)
1351 return 0;
1352
1353 /* Copy last error message. */
1354 if (keep_msg)
1355 lua_xmove(lua->T, T, 1);
1356
1357 /* Copy data between the coroutines. */
1358 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1359 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001360 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001361
1362 /* Destroy old data. */
1363 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1364
1365 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001366 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001367
1368 /* Fill the struct with the new coroutine values. */
1369 lua->Mref = new_ref;
1370 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001371 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001372
1373 /* Set context. */
1374 hlua_sethlua(lua);
1375
1376 return 1;
1377}
1378
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001379void hlua_hook(lua_State *L, lua_Debug *ar)
1380{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001381 struct hlua *hlua;
1382
1383 /* Get hlua struct, or NULL if we execute from main lua state */
1384 hlua = hlua_gethlua(L);
1385 if (!hlua)
1386 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001387
1388 /* Lua cannot yield when its returning from a function,
1389 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001390 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001391 */
1392 if (lua_gethookmask(L) & LUA_MASKRET) {
1393 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1394 return;
1395 }
1396
1397 /* restore the interrupt condition. */
1398 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1399
1400 /* If we interrupt the Lua processing in yieldable state, we yield.
1401 * If the state is not yieldable, trying yield causes an error.
1402 */
1403 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001404 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001405
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001406 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001407 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001408 hlua->run_time += now_ms - hlua->start_time;
1409 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001410 lua_pushfstring(L, "execution timeout");
1411 WILL_LJMP(lua_error(L));
1412 }
1413
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001414 /* Update the start time. */
1415 hlua->start_time = now_ms;
1416
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001417 /* Try to interrupt the process at the end of the current
1418 * unyieldable function.
1419 */
1420 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001421}
1422
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423/* This function start or resumes the Lua stack execution. If the flag
1424 * "yield_allowed" if no set and the LUA stack execution returns a yield
1425 * The function return an error.
1426 *
1427 * The function can returns 4 values:
1428 * - HLUA_E_OK : The execution is terminated without any errors.
1429 * - HLUA_E_AGAIN : The execution must continue at the next associated
1430 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001431 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001432 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001433 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001434 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001435 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001436 * LUA code.
1437 */
1438static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1439{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001440#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1441 int nres;
1442#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001443 int ret;
1444 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001445 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001446
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001447 /* Initialise run time counter. */
1448 if (!HLUA_IS_RUNNING(lua))
1449 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001450
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001451 /* Lock the whole Lua execution. This lock must be before the
1452 * label "resume_execution".
1453 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001454 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001455 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001456
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001457resume_execution:
1458
1459 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1460 * instructions. it is used for preventing infinite loops.
1461 */
1462 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1463
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001464 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001465 HLUA_SET_RUN(lua);
1466 HLUA_CLR_CTRLYIELD(lua);
1467 HLUA_CLR_WAKERESWR(lua);
1468 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001469 HLUA_CLR_NOYIELD(lua);
1470 if (!yield_allowed)
1471 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001472
Christopher Fauletbc275a92020-02-26 14:55:16 +01001473 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001474 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001475 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001476
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001477 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001478#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001479 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001480#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001481 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001482#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001483 switch (ret) {
1484
1485 case LUA_OK:
1486 ret = HLUA_E_OK;
1487 break;
1488
1489 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001490 /* Check if the execution timeout is expired. It it is the case, we
1491 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001492 */
Willy Tarreau55542642021-10-08 09:33:24 +02001493 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001494 lua->run_time += now_ms - lua->start_time;
1495 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001496 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001497 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001498 break;
1499 }
1500 /* Process the forced yield. if the general yield is not allowed or
1501 * if no task were associated this the current Lua execution
1502 * coroutine, we resume the execution. Else we want to return in the
1503 * scheduler and we want to be waked up again, to continue the
1504 * current Lua execution. So we schedule our own task.
1505 */
1506 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001507 if (!yield_allowed || !lua->task)
1508 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001509 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001510 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001511 if (!yield_allowed) {
1512 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001513 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514 break;
1515 }
1516 ret = HLUA_E_AGAIN;
1517 break;
1518
1519 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001520
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001521 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001522 * because the errors ares the only one mean to return immediately
1523 * from and lua execution.
1524 */
1525 if (lua->flags & HLUA_EXIT) {
1526 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001527 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001528 break;
1529 }
1530
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001531 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001532 if (!lua_checkstack(lua->T, 1)) {
1533 ret = HLUA_E_ERR;
1534 break;
1535 }
1536 msg = lua_tostring(lua->T, -1);
1537 lua_settop(lua->T, 0); /* Empty the stack. */
1538 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001539 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001540 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001541 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001542 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001543 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001544 ret = HLUA_E_ERRMSG;
1545 break;
1546
1547 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001548 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001549 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001550 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001551 break;
1552
1553 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001554 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001555 if (!lua_checkstack(lua->T, 1)) {
1556 ret = HLUA_E_ERR;
1557 break;
1558 }
1559 msg = lua_tostring(lua->T, -1);
1560 lua_settop(lua->T, 0); /* Empty the stack. */
1561 lua_pop(lua->T, 1);
1562 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001563 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001564 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001565 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001566 ret = HLUA_E_ERRMSG;
1567 break;
1568
1569 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001570 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001571 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001572 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001573 break;
1574 }
1575
1576 switch (ret) {
1577 case HLUA_E_AGAIN:
1578 break;
1579
1580 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001581 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001582 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001583 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001584 break;
1585
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001586 case HLUA_E_ETMOUT:
1587 case HLUA_E_NOMEM:
1588 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001589 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001590 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001591 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001592 hlua_ctx_renew(lua, 0);
1593 break;
1594
1595 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001596 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001597 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001598 break;
1599 }
1600
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001601 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001602 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001603 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001604
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001605 return ret;
1606}
1607
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001608/* This function exit the current code. */
1609__LJMP static int hlua_done(lua_State *L)
1610{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001611 struct hlua *hlua;
1612
1613 /* Get hlua struct, or NULL if we execute from main lua state */
1614 hlua = hlua_gethlua(L);
1615 if (!hlua)
1616 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001617
1618 hlua->flags |= HLUA_EXIT;
1619 WILL_LJMP(lua_error(L));
1620
1621 return 0;
1622}
1623
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001624/* This function is an LUA binding. It provides a function
1625 * for deleting ACL from a referenced ACL file.
1626 */
1627__LJMP static int hlua_del_acl(lua_State *L)
1628{
1629 const char *name;
1630 const char *key;
1631 struct pat_ref *ref;
1632
1633 MAY_LJMP(check_args(L, 2, "del_acl"));
1634
1635 name = MAY_LJMP(luaL_checkstring(L, 1));
1636 key = MAY_LJMP(luaL_checkstring(L, 2));
1637
1638 ref = pat_ref_lookup(name);
1639 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001640 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001641
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001642 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001643 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001644 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001645 return 0;
1646}
1647
1648/* This function is an LUA binding. It provides a function
1649 * for deleting map entry from a referenced map file.
1650 */
1651static int hlua_del_map(lua_State *L)
1652{
1653 const char *name;
1654 const char *key;
1655 struct pat_ref *ref;
1656
1657 MAY_LJMP(check_args(L, 2, "del_map"));
1658
1659 name = MAY_LJMP(luaL_checkstring(L, 1));
1660 key = MAY_LJMP(luaL_checkstring(L, 2));
1661
1662 ref = pat_ref_lookup(name);
1663 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001664 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001665
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001666 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001667 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001668 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001669 return 0;
1670}
1671
1672/* This function is an LUA binding. It provides a function
1673 * for adding ACL pattern from a referenced ACL file.
1674 */
1675static int hlua_add_acl(lua_State *L)
1676{
1677 const char *name;
1678 const char *key;
1679 struct pat_ref *ref;
1680
1681 MAY_LJMP(check_args(L, 2, "add_acl"));
1682
1683 name = MAY_LJMP(luaL_checkstring(L, 1));
1684 key = MAY_LJMP(luaL_checkstring(L, 2));
1685
1686 ref = pat_ref_lookup(name);
1687 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001688 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001689
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001690 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001691 if (pat_ref_find_elt(ref, key) == NULL)
1692 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001693 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001694 return 0;
1695}
1696
1697/* This function is an LUA binding. It provides a function
1698 * for setting map pattern and sample from a referenced map
1699 * file.
1700 */
1701static int hlua_set_map(lua_State *L)
1702{
1703 const char *name;
1704 const char *key;
1705 const char *value;
1706 struct pat_ref *ref;
1707
1708 MAY_LJMP(check_args(L, 3, "set_map"));
1709
1710 name = MAY_LJMP(luaL_checkstring(L, 1));
1711 key = MAY_LJMP(luaL_checkstring(L, 2));
1712 value = MAY_LJMP(luaL_checkstring(L, 3));
1713
1714 ref = pat_ref_lookup(name);
1715 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001716 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001717
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001718 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001719 if (pat_ref_find_elt(ref, key) != NULL)
1720 pat_ref_set(ref, key, value, NULL);
1721 else
1722 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001723 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001724 return 0;
1725}
1726
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001727/* A class is a lot of memory that contain data. This data can be a table,
1728 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001729 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001730 * the name of the object (_G[<name>] = <metable> ).
1731 *
1732 * A metable is a table that modify the standard behavior of a standard
1733 * access to the associated data. The entries of this new metatable are
1734 * defined as is:
1735 *
1736 * http://lua-users.org/wiki/MetatableEvents
1737 *
1738 * __index
1739 *
1740 * we access an absent field in a table, the result is nil. This is
1741 * true, but it is not the whole truth. Actually, such access triggers
1742 * the interpreter to look for an __index metamethod: If there is no
1743 * such method, as usually happens, then the access results in nil;
1744 * otherwise, the metamethod will provide the result.
1745 *
1746 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1747 * the key does not appear in the table, but the metatable has an __index
1748 * property:
1749 *
1750 * - if the value is a function, the function is called, passing in the
1751 * table and the key; the return value of that function is returned as
1752 * the result.
1753 *
1754 * - if the value is another table, the value of the key in that table is
1755 * asked for and returned (and if it doesn't exist in that table, but that
1756 * table's metatable has an __index property, then it continues on up)
1757 *
1758 * - Use "rawget(myTable,key)" to skip this metamethod.
1759 *
1760 * http://www.lua.org/pil/13.4.1.html
1761 *
1762 * __newindex
1763 *
1764 * Like __index, but control property assignment.
1765 *
1766 * __mode - Control weak references. A string value with one or both
1767 * of the characters 'k' and 'v' which specifies that the the
1768 * keys and/or values in the table are weak references.
1769 *
1770 * __call - Treat a table like a function. When a table is followed by
1771 * parenthesis such as "myTable( 'foo' )" and the metatable has
1772 * a __call key pointing to a function, that function is invoked
1773 * (passing any specified arguments) and the return value is
1774 * returned.
1775 *
1776 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1777 * called, if the metatable for myTable has a __metatable
1778 * key, the value of that key is returned instead of the
1779 * actual metatable.
1780 *
1781 * __tostring - Control string representation. When the builtin
1782 * "tostring( myTable )" function is called, if the metatable
1783 * for myTable has a __tostring property set to a function,
1784 * that function is invoked (passing myTable to it) and the
1785 * return value is used as the string representation.
1786 *
1787 * __len - Control table length. When the table length is requested using
1788 * the length operator ( '#' ), if the metatable for myTable has
1789 * a __len key pointing to a function, that function is invoked
1790 * (passing myTable to it) and the return value used as the value
1791 * of "#myTable".
1792 *
1793 * __gc - Userdata finalizer code. When userdata is set to be garbage
1794 * collected, if the metatable has a __gc field pointing to a
1795 * function, that function is first invoked, passing the userdata
1796 * to it. The __gc metamethod is not called for tables.
1797 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1798 *
1799 * Special metamethods for redefining standard operators:
1800 * http://www.lua.org/pil/13.1.html
1801 *
1802 * __add "+"
1803 * __sub "-"
1804 * __mul "*"
1805 * __div "/"
1806 * __unm "!"
1807 * __pow "^"
1808 * __concat ".."
1809 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001810 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001811 * http://www.lua.org/pil/13.2.html
1812 *
1813 * __eq "=="
1814 * __lt "<"
1815 * __le "<="
1816 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817
1818/*
1819 *
1820 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001821 * Class Map
1822 *
1823 *
1824 */
1825
1826/* Returns a struct hlua_map if the stack entry "ud" is
1827 * a class session, otherwise it throws an error.
1828 */
1829__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1830{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001831 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001832}
1833
1834/* This function is the map constructor. It don't need
1835 * the class Map object. It creates and return a new Map
1836 * object. It must be called only during "body" or "init"
1837 * context because it process some filesystem accesses.
1838 */
1839__LJMP static int hlua_map_new(struct lua_State *L)
1840{
1841 const char *fn;
1842 int match = PAT_MATCH_STR;
1843 struct sample_conv conv;
1844 const char *file = "";
1845 int line = 0;
1846 lua_Debug ar;
1847 char *err = NULL;
1848 struct arg args[2];
1849
1850 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1851 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1852
1853 fn = MAY_LJMP(luaL_checkstring(L, 1));
1854
1855 if (lua_gettop(L) >= 2) {
1856 match = MAY_LJMP(luaL_checkinteger(L, 2));
1857 if (match < 0 || match >= PAT_MATCH_NUM)
1858 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1859 }
1860
1861 /* Get Lua filename and line number. */
1862 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1863 lua_getinfo(L, "Sl", &ar); /* get info about it */
1864 if (ar.currentline > 0) { /* is there info? */
1865 file = ar.short_src;
1866 line = ar.currentline;
1867 }
1868 }
1869
1870 /* fill fake sample_conv struct. */
1871 conv.kw = ""; /* unused. */
1872 conv.process = NULL; /* unused. */
1873 conv.arg_mask = 0; /* unused. */
1874 conv.val_args = NULL; /* unused. */
1875 conv.out_type = SMP_T_STR;
1876 conv.private = (void *)(long)match;
1877 switch (match) {
1878 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1879 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1880 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1881 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1882 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1883 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1884 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001885 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001886 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1887 default:
1888 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1889 }
1890
1891 /* fill fake args. */
1892 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001893 args[0].data.str.area = strdup(fn);
1894 args[0].data.str.data = strlen(fn);
1895 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001896 args[1].type = ARGT_STOP;
1897
1898 /* load the map. */
1899 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001900 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001901 * free the err variable.
1902 */
1903 luaL_where(L, 1);
1904 lua_pushfstring(L, "'new': %s.", err);
1905 lua_concat(L, 2);
1906 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001907 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001908 WILL_LJMP(lua_error(L));
1909 }
1910
1911 /* create the lua object. */
1912 lua_newtable(L);
1913 lua_pushlightuserdata(L, args[0].data.map);
1914 lua_rawseti(L, -2, 0);
1915
1916 /* Pop a class Map metatable and affect it to the userdata. */
1917 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1918 lua_setmetatable(L, -2);
1919
1920
1921 return 1;
1922}
1923
1924__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1925{
1926 struct map_descriptor *desc;
1927 struct pattern *pat;
1928 struct sample smp;
1929
1930 MAY_LJMP(check_args(L, 2, "lookup"));
1931 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001932 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001933 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001934 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001935 }
1936 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001937 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001938 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001939 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 +01001940 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001941 }
1942
1943 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001944 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001945 if (str)
1946 lua_pushstring(L, "");
1947 else
1948 lua_pushnil(L);
1949 return 1;
1950 }
1951
1952 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001953 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001954 return 1;
1955}
1956
1957__LJMP static int hlua_map_lookup(struct lua_State *L)
1958{
1959 return _hlua_map_lookup(L, 0);
1960}
1961
1962__LJMP static int hlua_map_slookup(struct lua_State *L)
1963{
1964 return _hlua_map_lookup(L, 1);
1965}
1966
1967/*
1968 *
1969 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970 * Class Socket
1971 *
1972 *
1973 */
1974
1975__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1976{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001977 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001978}
1979
1980/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001981 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001982 * received.
1983 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001984static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985{
Willy Tarreau5321da92022-05-06 11:57:34 +02001986 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02001987 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001988
Willy Tarreau5321da92022-05-06 11:57:34 +02001989 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02001990 sc_shutw(sc);
1991 sc_shutr(sc);
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01001992 sc_ic(sc)->flags |= CF_READ_EVENT;
Willy Tarreau5321da92022-05-06 11:57:34 +02001993 notification_wake(&ctx->wake_on_read);
1994 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02001995 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001996 }
1997
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001998 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001999 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002000 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002001
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002002 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002003 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002004 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002005
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002006 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002007 * to be notified whenever the connection completes.
2008 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002009 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002010 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002011 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002012 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002013 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002014 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015
2016 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002017 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002019 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002020 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002021 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022
2023 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002024 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002025 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002026
2027 /* Some data were injected in the buffer, notify the stream
2028 * interface.
2029 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002030 if (!channel_is_empty(sc_ic(sc)))
2031 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002032
2033 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002034 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002035 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002036 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002037 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038}
2039
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002040static int hlua_socket_init(struct appctx *appctx)
2041{
2042 struct hlua_csk_ctx *ctx = appctx->svcctx;
2043 struct stream *s;
2044
2045 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2046 goto error;
2047
2048 s = appctx_strm(appctx);
2049
Willy Tarreau4596fe22022-05-17 19:07:51 +02002050 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002051 * and retrieve data from the server. The connection is initialized
2052 * with the "struct server".
2053 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002054 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002055
2056 /* Force destination server. */
2057 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2058 s->target = &socket_tcp->obj_type;
2059
2060 ctx->appctx = appctx;
2061 return 0;
2062
2063 error:
2064 return -1;
2065}
2066
Willy Tarreau87b09662015-04-03 00:22:06 +02002067/* This function is called when the "struct stream" is destroyed.
2068 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069 * Wake all the pending signals.
2070 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002071static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072{
Willy Tarreau5321da92022-05-06 11:57:34 +02002073 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002074 struct xref *peer;
2075
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002076 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002077 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002079 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080
2081 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002082 notification_wake(&ctx->wake_on_read);
2083 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084}
2085
2086/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002087 * uses this object. If the stream does not exists, just quit.
2088 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089 * pending signal can rest in the read and write lists. destroy
2090 * it.
2091 */
2092__LJMP static int hlua_socket_gc(lua_State *L)
2093{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002094 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002095 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002096 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 MAY_LJMP(check_args(L, 1, "__gc"));
2099
2100 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002101 peer = xref_get_peer_and_lock(&socket->xref);
2102 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002104
2105 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002107 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002108 ctx->die = 1;
2109 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002111 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002112 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002113 return 0;
2114}
2115
2116/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002117 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118 */
sada05ed3302018-05-11 11:48:18 -07002119__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002121 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002122 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002123 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002124 struct hlua *hlua;
2125
2126 /* Get hlua struct, or NULL if we execute from main lua state */
2127 hlua = hlua_gethlua(L);
2128 if (!hlua)
2129 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002131 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002132
2133 /* Check if we run on the same thread than the xreator thread.
2134 * We cannot access to the socket if the thread is different.
2135 */
2136 if (socket->tid != tid)
2137 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2138
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002139 peer = xref_get_peer_and_lock(&socket->xref);
2140 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002142
2143 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002144 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002146 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002147 ctx->die = 1;
2148 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002150 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002151 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 return 0;
2153}
2154
sada05ed3302018-05-11 11:48:18 -07002155/* The close function calls close_helper.
2156 */
2157__LJMP static int hlua_socket_close(lua_State *L)
2158{
2159 MAY_LJMP(check_args(L, 1, "close"));
2160 return hlua_socket_close_helper(L);
2161}
2162
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002163/* This Lua function assumes that the stack contain three parameters.
2164 * 1 - USERDATA containing a struct socket
2165 * 2 - INTEGER with values of the macro defined below
2166 * If the integer is -1, we must read at most one line.
2167 * If the integer is -2, we ust read all the data until the
2168 * end of the stream.
2169 * If the integer is positive value, we must read a number of
2170 * bytes corresponding to this value.
2171 */
2172#define HLSR_READ_LINE (-1)
2173#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002174__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175{
2176 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2177 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002178 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002179 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002181 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002183 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002184 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002185 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002186 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002187 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002188 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002189 struct stream *s;
2190 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002191 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002193 /* Get hlua struct, or NULL if we execute from main lua state */
2194 hlua = hlua_gethlua(L);
2195
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196 /* Check if this lua stack is schedulable. */
2197 if (!hlua || !hlua->task)
2198 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2199 "'frontend', 'backend' or 'task'"));
2200
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002201 /* Check if we run on the same thread than the xreator thread.
2202 * We cannot access to the socket if the thread is different.
2203 */
2204 if (socket->tid != tid)
2205 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2206
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002207 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002208 peer = xref_get_peer_and_lock(&socket->xref);
2209 if (!peer)
2210 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002211
2212 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2213 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002214 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002216 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002219 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220 if (nblk < 0) /* Connection close. */
2221 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002222 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002224
2225 /* remove final \r\n. */
2226 if (nblk == 1) {
2227 if (blk1[len1-1] == '\n') {
2228 len1--;
2229 skip_at_end++;
2230 if (blk1[len1-1] == '\r') {
2231 len1--;
2232 skip_at_end++;
2233 }
2234 }
2235 }
2236 else {
2237 if (blk2[len2-1] == '\n') {
2238 len2--;
2239 skip_at_end++;
2240 if (blk2[len2-1] == '\r') {
2241 len2--;
2242 skip_at_end++;
2243 }
2244 }
2245 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246 }
2247
2248 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002250 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 if (nblk < 0) /* Connection close. */
2252 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002253 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254 goto connection_empty;
2255 }
2256
2257 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002259 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260 if (nblk < 0) /* Connection close. */
2261 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002262 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263 goto connection_empty;
2264
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002265 missing_bytes = wanted - socket->b.n;
2266 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002268 len1 = missing_bytes;
2269 } if (nblk == 2 && len1 + len2 > missing_bytes)
2270 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 }
2272
2273 len = len1;
2274
2275 luaL_addlstring(&socket->b, blk1, len1);
2276 if (nblk == 2) {
2277 len += len2;
2278 luaL_addlstring(&socket->b, blk2, len2);
2279 }
2280
2281 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002282 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283
2284 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002285 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
2287 /* If the pattern reclaim to read all the data
2288 * in the connection, got out.
2289 */
2290 if (wanted == HLSR_READ_ALL)
2291 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002292 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 goto connection_empty;
2294
2295 /* Return result. */
2296 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002297 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 return 1;
2299
2300connection_closed:
2301
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002302 xref_unlock(&socket->xref, peer);
2303
2304no_peer:
2305
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 /* If the buffer containds data. */
2307 if (socket->b.n > 0) {
2308 luaL_pushresult(&socket->b);
2309 return 1;
2310 }
2311 lua_pushnil(L);
2312 lua_pushstring(L, "connection closed.");
2313 return 2;
2314
2315connection_empty:
2316
Willy Tarreau5321da92022-05-06 11:57:34 +02002317 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002318 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002320 }
2321 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002322 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 return 0;
2324}
2325
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002326/* This Lua function gets two parameters. The first one can be string
2327 * or a number. If the string is "*l", the user requires one line. If
2328 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329 * If the value is a number, the user require a number of bytes equal
2330 * to the value. The default value is "*l" (a line).
2331 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002332 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333 * integer takes this values:
2334 * -1 : read a line
2335 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002336 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002338 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339 * concatenated with the read data.
2340 */
2341__LJMP static int hlua_socket_receive(struct lua_State *L)
2342{
2343 int wanted = HLSR_READ_LINE;
2344 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002345 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 char *error;
2347 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002348 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349
2350 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2351 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2352
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002353 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002354
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002355 /* Check if we run on the same thread than the xreator thread.
2356 * We cannot access to the socket if the thread is different.
2357 */
2358 if (socket->tid != tid)
2359 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2360
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 /* check for pattern. */
2362 if (lua_gettop(L) >= 2) {
2363 type = lua_type(L, 2);
2364 if (type == LUA_TSTRING) {
2365 pattern = lua_tostring(L, 2);
2366 if (strcmp(pattern, "*a") == 0)
2367 wanted = HLSR_READ_ALL;
2368 else if (strcmp(pattern, "*l") == 0)
2369 wanted = HLSR_READ_LINE;
2370 else {
2371 wanted = strtoll(pattern, &error, 10);
2372 if (*error != '\0')
2373 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2374 }
2375 }
2376 else if (type == LUA_TNUMBER) {
2377 wanted = lua_tointeger(L, 2);
2378 if (wanted < 0)
2379 WILL_LJMP(luaL_error(L, "Unsupported size."));
2380 }
2381 }
2382
2383 /* Set pattern. */
2384 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002385
2386 /* Check if we would replace the top by itself. */
2387 if (lua_gettop(L) != 2)
2388 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389
Christopher Fauletc31b2002021-05-03 10:11:13 +02002390 /* Save index of the top of the stack because since buffers are used, it
2391 * may change
2392 */
2393 lastarg = lua_gettop(L);
2394
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002395 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396 luaL_buffinit(L, &socket->b);
2397
2398 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002399 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400 if (lua_type(L, 3) != LUA_TSTRING)
2401 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2402 pattern = lua_tolstring(L, 3, &len);
2403 luaL_addlstring(&socket->b, pattern, len);
2404 }
2405
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002406 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407}
2408
2409/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002410 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002412static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413{
2414 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002415 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002416 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417 struct appctx *appctx;
2418 size_t buf_len;
2419 const char *buf;
2420 int len;
2421 int send_len;
2422 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002423 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002424 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002425 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002426
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002427 /* Get hlua struct, or NULL if we execute from main lua state */
2428 hlua = hlua_gethlua(L);
2429
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002430 /* Check if this lua stack is schedulable. */
2431 if (!hlua || !hlua->task)
2432 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2433 "'frontend', 'backend' or 'task'"));
2434
2435 /* Get object */
2436 socket = MAY_LJMP(hlua_checksocket(L, 1));
2437 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002438 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002440 /* Check if we run on the same thread than the xreator thread.
2441 * We cannot access to the socket if the thread is different.
2442 */
2443 if (socket->tid != tid)
2444 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2445
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002446 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002447 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002448 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002449 lua_pushinteger(L, -1);
2450 return 1;
2451 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002452
2453 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2454 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002455 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002456 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002457
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002459 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002460 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002461 lua_pushinteger(L, -1);
2462 return 1;
2463 }
2464
2465 /* Update the input buffer data. */
2466 buf += sent;
2467 send_len = buf_len - sent;
2468
2469 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002470 if (sent >= buf_len) {
2471 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002473 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002475 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002476 * the request buffer if its not required.
2477 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002478 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002479 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002480 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002481 }
2482
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002483 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002484 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002485 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002487 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002488
2489 /* send data */
2490 if (len < send_len)
2491 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002492 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002493
2494 /* "Not enough space" (-1), "Buffer too little to contain
2495 * the data" (-2) are not expected because the available length
2496 * is tested.
2497 * Other unknown error are also not expected.
2498 */
2499 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002500 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002501 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002502
sada05ed3302018-05-11 11:48:18 -07002503 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002504 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002505 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002506 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002507 return 1;
2508 }
2509
2510 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002511 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002512
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002513 s->req.rex = TICK_ETERNITY;
2514 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515
2516 /* Update length sent. */
2517 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002518 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519
2520 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002521 if (sent + len >= buf_len) {
2522 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002523 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002524 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525
2526hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002527 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002528 xref_unlock(&socket->xref, peer);
2529 WILL_LJMP(luaL_error(L, "out of memory"));
2530 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002531 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002532 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002533 return 0;
2534}
2535
2536/* This function initiate the send of data. It just check the input
2537 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002538 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002539 * "hlua_socket_write_yield" that can yield.
2540 *
2541 * The Lua function gets between 3 and 4 parameters. The first one is
2542 * the associated object. The second is a string buffer. The third is
2543 * a facultative integer that represents where is the buffer position
2544 * of the start of the data that can send. The first byte is the
2545 * position "1". The default value is "1". The fourth argument is a
2546 * facultative integer that represents where is the buffer position
2547 * of the end of the data that can send. The default is the last byte.
2548 */
2549static int hlua_socket_send(struct lua_State *L)
2550{
2551 int i;
2552 int j;
2553 const char *buf;
2554 size_t buf_len;
2555
2556 /* Check number of arguments. */
2557 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2558 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2559
2560 /* Get the string. */
2561 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2562
2563 /* Get and check j. */
2564 if (lua_gettop(L) == 4) {
2565 j = MAY_LJMP(luaL_checkinteger(L, 4));
2566 if (j < 0)
2567 j = buf_len + j + 1;
2568 if (j > buf_len)
2569 j = buf_len + 1;
2570 lua_pop(L, 1);
2571 }
2572 else
2573 j = buf_len;
2574
2575 /* Get and check i. */
2576 if (lua_gettop(L) == 3) {
2577 i = MAY_LJMP(luaL_checkinteger(L, 3));
2578 if (i < 0)
2579 i = buf_len + i + 1;
2580 if (i > buf_len)
2581 i = buf_len + 1;
2582 lua_pop(L, 1);
2583 } else
2584 i = 1;
2585
2586 /* Check bth i and j. */
2587 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589 return 1;
2590 }
2591 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002592 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593 return 1;
2594 }
2595 if (i == 0)
2596 i = 1;
2597 if (j == 0)
2598 j = 1;
2599
2600 /* Pop the string. */
2601 lua_pop(L, 1);
2602
2603 /* Update the buffer length. */
2604 buf += i - 1;
2605 buf_len = j - i + 1;
2606 lua_pushlstring(L, buf, buf_len);
2607
2608 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002611 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002612}
2613
Willy Tarreau22b0a682015-06-17 19:43:49 +02002614#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002615__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616{
2617 static char buffer[SOCKET_INFO_MAX_LEN];
2618 int ret;
2619 int len;
2620 char *p;
2621
2622 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2623 if (ret <= 0) {
2624 lua_pushnil(L);
2625 return 1;
2626 }
2627
2628 if (ret == AF_UNIX) {
2629 lua_pushstring(L, buffer+1);
2630 return 1;
2631 }
2632 else if (ret == AF_INET6) {
2633 buffer[0] = '[';
2634 len = strlen(buffer);
2635 buffer[len] = ']';
2636 len++;
2637 buffer[len] = ':';
2638 len++;
2639 p = buffer;
2640 }
2641 else if (ret == AF_INET) {
2642 p = buffer + 1;
2643 len = strlen(p);
2644 p[len] = ':';
2645 len++;
2646 }
2647 else {
2648 lua_pushnil(L);
2649 return 1;
2650 }
2651
2652 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2653 lua_pushnil(L);
2654 return 1;
2655 }
2656
2657 lua_pushstring(L, p);
2658 return 1;
2659}
2660
2661/* Returns information about the peer of the connection. */
2662__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2663{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002664 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002665 struct xref *peer;
2666 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002667 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002668 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002669 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002670
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002671 MAY_LJMP(check_args(L, 1, "getpeername"));
2672
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002673 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002675 /* Check if we run on the same thread than the xreator thread.
2676 * We cannot access to the socket if the thread is different.
2677 */
2678 if (socket->tid != tid)
2679 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2680
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002681 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002682 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002683 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684 lua_pushnil(L);
2685 return 1;
2686 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002687
2688 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002689 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002690 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002691 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002692 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002693 lua_pushnil(L);
2694 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002695 }
2696
Christopher Faulet16f16af2021-10-27 09:34:56 +02002697 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002698 xref_unlock(&socket->xref, peer);
2699 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002700}
2701
2702/* Returns information about my connection side. */
2703static int hlua_socket_getsockname(struct lua_State *L)
2704{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002705 struct hlua_socket *socket;
2706 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002707 struct appctx *appctx;
2708 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002709 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002710 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002711
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712 MAY_LJMP(check_args(L, 1, "getsockname"));
2713
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002714 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002715
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002716 /* Check if we run on the same thread than the xreator thread.
2717 * We cannot access to the socket if the thread is different.
2718 */
2719 if (socket->tid != tid)
2720 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2721
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002722 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002723 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002724 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725 lua_pushnil(L);
2726 return 1;
2727 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002728
2729 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002730 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002731
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002732 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002733 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002734 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002735 lua_pushnil(L);
2736 return 1;
2737 }
2738
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002739 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002740 xref_unlock(&socket->xref, peer);
2741 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002742}
2743
2744/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002745static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002746 .obj_type = OBJ_TYPE_APPLET,
2747 .name = "<LUA_TCP>",
2748 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002749 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002750 .release = hlua_socket_release,
2751};
2752
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002753__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002754{
2755 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002756 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002757 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002758 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002759 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002760 struct stream *s;
2761
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002762 /* Get hlua struct, or NULL if we execute from main lua state */
2763 hlua = hlua_gethlua(L);
2764 if (!hlua)
2765 return 0;
2766
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002767 /* Check if we run on the same thread than the xreator thread.
2768 * We cannot access to the socket if the thread is different.
2769 */
2770 if (socket->tid != tid)
2771 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2772
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002773 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002774 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002775 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002776 lua_pushnil(L);
2777 lua_pushstring(L, "Can't connect");
2778 return 2;
2779 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002780
2781 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2782 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002783 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002784
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002785 /* Check if we run on the same thread than the xreator thread.
2786 * We cannot access to the socket if the thread is different.
2787 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002788 if (socket->tid != tid) {
2789 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002790 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002791 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002792
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002794 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002795 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002796 lua_pushnil(L);
2797 lua_pushstring(L, "Can't connect");
2798 return 2;
2799 }
2800
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002801 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002802
2803 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002804 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002805 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002806 lua_pushinteger(L, 1);
2807 return 1;
2808 }
2809
Willy Tarreau5321da92022-05-06 11:57:34 +02002810 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002811 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002812 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002813 }
2814 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002815 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002816 return 0;
2817}
2818
2819/* This function fail or initite the connection. */
2820__LJMP static int hlua_socket_connect(struct lua_State *L)
2821{
2822 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002823 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002824 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002825 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002826 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002827 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002828 int low, high;
2829 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002830 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002831 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002832 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002833
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002834 if (lua_gettop(L) < 2)
2835 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002836
2837 /* Get args. */
2838 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002839
2840 /* Check if we run on the same thread than the xreator thread.
2841 * We cannot access to the socket if the thread is different.
2842 */
2843 if (socket->tid != tid)
2844 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2845
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002846 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002847 if (lua_gettop(L) >= 3) {
2848 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002849 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002850
Tim Duesterhus6edab862018-01-06 19:04:45 +01002851 /* Force the ip to end with a colon, to support IPv6 addresses
2852 * that are not enclosed within square brackets.
2853 */
2854 if (port > 0) {
2855 luaL_buffinit(L, &b);
2856 luaL_addstring(&b, ip);
2857 luaL_addchar(&b, ':');
2858 luaL_pushresult(&b);
2859 ip = lua_tolstring(L, lua_gettop(L), NULL);
2860 }
2861 }
2862
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002863 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002864 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002865 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002866 lua_pushnil(L);
2867 return 1;
2868 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002869
2870 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002871 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 +02002872 if (!addr) {
2873 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002874 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002875 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002876
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002877 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002878 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002879 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002880 if (port == -1) {
2881 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002882 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002883 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002884 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2885 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002886 if (port == -1) {
2887 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002888 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002889 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002890 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002891 }
2892 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002893
Willy Tarreau5321da92022-05-06 11:57:34 +02002894 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2895 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002896 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002897 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002898
Willy Tarreau3e7be362022-05-27 10:35:27 +02002899 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002900 xref_unlock(&socket->xref, peer);
2901 WILL_LJMP(luaL_error(L, "connect: internal error"));
2902 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002903
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002904 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002905 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002906 if (!hlua)
2907 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002908
2909 /* inform the stream that we want to be notified whenever the
2910 * connection completes.
2911 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002912 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002913 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002914 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002915
Willy Tarreauf31af932020-01-14 09:59:38 +01002916 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002917
Willy Tarreau5321da92022-05-06 11:57:34 +02002918 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002919 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002920 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002921 }
2922 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002923
2924 task_wakeup(s->task, TASK_WOKEN_INIT);
2925 /* Return yield waiting for connection. */
2926
Willy Tarreau9635e032018-10-16 17:52:55 +02002927 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002928
2929 return 0;
2930}
2931
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002932#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2934{
2935 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002936 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002937 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002938
2939 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2940 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002941
2942 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002943 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002944 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002945 lua_pushnil(L);
2946 return 1;
2947 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002948
Willy Tarreau0698c802022-05-11 14:09:57 +02002949 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002950
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002951 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002952 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953 return MAY_LJMP(hlua_socket_connect(L));
2954}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002955#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002956
2957__LJMP static int hlua_socket_setoption(struct lua_State *L)
2958{
2959 return 0;
2960}
2961
2962__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2963{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002964 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002965 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002966 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002967 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002968 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002969
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970 MAY_LJMP(check_args(L, 2, "settimeout"));
2971
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002972 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002973
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002974 /* convert the timeout to millis */
2975 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002976
Thierry Fournier17a921b2018-03-08 09:59:02 +01002977 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002978 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002979 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2980
Mark Lakes56cc1252018-03-27 09:48:06 +02002981 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002982 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002983
2984 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002985 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002986 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002987
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002988 /* Check if we run on the same thread than the xreator thread.
2989 * We cannot access to the socket if the thread is different.
2990 */
2991 if (socket->tid != tid)
2992 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2993
Mark Lakes56cc1252018-03-27 09:48:06 +02002994 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002995 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002996 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002997 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2998 WILL_LJMP(lua_error(L));
2999 return 0;
3000 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003001
Willy Tarreau0698c802022-05-11 14:09:57 +02003002 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003003
Cyril Bonté7bb63452018-08-17 23:51:02 +02003004 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003005 s->req.rto = tmout;
3006 s->req.wto = tmout;
3007 s->res.rto = tmout;
3008 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003009 s->req.rex = tick_add_ifset(now_ms, tmout);
3010 s->req.wex = tick_add_ifset(now_ms, tmout);
3011 s->res.rex = tick_add_ifset(now_ms, tmout);
3012 s->res.wex = tick_add_ifset(now_ms, tmout);
3013
3014 s->task->expire = tick_add_ifset(now_ms, tmout);
3015 task_queue(s->task);
3016
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003017 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003018
Thierry Fourniere9636f12018-03-08 09:54:32 +01003019 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003020 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021}
3022
3023__LJMP static int hlua_socket_new(lua_State *L)
3024{
3025 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003026 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003027 struct appctx *appctx;
3028
3029 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003030 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003031 hlua_pusherror(L, "socket: full stack");
3032 goto out_fail_conf;
3033 }
3034
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003035 /* Create the object: obj[0] = userdata. */
3036 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003037 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003038 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003039 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003040 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003041
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003042 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003043 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003044 hlua_pusherror(L, "socket: uninitialized pools.");
3045 goto out_fail_conf;
3046 }
3047
Willy Tarreau87b09662015-04-03 00:22:06 +02003048 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003049 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3050 lua_setmetatable(L, -2);
3051
Willy Tarreaud420a972015-04-06 00:39:18 +02003052 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003053 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003054 if (!appctx) {
3055 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003056 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003057 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003058 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3059 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003060 ctx->die = 0;
3061 LIST_INIT(&ctx->wake_on_write);
3062 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003063
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003064 if (appctx_init(appctx) == -1) {
3065 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003066 goto out_fail_appctx;
3067 }
3068
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003069 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003070 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003071 return 1;
3072
Christopher Faulet13a35e52021-12-20 15:34:16 +01003073 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003074 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003075 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003076 WILL_LJMP(lua_error(L));
3077 return 0;
3078}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003079
3080/*
3081 *
3082 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083 * Class Channel
3084 *
3085 *
3086 */
3087
3088/* Returns the struct hlua_channel join to the class channel in the
3089 * stack entry "ud" or throws an argument error.
3090 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003091__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003092{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003093 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003094}
3095
Willy Tarreau47860ed2015-03-10 14:07:50 +01003096/* Pushes the channel onto the top of the stack. If the stask does not have a
3097 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003098 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003099static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003100{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003102 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003103 return 0;
3104
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003105 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003106 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003107 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003108
3109 /* Pop a class sesison metatable and affect it to the userdata. */
3110 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3111 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003112 return 1;
3113}
3114
Christopher Faulet9f55a502020-02-25 15:21:02 +01003115/* Helper function returning a filter attached to a channel at the position <ud>
3116 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003117 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003118 * initialized.
3119 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003120static 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 +01003121{
3122 struct filter *filter = NULL;
3123
3124 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3125 struct hlua_flt_ctx *flt_ctx;
3126
3127 filter = lua_touserdata (L, -1);
3128 flt_ctx = filter->ctx;
3129 if (hlua_filter_from_payload(filter)) {
3130 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3131 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3132 }
3133 }
3134
3135 lua_pop(L, 1);
3136 return filter;
3137}
3138
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003139/* Copies <len> bytes of data present in the channel's buffer, starting at the
3140* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003141* responsibility to ensure <len> and <offset> are valid. It always return the
3142* length of the built string. <len> may be 0, in this case, an empty string is
3143* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003144*/
3145static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003146{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003147 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003148 luaL_Buffer b;
3149
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003150 block1 = len;
3151 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3152 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3153 block2 = len - block1;
3154
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003155 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003156 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3157 if (block2)
3158 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003159 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003160 return len;
3161}
3162
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003163/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3164 * function returns -1 if data cannot be copied. Otherwise, it returns the
3165 * number of bytes copied.
3166 */
3167static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3168{
3169 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003170
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003171 /* Nothing to do, just return */
3172 if (unlikely(istlen(str) == 0))
3173 goto end;
3174
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003175 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003176 ret = -1;
3177 goto end;
3178 }
3179 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3180
3181 end:
3182 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003183}
3184
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003185/* Removes <len> bytes of data at the absolute position <offset>.
3186 */
3187static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3188{
3189 size_t end = offset + len;
3190
3191 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3192 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3193 b_data(&chn->buf) - end, -len);
3194 b_sub(&chn->buf, len);
3195}
3196
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003197/* Copies input data in the channel's buffer. It is possible to set a specific
3198 * offset (0 by default) and a length (all remaining input data starting for the
3199 * offset by default). If there is not enough input data and more data can be
3200 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003201 *
3202 * From an action, All input data are considered. For a filter, the offset and
3203 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003204 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003206{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003207 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208 struct filter *filter;
3209 size_t input, output;
3210 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003211
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003212 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003213
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003214 output = co_data(chn);
3215 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003216
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003217 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3218 if (filter && !hlua_filter_from_payload(filter))
3219 WILL_LJMP(lua_error(L));
3220
3221 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003222 if (lua_gettop(L) > 1) {
3223 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3224 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003225 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003226 offset += output;
3227 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228 lua_pushfstring(L, "offset out of range.");
3229 WILL_LJMP(lua_error(L));
3230 }
3231 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003232 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003233 if (lua_gettop(L) == 3) {
3234 len = MAY_LJMP(luaL_checkinteger(L, 3));
3235 if (!len)
3236 goto dup;
3237 if (len == -1)
3238 len = global.tune.bufsize;
3239 if (len < 0) {
3240 lua_pushfstring(L, "length out of range.");
3241 WILL_LJMP(lua_error(L));
3242 }
3243 }
3244
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003245 /* Wait for more data if possible if no length was specified and there
3246 * is no data or not enough data was received.
3247 */
3248 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003249 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3250 /* Yield waiting for more data, as requested */
3251 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3252 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003253
3254 /* Return 'nil' if there is no data and the channel can't receive more data */
3255 if (!len) {
3256 lua_pushnil(L);
3257 return -1;
3258 }
3259
3260 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003261 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003262 }
3263
3264 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003265 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003266 return 1;
3267}
3268
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003269/* Copies the first line (including the trailing LF) of input data in the
3270 * channel's buffer. It is possible to set a specific offset (0 by default) and
3271 * a length (all remaining input data starting for the offset by default). If
3272 * there is not enough input data and more data can be received, the function
3273 * yields. If a length is explicitly specified, no more data are
3274 * copied. Otherwise, if no LF is found and more data can be received, this
3275 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003276 *
3277 * From an action, All input data are considered. For a filter, the offset and
3278 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003279 */
3280__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003281{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003282 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003283 struct filter *filter;
3284 size_t l, input, output;
3285 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003286
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003287 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003288 output = co_data(chn);
3289 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003290
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003291 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3292 if (filter && !hlua_filter_from_payload(filter))
3293 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003294
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003296 if (lua_gettop(L) > 1) {
3297 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3298 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003299 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300 offset += output;
3301 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003302 lua_pushfstring(L, "offset out of range.");
3303 WILL_LJMP(lua_error(L));
3304 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003305 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003306
3307 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003308 if (lua_gettop(L) == 3) {
3309 len = MAY_LJMP(luaL_checkinteger(L, 3));
3310 if (!len)
3311 goto dup;
3312 if (len == -1)
3313 len = global.tune.bufsize;
3314 if (len < 0) {
3315 lua_pushfstring(L, "length out of range.");
3316 WILL_LJMP(lua_error(L));
3317 }
3318 }
3319
3320 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003321 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003322 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003323 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003324 len = l+1;
3325 goto dup;
3326 }
3327 }
3328
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003329 /* Wait for more data if possible if no line is found and no length was
3330 * specified or not enough data was received.
3331 */
3332 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003333 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3334 /* Yield waiting for more data */
3335 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3336 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003337
3338 /* Return 'nil' if there is no data and the channel can't receive more data */
3339 if (!len) {
3340 lua_pushnil(L);
3341 return -1;
3342 }
3343
3344 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003345 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003346 }
3347
3348 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003349 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003350 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003351}
3352
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353/* [ DEPRECATED ]
3354 *
3355 * Duplicate all input data foud in the channel's buffer. The data are not
3356 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003357 *
3358 * From an action, All input data are considered. For a filter, the offset and
3359 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003360 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003361__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003362{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003363 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003364 struct filter *filter;
3365 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003366
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003367 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003368 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003369 if (IS_HTX_STRM(chn_strm(chn))) {
3370 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3371 WILL_LJMP(lua_error(L));
3372 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003373
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003374 offset = co_data(chn);
3375 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003376
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003377 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3378 if (filter && !hlua_filter_from_payload(filter))
3379 WILL_LJMP(lua_error(L));
3380
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003381 if (!ci_data(chn) && channel_input_closed(chn)) {
3382 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003383 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003384 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003385
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003386 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003387 return 1;
3388}
3389
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003390/* [ DEPRECATED ]
3391 *
3392 * Get all input data foud in the channel's buffer. The data are removed from
3393 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3394 * _hlua_channel_delete().
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.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003398 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003399__LJMP static int hlua_channel_get(lua_State *L)
3400{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003401 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003402 struct filter *filter;
3403 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003404 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003405
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003406 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003407 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3408 if (IS_HTX_STRM(chn_strm(chn))) {
3409 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3410 WILL_LJMP(lua_error(L));
3411 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003412
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003413 offset = co_data(chn);
3414 len = ci_data(chn);
3415
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003416 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3417 if (filter && !hlua_filter_from_payload(filter))
3418 WILL_LJMP(lua_error(L));
3419
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003420 if (!ci_data(chn) && channel_input_closed(chn)) {
3421 lua_pushnil(L);
3422 return 1;
3423 }
3424
3425 ret = _hlua_channel_dup(chn, L, offset, len);
3426 _hlua_channel_delete(chn, offset, ret);
3427 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003428}
3429
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003430/* This functions consumes and returns one line. If the channel is closed,
3431 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003432 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003433 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003434 *
3435 * From an action, All input data are considered. For a filter, the offset and
3436 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003437 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003438__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003439{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003440 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003441 struct filter *filter;
3442 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003443 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003444
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003445 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003446
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003447 offset = co_data(chn);
3448 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003449
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003450 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3451 if (filter && !hlua_filter_from_payload(filter))
3452 WILL_LJMP(lua_error(L));
3453
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003454 if (!ci_data(chn) && channel_input_closed(chn)) {
3455 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003456 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003457 }
3458
3459 for (l = 0; l < len; l++) {
3460 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3461 len = l+1;
3462 goto dup;
3463 }
3464 }
3465
3466 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3467 /* Yield waiting for more data */
3468 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3469 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003470
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003471 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003472 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003473 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003474 return 1;
3475}
3476
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003477/* [ DEPRECATED ]
3478 *
3479 * Check arguments for the function "hlua_channel_getline_yield".
3480 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003481__LJMP static int hlua_channel_getline(lua_State *L)
3482{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003483 struct channel *chn;
3484
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003485 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003486 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3487 if (IS_HTX_STRM(chn_strm(chn))) {
3488 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3489 WILL_LJMP(lua_error(L));
3490 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003491 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3492}
3493
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003494/* Retrieves a given amount of input data at the given offset. By default all
3495 * available input data are returned. The offset may be negactive to start from
3496 * the end of input data. The length may be -1 to set it to the maximum buffer
3497 * size.
3498 */
3499__LJMP static int hlua_channel_get_data(lua_State *L)
3500{
3501 struct channel *chn;
3502
3503 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3504 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3505 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3506 if (IS_HTX_STRM(chn_strm(chn))) {
3507 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3508 WILL_LJMP(lua_error(L));
3509 }
3510 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3511}
3512
3513/* Retrieves a given amount of input data at the given offset. By default all
3514 * available input data are returned. The offset may be negactive to start from
3515 * the end of input data. The length may be -1 to set it to the maximum buffer
3516 * size.
3517 */
3518__LJMP static int hlua_channel_get_line(lua_State *L)
3519{
3520 struct channel *chn;
3521
3522 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3523 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3524 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3525 if (IS_HTX_STRM(chn_strm(chn))) {
3526 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3527 WILL_LJMP(lua_error(L));
3528 }
3529 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3530}
3531
3532/* Appends a string into the input side of channel. It returns the length of the
3533 * written string, or -1 if the channel is closed or if the buffer size is too
3534 * little for the data. 0 may be returned if nothing is copied. This function
3535 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003536 *
3537 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003538 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003539__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003540{
Christopher Faulet23976d92021-08-06 09:59:49 +02003541 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003542 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003543 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003544 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003545 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003546
3547 MAY_LJMP(check_args(L, 2, "append"));
3548 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003549 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003550 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003551 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003552 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003553 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003554
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003555 offset = co_data(chn);
3556 len = ci_data(chn);
3557
3558 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3559 if (filter && !hlua_filter_from_payload(filter))
3560 WILL_LJMP(lua_error(L));
3561
3562 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3563 if (ret > 0 && filter) {
3564 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3565
3566 flt_update_offsets(filter, chn, ret);
3567 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3568 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003569 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003570 return 1;
3571}
3572
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003573/* Prepends a string into the input side of channel. It returns the length of the
3574 * written string, or -1 if the channel is closed or if the buffer size is too
3575 * little for the data. 0 may be returned if nothing is copied. This function
3576 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003577 *
3578 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003579 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003580__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003581{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003582 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003583 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003584 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003586 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003587
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003589 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003590 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3591 if (IS_HTX_STRM(chn_strm(chn))) {
3592 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3593 WILL_LJMP(lua_error(L));
3594 }
3595
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003596 offset = co_data(chn);
3597 len = ci_data(chn);
3598
3599 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3600 if (filter && !hlua_filter_from_payload(filter))
3601 WILL_LJMP(lua_error(L));
3602
3603 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3604 if (ret > 0 && filter) {
3605 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3606
3607 flt_update_offsets(filter, chn, ret);
3608 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3609 }
3610
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003611 lua_pushinteger(L, ret);
3612 return 1;
3613}
3614
3615/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003616 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003617 * returns the length of the written string, or -1 if the channel is closed or
3618 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003619 *
3620 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621 */
3622__LJMP static int hlua_channel_insert_data(lua_State *L)
3623{
3624 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003626 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003627 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003628 int ret, offset;
3629
3630 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3631 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3632 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3633 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003634
3635 output = co_data(chn);
3636 input = ci_data(chn);
3637
3638 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3639 if (filter && !hlua_filter_from_payload(filter))
3640 WILL_LJMP(lua_error(L));
3641
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003642 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003643 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003645 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003646 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003647 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003648 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003649 lua_pushfstring(L, "offset out of range.");
3650 WILL_LJMP(lua_error(L));
3651 }
3652 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003653 if (IS_HTX_STRM(chn_strm(chn))) {
3654 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3655 WILL_LJMP(lua_error(L));
3656 }
3657
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003658 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3659 if (ret > 0 && filter) {
3660 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003661
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662 flt_update_offsets(filter, chn, ret);
3663 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003664 }
3665
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666 lua_pushinteger(L, ret);
3667 return 1;
3668}
3669/* Replaces a given amount of input data at the given offset by a string
3670 * content. By default all remaining data are removed (offset = 0 and len =
3671 * -1). It returns the length of the written string, or -1 if the channel is
3672 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003673 *
3674 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003675 */
3676__LJMP static int hlua_channel_set_data(lua_State *L)
3677{
3678 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003679 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003680 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003681 size_t sz, input, output;
3682 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003683
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003684 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3685 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3686 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3687 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003688
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003689 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003690 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003691 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003692 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003693
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003694 output = co_data(chn);
3695 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003696
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003697 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3698 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003699 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003700
3701 offset = output;
3702 if (lua_gettop(L) > 2) {
3703 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3704 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003705 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003706 offset += output;
3707 if (offset < output || offset > input + output) {
3708 lua_pushfstring(L, "offset out of range.");
3709 WILL_LJMP(lua_error(L));
3710 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003711 }
3712
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003713 len = output + input - offset;
3714 if (lua_gettop(L) == 4) {
3715 len = MAY_LJMP(luaL_checkinteger(L, 4));
3716 if (!len)
3717 goto set;
3718 if (len == -1)
3719 len = output + input - offset;
3720 if (len < 0 || offset + len > output + input) {
3721 lua_pushfstring(L, "length out of range.");
3722 WILL_LJMP(lua_error(L));
3723 }
3724 }
3725
3726 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003727 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003728 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003729 lua_pushinteger(L, -1);
3730 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003731 _hlua_channel_delete(chn, offset, len);
3732 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3733 if (filter) {
3734 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3735
3736 len -= (ret > 0 ? ret : 0);
3737 flt_update_offsets(filter, chn, -len);
3738 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3739 }
3740
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003741 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003742 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003743 return 1;
3744}
3745
3746/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003748 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 *
3750 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003751 */
3752__LJMP static int hlua_channel_del_data(lua_State *L)
3753{
3754 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003755 struct filter *filter;
3756 size_t input, output;
3757 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003758
3759 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3760 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3761 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003762
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003763 if (IS_HTX_STRM(chn_strm(chn))) {
3764 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3765 WILL_LJMP(lua_error(L));
3766 }
3767
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003768 output = co_data(chn);
3769 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003770
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003771 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3772 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003773 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003774
3775 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003776 if (lua_gettop(L) > 1) {
3777 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003778 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003779 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003780 offset += output;
3781 if (offset < output || offset > input + output) {
3782 lua_pushfstring(L, "offset out of range.");
3783 WILL_LJMP(lua_error(L));
3784 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003785 }
3786
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003787 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003788 if (lua_gettop(L) == 3) {
3789 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003790 if (!len)
3791 goto end;
3792 if (len == -1)
3793 len = output + input - offset;
3794 if (len < 0 || offset + len > output + input) {
3795 lua_pushfstring(L, "length out of range.");
3796 WILL_LJMP(lua_error(L));
3797 }
3798 }
3799
3800 _hlua_channel_delete(chn, offset, len);
3801 if (filter) {
3802 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3803
3804 flt_update_offsets(filter, chn, -len);
3805 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3806 }
3807
3808 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003809 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003810 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003811}
3812
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003813/* Append data in the output side of the buffer. This data is immediately
3814 * sent. The function returns the amount of data written. If the buffer
3815 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003816 * if the channel is closed.
3817 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003818__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003819{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003820 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003821 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003822 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003823 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003824 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003825 struct hlua *hlua;
3826
3827 /* Get hlua struct, or NULL if we execute from main lua state */
3828 hlua = hlua_gethlua(L);
3829 if (!hlua) {
3830 lua_pushnil(L);
3831 return 1;
3832 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003833
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003834 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3835 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3836 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003837
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 offset = co_data(chn);
3839 len = ci_data(chn);
3840
3841 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3842 if (filter && !hlua_filter_from_payload(filter))
3843 WILL_LJMP(lua_error(L));
3844
3845
Willy Tarreau47860ed2015-03-10 14:07:50 +01003846 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003847 lua_pushinteger(L, -1);
3848 return 1;
3849 }
3850
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003851 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003852 if (len > sz -l) {
3853 if (filter) {
3854 lua_pushinteger(L, -1);
3855 return 1;
3856 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003857 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003858 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003859
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003860 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861 if (ret == -1) {
3862 lua_pop(L, 1);
3863 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003864 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003865 }
3866 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003867 if (filter) {
3868 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3869
3870
3871 flt_update_offsets(filter, chn, ret);
3872 FLT_OFF(filter, chn) += ret;
3873 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3874 }
3875 else
3876 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003877
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003878 l += ret;
3879 lua_pop(L, 1);
3880 lua_pushinteger(L, l);
3881 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003882
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003883 if (l < sz) {
3884 /* Yield only if the channel's output is not empty.
3885 * Otherwise it means we cannot add more data. */
3886 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003887 return 1;
3888
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003889 /* If we are waiting for space in the response buffer, we
3890 * must set the flag WAKERESWR. This flag required the task
3891 * wake up if any activity is detected on the response buffer.
3892 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003893 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003894 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003895 else
3896 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003897 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003898 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003899
3900 return 1;
3901}
3902
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003903/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003904 * yield the LUA process, and resume it without checking the
3905 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003906 *
3907 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003908 */
3909__LJMP static int hlua_channel_send(lua_State *L)
3910{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003911 struct channel *chn;
3912
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003913 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003914 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3915 if (IS_HTX_STRM(chn_strm(chn))) {
3916 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3917 WILL_LJMP(lua_error(L));
3918 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003919 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003920 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003921}
3922
3923/* This function forward and amount of butes. The data pass from
3924 * the input side of the buffer to the output side, and can be
3925 * forwarded. This function never fails.
3926 *
3927 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003928 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003929 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003930__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003931{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003932 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003933 struct filter *filter;
3934 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003935 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003936 struct hlua *hlua;
3937
3938 /* Get hlua struct, or NULL if we execute from main lua state */
3939 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003940 if (!hlua) {
3941 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003942 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003943 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003944
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003945 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003946 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003947 l = MAY_LJMP(luaL_checkinteger(L, -1));
3948
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003949 offset = co_data(chn);
3950 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003951
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003952 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3953 if (filter && !hlua_filter_from_payload(filter))
3954 WILL_LJMP(lua_error(L));
3955
3956 max = fwd - l;
3957 if (max > len)
3958 max = len;
3959
3960 if (filter) {
3961 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3962
3963 FLT_OFF(filter, chn) += max;
3964 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3965 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3966 }
3967 else
3968 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003969
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003970 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003971 lua_pop(L, 1);
3972 lua_pushinteger(L, l);
3973
3974 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003975 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003976 /* The the input channel or the output channel are closed, we
3977 * must return the amount of data forwarded.
3978 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003979 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003980 return 1;
3981
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003982 /* If we are waiting for space data in the response buffer, we
3983 * must set the flag WAKERESWR. This flag required the task
3984 * wake up if any activity is detected on the response buffer.
3985 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003986 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003987 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003988 else
3989 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003990
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003991 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003992 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003993 }
3994
3995 return 1;
3996}
3997
3998/* Just check the input and prepare the stack for the previous
3999 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004000 *
4001 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004002 */
4003__LJMP static int hlua_channel_forward(lua_State *L)
4004{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004005 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004006
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004007 MAY_LJMP(check_args(L, 2, "forward"));
4008 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4009 if (IS_HTX_STRM(chn_strm(chn))) {
4010 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4011 WILL_LJMP(lua_error(L));
4012 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004013 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004014 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004015}
4016
4017/* Just returns the number of bytes available in the input
4018 * side of the buffer. This function never fails.
4019 */
4020__LJMP static int hlua_channel_get_in_len(lua_State *L)
4021{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004022 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004023 struct filter *filter;
4024 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004025
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004026 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004027 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004028
4029 output = co_data(chn);
4030 input = ci_data(chn);
4031 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4032 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4033 lua_pushinteger(L, input);
4034 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004035 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004036
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004037 lua_pushinteger(L, htx->data - co_data(chn));
4038 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004039 return 1;
4040}
4041
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004042/* Returns true if the channel is full. */
4043__LJMP static int hlua_channel_is_full(lua_State *L)
4044{
4045 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004046
4047 MAY_LJMP(check_args(L, 1, "is_full"));
4048 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004049 /* ignore the reserve, we are not on a producer side (ie in an
4050 * applet).
4051 */
4052 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004053 return 1;
4054}
4055
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004056/* Returns true if the channel may still receive data. */
4057__LJMP static int hlua_channel_may_recv(lua_State *L)
4058{
4059 struct channel *chn;
4060
4061 MAY_LJMP(check_args(L, 1, "may_recv"));
4062 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4063 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4064 return 1;
4065}
4066
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004067/* Returns true if the channel is the response channel. */
4068__LJMP static int hlua_channel_is_resp(lua_State *L)
4069{
4070 struct channel *chn;
4071
4072 MAY_LJMP(check_args(L, 1, "is_resp"));
4073 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4074
4075 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4076 return 1;
4077}
4078
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004079/* Just returns the number of bytes available in the output
4080 * side of the buffer. This function never fails.
4081 */
4082__LJMP static int hlua_channel_get_out_len(lua_State *L)
4083{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004084 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004085 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004086
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004087 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004088 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004089
4090 output = co_data(chn);
4091 input = ci_data(chn);
4092 hlua_channel_filter(L, 1, chn, &output, &input);
4093
4094 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004095 return 1;
4096}
4097
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004098/*
4099 *
4100 *
4101 * Class Fetches
4102 *
4103 *
4104 */
4105
4106/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004107 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004108 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004109__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004110{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004111 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004112}
4113
4114/* This function creates and push in the stack a fetch object according
4115 * with a current TXN.
4116 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004117static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004118{
Willy Tarreau7073c472015-04-06 11:15:40 +02004119 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004120
4121 /* Check stack size. */
4122 if (!lua_checkstack(L, 3))
4123 return 0;
4124
4125 /* Create the object: obj[0] = userdata.
4126 * Note that the base of the Fetches object is the
4127 * transaction object.
4128 */
4129 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004130 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004131 lua_rawseti(L, -2, 0);
4132
Willy Tarreau7073c472015-04-06 11:15:40 +02004133 hsmp->s = txn->s;
4134 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004135 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004136 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004137
4138 /* Pop a class sesison metatable and affect it to the userdata. */
4139 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4140 lua_setmetatable(L, -2);
4141
4142 return 1;
4143}
4144
4145/* This function is an LUA binding. It is called with each sample-fetch.
4146 * It uses closure argument to store the associated sample-fetch. It
4147 * returns only one argument or throws an error. An error is thrown
4148 * only if an error is encountered during the argument parsing. If
4149 * the "sample-fetch" function fails, nil is returned.
4150 */
4151__LJMP static int hlua_run_sample_fetch(lua_State *L)
4152{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004153 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004154 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004155 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004156 int i;
4157 struct sample smp;
4158
4159 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004160 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004161
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004162 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004163 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004164
Thierry FOURNIERca988662015-12-20 18:43:03 +01004165 /* Check execution authorization. */
4166 if (f->use & SMP_USE_HTTP_ANY &&
4167 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4168 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4169 "is not available in Lua services", f->kw);
4170 WILL_LJMP(lua_error(L));
4171 }
4172
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004173 /* Get extra arguments. */
4174 for (i = 0; i < lua_gettop(L) - 1; i++) {
4175 if (i >= ARGM_NBARGS)
4176 break;
4177 hlua_lua2arg(L, i + 2, &args[i]);
4178 }
4179 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004180 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004181
4182 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004183 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004184
4185 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004186 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004187 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004188 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004189 }
4190
4191 /* Initialise the sample. */
4192 memset(&smp, 0, sizeof(smp));
4193
4194 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004195 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004196 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004197 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004198 lua_pushstring(L, "");
4199 else
4200 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004201 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004202 }
4203
4204 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004205 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004206 hlua_smp2lua_str(L, &smp);
4207 else
4208 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004209
4210 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004211 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004212 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004213
4214 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004215 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004216 WILL_LJMP(lua_error(L));
4217 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004218}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004219
4220/*
4221 *
4222 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004223 * Class Converters
4224 *
4225 *
4226 */
4227
4228/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004229 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004230 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004231__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004232{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004233 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004234}
4235
4236/* This function creates and push in the stack a Converters object
4237 * according with a current TXN.
4238 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004239static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004240{
Willy Tarreau7073c472015-04-06 11:15:40 +02004241 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004242
4243 /* Check stack size. */
4244 if (!lua_checkstack(L, 3))
4245 return 0;
4246
4247 /* Create the object: obj[0] = userdata.
4248 * Note that the base of the Converters object is the
4249 * same than the TXN object.
4250 */
4251 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004252 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004253 lua_rawseti(L, -2, 0);
4254
Willy Tarreau7073c472015-04-06 11:15:40 +02004255 hsmp->s = txn->s;
4256 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004257 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004258 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004259
Willy Tarreau87b09662015-04-03 00:22:06 +02004260 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004261 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4262 lua_setmetatable(L, -2);
4263
4264 return 1;
4265}
4266
4267/* This function is an LUA binding. It is called with each converter.
4268 * It uses closure argument to store the associated converter. It
4269 * returns only one argument or throws an error. An error is thrown
4270 * only if an error is encountered during the argument parsing. If
4271 * the converter function function fails, nil is returned.
4272 */
4273__LJMP static int hlua_run_sample_conv(lua_State *L)
4274{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004275 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004276 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004277 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004278 int i;
4279 struct sample smp;
4280
4281 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004282 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004283
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004284 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004285 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004286
4287 /* Get extra arguments. */
4288 for (i = 0; i < lua_gettop(L) - 2; i++) {
4289 if (i >= ARGM_NBARGS)
4290 break;
4291 hlua_lua2arg(L, i + 3, &args[i]);
4292 }
4293 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004294 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004295
4296 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004297 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004298
4299 /* Run the special args checker. */
4300 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4301 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004302 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004303 }
4304
4305 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004306 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004307 if (!hlua_lua2smp(L, 2, &smp)) {
4308 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004309 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004310 }
4311
Willy Tarreau1777ea62016-03-10 16:15:46 +01004312 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4313
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004314 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004315 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004316 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004317 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004318 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004319 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004320 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4321 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004322 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004323 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004324 }
4325
4326 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004327 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004328 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004329 lua_pushstring(L, "");
4330 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004331 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004332 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004333 }
4334
4335 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004336 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004337 hlua_smp2lua_str(L, &smp);
4338 else
4339 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004340 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004341 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004342 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004343
4344 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004345 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004346 WILL_LJMP(lua_error(L));
4347 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004348}
4349
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004350/*
4351 *
4352 *
4353 * Class AppletTCP
4354 *
4355 *
4356 */
4357
4358/* Returns a struct hlua_txn if the stack entry "ud" is
4359 * a class stream, otherwise it throws an error.
4360 */
4361__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4362{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004363 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004364}
4365
4366/* This function creates and push in the stack an Applet object
4367 * according with a current TXN.
4368 */
4369static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4370{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004371 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004372 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004373 struct proxy *p;
4374
4375 ALREADY_CHECKED(s);
4376 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004377
4378 /* Check stack size. */
4379 if (!lua_checkstack(L, 3))
4380 return 0;
4381
4382 /* Create the object: obj[0] = userdata.
4383 * Note that the base of the Converters object is the
4384 * same than the TXN object.
4385 */
4386 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004387 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004388 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004389 luactx->appctx = ctx;
4390 luactx->htxn.s = s;
4391 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004392
4393 /* Create the "f" field that contains a list of fetches. */
4394 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004395 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004396 return 0;
4397 lua_settable(L, -3);
4398
4399 /* Create the "sf" field that contains a list of stringsafe fetches. */
4400 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004401 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004402 return 0;
4403 lua_settable(L, -3);
4404
4405 /* Create the "c" field that contains a list of converters. */
4406 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004407 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004408 return 0;
4409 lua_settable(L, -3);
4410
4411 /* Create the "sc" field that contains a list of stringsafe converters. */
4412 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004413 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004414 return 0;
4415 lua_settable(L, -3);
4416
4417 /* Pop a class stream metatable and affect it to the table. */
4418 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4419 lua_setmetatable(L, -2);
4420
4421 return 1;
4422}
4423
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004424__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4425{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004426 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004427 struct stream *s;
4428 const char *name;
4429 size_t len;
4430 struct sample smp;
4431
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004432 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4433 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004434
4435 /* It is useles to retrieve the stream, but this function
4436 * runs only in a stream context.
4437 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004438 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004439 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004440 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004441
4442 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004443 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004444 hlua_lua2smp(L, 3, &smp);
4445
4446 /* Store the sample in a variable. */
4447 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004448
4449 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4450 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4451 else
4452 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4453
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004454 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004455}
4456
4457__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4458{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004459 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004460 struct stream *s;
4461 const char *name;
4462 size_t len;
4463 struct sample smp;
4464
4465 MAY_LJMP(check_args(L, 2, "unset_var"));
4466
4467 /* It is useles to retrieve the stream, but this function
4468 * runs only in a stream context.
4469 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004470 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004471 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004472 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004473
4474 /* Unset the variable. */
4475 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004476 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4477 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004478}
4479
4480__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4481{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004482 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004483 struct stream *s;
4484 const char *name;
4485 size_t len;
4486 struct sample smp;
4487
4488 MAY_LJMP(check_args(L, 2, "get_var"));
4489
4490 /* It is useles to retrieve the stream, but this function
4491 * runs only in a stream context.
4492 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004493 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004494 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004495 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004496
4497 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004498 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004499 lua_pushnil(L);
4500 return 1;
4501 }
4502
4503 return hlua_smp2lua(L, &smp);
4504}
4505
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004506__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4507{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004508 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4509 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004510 struct hlua *hlua;
4511
4512 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004513 if (!s->hlua)
4514 return 0;
4515 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004516
4517 MAY_LJMP(check_args(L, 2, "set_priv"));
4518
4519 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004520 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004521
4522 /* Get and store new value. */
4523 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4524 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4525
4526 return 0;
4527}
4528
4529__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4530{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004531 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4532 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004533 struct hlua *hlua;
4534
4535 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004536 if (!s->hlua) {
4537 lua_pushnil(L);
4538 return 1;
4539 }
4540 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004541
4542 /* Push configuration index in the stack. */
4543 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4544
4545 return 1;
4546}
4547
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004548/* If expected data not yet available, it returns a yield. This function
4549 * consumes the data in the buffer. It returns a string containing the
4550 * data. This string can be empty.
4551 */
4552__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4553{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004554 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004555 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004556 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004557 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004558 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004559 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004560 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004561
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004562 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004563 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004564
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004565 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004567 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004568 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004569 }
4570
4571 /* End of data: commit the total strings and return. */
4572 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004573 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004574 return 1;
4575 }
4576
4577 /* Ensure that the block 2 length is usable. */
4578 if (ret == 1)
4579 len2 = 0;
4580
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004581 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004582 luaL_addlstring(&luactx->b, blk1, len1);
4583 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584
4585 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004586 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004587 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588 return 1;
4589}
4590
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004591/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004592__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4593{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004594 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004595
4596 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004597 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004598
4599 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4600}
4601
4602/* If expected data not yet available, it returns a yield. This function
4603 * consumes the data in the buffer. It returns a string containing the
4604 * data. This string can be empty.
4605 */
4606__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4607{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004608 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004609 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004610 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004611 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004612 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004613 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004614 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004615 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004616
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004617 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004618 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004619
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004620 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004621 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004622 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004623 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004624 }
4625
4626 /* End of data: commit the total strings and return. */
4627 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004628 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004629 return 1;
4630 }
4631
4632 /* Ensure that the block 2 length is usable. */
4633 if (ret == 1)
4634 len2 = 0;
4635
4636 if (len == -1) {
4637
4638 /* If len == -1, catenate all the data avalaile and
4639 * yield because we want to get all the data until
4640 * the end of data stream.
4641 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004642 luaL_addlstring(&luactx->b, blk1, len1);
4643 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004644 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004645 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004646 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004647
4648 } else {
4649
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004650 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004651 if (len1 > len)
4652 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004653 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004654 len -= len1;
4655
4656 /* Copy the second block. */
4657 if (len2 > len)
4658 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004659 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004660 len -= len2;
4661
4662 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004663 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004664
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004665 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004666 if (len > 0) {
4667 lua_pushinteger(L, len);
4668 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004669 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004670 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004671 }
4672
4673 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004674 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004675 return 1;
4676 }
4677
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004678 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004679 hlua_pusherror(L, "Lua: internal error");
4680 WILL_LJMP(lua_error(L));
4681 return 0;
4682}
4683
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004684/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004685__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4686{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004687 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004688 int len = -1;
4689
4690 if (lua_gettop(L) > 2)
4691 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4692 if (lua_gettop(L) >= 2) {
4693 len = MAY_LJMP(luaL_checkinteger(L, 2));
4694 lua_pop(L, 1);
4695 }
4696
4697 /* Confirm or set the required length */
4698 lua_pushinteger(L, len);
4699
4700 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004701 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004702
4703 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4704}
4705
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004706/* Append data in the output side of the buffer. This data is immediately
4707 * sent. The function returns the amount of data written. If the buffer
4708 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004709 * if the channel is closed.
4710 */
4711__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4712{
4713 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004714 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004715 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4716 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004717 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004718 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004719 int max;
4720
4721 /* Get the max amount of data which can write as input in the channel. */
4722 max = channel_recv_max(chn);
4723 if (max > (len - l))
4724 max = len - l;
4725
4726 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004727 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004728
4729 /* update counters. */
4730 l += max;
4731 lua_pop(L, 1);
4732 lua_pushinteger(L, l);
4733
4734 /* If some data is not send, declares the situation to the
4735 * applet, and returns a yield.
4736 */
4737 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004738 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004739 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004740 }
4741
4742 return 1;
4743}
4744
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004745/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004746 * yield the LUA process, and resume it without checking the
4747 * input arguments.
4748 */
4749__LJMP static int hlua_applet_tcp_send(lua_State *L)
4750{
4751 MAY_LJMP(check_args(L, 2, "send"));
4752 lua_pushinteger(L, 0);
4753
4754 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4755}
4756
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004757/*
4758 *
4759 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004760 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004761 *
4762 *
4763 */
4764
4765/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004766 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004767 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004768__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004769{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004770 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004771}
4772
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004773/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004774 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004775 * It relies on the caller to have already reserved the room in ctx->svcctx
4776 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004777 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004778static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004779{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004780 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004781 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004782 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004783 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004784 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004785 struct htx *htx;
4786 struct htx_blk *blk;
4787 struct htx_sl *sl;
4788 struct ist path;
4789 unsigned long long len = 0;
4790 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004791 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004792
4793 /* Check stack size. */
4794 if (!lua_checkstack(L, 3))
4795 return 0;
4796
4797 /* Create the object: obj[0] = userdata.
4798 * Note that the base of the Converters object is the
4799 * same than the TXN object.
4800 */
4801 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004803 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004804 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004805 http_ctx->status = 200; /* Default status code returned. */
4806 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004807 luactx->htxn.s = s;
4808 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004809
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004810 /* Create the "f" field that contains a list of fetches. */
4811 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004812 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004813 return 0;
4814 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004815
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004816 /* Create the "sf" field that contains a list of stringsafe fetches. */
4817 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004818 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004819 return 0;
4820 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004822 /* Create the "c" field that contains a list of converters. */
4823 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004824 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004825 return 0;
4826 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004827
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004828 /* Create the "sc" field that contains a list of stringsafe converters. */
4829 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004830 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004831 return 0;
4832 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004833
Christopher Fauleta2097962019-07-15 16:25:33 +02004834 htx = htxbuf(&s->req.buf);
4835 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004836 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004837 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004838
Christopher Fauleta2097962019-07-15 16:25:33 +02004839 /* Stores the request method. */
4840 lua_pushstring(L, "method");
4841 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4842 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004843
Christopher Fauleta2097962019-07-15 16:25:33 +02004844 /* Stores the http version. */
4845 lua_pushstring(L, "version");
4846 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4847 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004848
Christopher Fauleta2097962019-07-15 16:25:33 +02004849 /* creates an array of headers. hlua_http_get_headers() crates and push
4850 * the array on the top of the stack.
4851 */
4852 lua_pushstring(L, "headers");
4853 htxn.s = s;
4854 htxn.p = px;
4855 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004856 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004857 return 0;
4858 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004859
Amaury Denoyellec453f952021-07-06 11:40:12 +02004860 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4861 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004862 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004863 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004864
Christopher Fauleta2097962019-07-15 16:25:33 +02004865 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004866 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004867 q = p;
4868 while (q < end && *q != '?')
4869 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004870
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004871 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004872 lua_pushstring(L, "path");
4873 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004874 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004875
Christopher Fauleta2097962019-07-15 16:25:33 +02004876 /* Stores the query string. */
4877 lua_pushstring(L, "qs");
4878 if (*q == '?')
4879 q++;
4880 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004881 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004882 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004883
Christopher Fauleta2097962019-07-15 16:25:33 +02004884 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4885 struct htx_blk *blk = htx_get_blk(htx, pos);
4886 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004887
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004888 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004889 break;
4890 if (type == HTX_BLK_DATA)
4891 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004892 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01004893 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02004894 len += htx->extra;
4895
4896 /* Stores the request path. */
4897 lua_pushstring(L, "length");
4898 lua_pushinteger(L, len);
4899 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004900
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004901 /* Create an empty array of HTTP request headers. */
4902 lua_pushstring(L, "response");
4903 lua_newtable(L);
4904 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004905
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004906 /* Pop a class stream metatable and affect it to the table. */
4907 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4908 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004909
4910 return 1;
4911}
4912
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004913__LJMP static int hlua_applet_http_set_var(lua_State *L)
4914{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004915 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004916 struct stream *s;
4917 const char *name;
4918 size_t len;
4919 struct sample smp;
4920
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004921 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4922 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004923
4924 /* It is useles to retrieve the stream, but this function
4925 * runs only in a stream context.
4926 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004927 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004928 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004929 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004930
4931 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004932 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004933 hlua_lua2smp(L, 3, &smp);
4934
4935 /* Store the sample in a variable. */
4936 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004937
4938 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4939 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4940 else
4941 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4942
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004943 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004944}
4945
4946__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4947{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004948 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004949 struct stream *s;
4950 const char *name;
4951 size_t len;
4952 struct sample smp;
4953
4954 MAY_LJMP(check_args(L, 2, "unset_var"));
4955
4956 /* It is useles to retrieve the stream, but this function
4957 * runs only in a stream context.
4958 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004959 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004960 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004961 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004962
4963 /* Unset the variable. */
4964 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004965 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4966 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004967}
4968
4969__LJMP static int hlua_applet_http_get_var(lua_State *L)
4970{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004971 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004972 struct stream *s;
4973 const char *name;
4974 size_t len;
4975 struct sample smp;
4976
4977 MAY_LJMP(check_args(L, 2, "get_var"));
4978
4979 /* It is useles to retrieve the stream, but this function
4980 * runs only in a stream context.
4981 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004982 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004983 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004984 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004985
4986 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004987 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004988 lua_pushnil(L);
4989 return 1;
4990 }
4991
4992 return hlua_smp2lua(L, &smp);
4993}
4994
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004995__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4996{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004997 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4998 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004999 struct hlua *hlua;
5000
5001 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005002 if (!s->hlua)
5003 return 0;
5004 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005005
5006 MAY_LJMP(check_args(L, 2, "set_priv"));
5007
5008 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005009 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005010
5011 /* Get and store new value. */
5012 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5013 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5014
5015 return 0;
5016}
5017
5018__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5019{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005020 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5021 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005022 struct hlua *hlua;
5023
5024 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005025 if (!s->hlua) {
5026 lua_pushnil(L);
5027 return 1;
5028 }
5029 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005030
5031 /* Push configuration index in the stack. */
5032 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5033
5034 return 1;
5035}
5036
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005037/* If expected data not yet available, it returns a yield. This function
5038 * consumes the data in the buffer. It returns a string containing the
5039 * data. This string can be empty.
5040 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005041__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005042{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005043 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005044 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005045 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005046 struct htx *htx;
5047 struct htx_blk *blk;
5048 size_t count;
5049 int stop = 0;
5050
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005051 htx = htx_from_buf(&req->buf);
5052 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005053 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005054
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005055 while (count && !stop && blk) {
5056 enum htx_blk_type type = htx_get_blk_type(blk);
5057 uint32_t sz = htx_get_blksz(blk);
5058 struct ist v;
5059 uint32_t vlen;
5060 char *nl;
5061
5062 vlen = sz;
5063 if (vlen > count) {
5064 if (type != HTX_BLK_DATA)
5065 break;
5066 vlen = count;
5067 }
5068
5069 switch (type) {
5070 case HTX_BLK_UNUSED:
5071 break;
5072
5073 case HTX_BLK_DATA:
5074 v = htx_get_blk_value(htx, blk);
5075 v.len = vlen;
5076 nl = istchr(v, '\n');
5077 if (nl != NULL) {
5078 stop = 1;
5079 vlen = nl - v.ptr + 1;
5080 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005081 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005082 break;
5083
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005084 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005085 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005086 stop = 1;
5087 break;
5088
5089 default:
5090 break;
5091 }
5092
Willy Tarreau84240042022-02-28 16:51:23 +01005093 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005094 count -= vlen;
5095 if (sz == vlen)
5096 blk = htx_remove_blk(htx, blk);
5097 else {
5098 htx_cut_data_blk(htx, blk, vlen);
5099 break;
5100 }
5101 }
5102
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005103 /* The message was fully consumed and no more data are expected
5104 * (EOM flag set).
5105 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005106 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005107 stop = 1;
5108
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005109 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005110 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005111 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005112 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005113 }
5114
5115 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005116 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005117 return 1;
5118}
5119
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005120
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005121/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005122__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005123{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005124 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005125
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005126 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005127 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005128
Christopher Fauleta2097962019-07-15 16:25:33 +02005129 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005130}
5131
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005132/* If expected data not yet available, it returns a yield. This function
5133 * consumes the data in the buffer. It returns a string containing the
5134 * data. This string can be empty.
5135 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005136__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005137{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005138 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005139 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005140 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005141 struct htx *htx;
5142 struct htx_blk *blk;
5143 size_t count;
5144 int len;
5145
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005146 htx = htx_from_buf(&req->buf);
5147 len = MAY_LJMP(luaL_checkinteger(L, 2));
5148 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005149 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005150 while (count && len && blk) {
5151 enum htx_blk_type type = htx_get_blk_type(blk);
5152 uint32_t sz = htx_get_blksz(blk);
5153 struct ist v;
5154 uint32_t vlen;
5155
5156 vlen = sz;
5157 if (len > 0 && vlen > len)
5158 vlen = len;
5159 if (vlen > count) {
5160 if (type != HTX_BLK_DATA)
5161 break;
5162 vlen = count;
5163 }
5164
5165 switch (type) {
5166 case HTX_BLK_UNUSED:
5167 break;
5168
5169 case HTX_BLK_DATA:
5170 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005171 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005172 break;
5173
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005174 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005175 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005176 len = 0;
5177 break;
5178
5179 default:
5180 break;
5181 }
5182
Willy Tarreau84240042022-02-28 16:51:23 +01005183 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005184 count -= vlen;
5185 if (len > 0)
5186 len -= vlen;
5187 if (sz == vlen)
5188 blk = htx_remove_blk(htx, blk);
5189 else {
5190 htx_cut_data_blk(htx, blk, vlen);
5191 break;
5192 }
5193 }
5194
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005195 /* The message was fully consumed and no more data are expected
5196 * (EOM flag set).
5197 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005198 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005199 len = 0;
5200
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005201 htx_to_buf(htx, &req->buf);
5202
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005203 /* If we are no other data available, yield waiting for new data. */
5204 if (len) {
5205 if (len > 0) {
5206 lua_pushinteger(L, len);
5207 lua_replace(L, 2);
5208 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005209 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005210 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005211 }
5212
5213 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005214 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005215 return 1;
5216}
5217
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005218/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005219__LJMP static int hlua_applet_http_recv(lua_State *L)
5220{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005221 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005222 int len = -1;
5223
5224 /* Check arguments. */
5225 if (lua_gettop(L) > 2)
5226 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5227 if (lua_gettop(L) >= 2) {
5228 len = MAY_LJMP(luaL_checkinteger(L, 2));
5229 lua_pop(L, 1);
5230 }
5231
Christopher Fauleta2097962019-07-15 16:25:33 +02005232 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005233
Christopher Fauleta2097962019-07-15 16:25:33 +02005234 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005235 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005236
Christopher Fauleta2097962019-07-15 16:25:33 +02005237 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005238}
5239
5240/* Append data in the output side of the buffer. This data is immediately
5241 * sent. The function returns the amount of data written. If the buffer
5242 * cannot contain the data, the function yields. The function returns -1
5243 * if the channel is closed.
5244 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005245__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005246{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005247 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005248 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005249 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005250 struct htx *htx = htx_from_buf(&res->buf);
5251 const char *data;
5252 size_t len;
5253 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5254 int max;
5255
Christopher Faulet9060fc02019-07-03 11:39:30 +02005256 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005257 if (!max)
5258 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005259
5260 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5261
5262 /* Get the max amount of data which can write as input in the channel. */
5263 if (max > (len - l))
5264 max = len - l;
5265
5266 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005267 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005268 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005269
5270 /* update counters. */
5271 l += max;
5272 lua_pop(L, 1);
5273 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005274
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005275 /* If some data is not send, declares the situation to the
5276 * applet, and returns a yield.
5277 */
5278 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005279 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005280 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005281 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005282 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005283 }
5284
Christopher Fauleta2097962019-07-15 16:25:33 +02005285 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005286 return 1;
5287}
5288
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005289/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005290 * yield the LUA process, and resume it without checking the
5291 * input arguments.
5292 */
5293__LJMP static int hlua_applet_http_send(lua_State *L)
5294{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005295 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005296 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005297
5298 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005299 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005300 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5301 WILL_LJMP(lua_error(L));
5302 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005303
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005304 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005305 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005306
Christopher Fauleta2097962019-07-15 16:25:33 +02005307 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005308}
5309
5310__LJMP static int hlua_applet_http_addheader(lua_State *L)
5311{
5312 const char *name;
5313 int ret;
5314
5315 MAY_LJMP(hlua_checkapplet_http(L, 1));
5316 name = MAY_LJMP(luaL_checkstring(L, 2));
5317 MAY_LJMP(luaL_checkstring(L, 3));
5318
5319 /* Push in the stack the "response" entry. */
5320 ret = lua_getfield(L, 1, "response");
5321 if (ret != LUA_TTABLE) {
5322 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5323 "is expected as an array. %s found", lua_typename(L, ret));
5324 WILL_LJMP(lua_error(L));
5325 }
5326
5327 /* check if the header is already registered if it is not
5328 * the case, register it.
5329 */
5330 ret = lua_getfield(L, -1, name);
5331 if (ret == LUA_TNIL) {
5332
5333 /* Entry not found. */
5334 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5335
5336 /* Insert the new header name in the array in the top of the stack.
5337 * It left the new array in the top of the stack.
5338 */
5339 lua_newtable(L);
5340 lua_pushvalue(L, 2);
5341 lua_pushvalue(L, -2);
5342 lua_settable(L, -4);
5343
5344 } else if (ret != LUA_TTABLE) {
5345
5346 /* corruption error. */
5347 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5348 "is expected as an array. %s found", name, lua_typename(L, ret));
5349 WILL_LJMP(lua_error(L));
5350 }
5351
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005352 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005353 * the header value as new entry.
5354 */
5355 lua_pushvalue(L, 3);
5356 ret = lua_rawlen(L, -2);
5357 lua_rawseti(L, -2, ret + 1);
5358 lua_pushboolean(L, 1);
5359 return 1;
5360}
5361
5362__LJMP static int hlua_applet_http_status(lua_State *L)
5363{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005364 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005365 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005366 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005367 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005368
5369 if (status < 100 || status > 599) {
5370 lua_pushboolean(L, 0);
5371 return 1;
5372 }
5373
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005374 http_ctx->status = status;
5375 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005376 lua_pushboolean(L, 1);
5377 return 1;
5378}
5379
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380
Christopher Fauleta2097962019-07-15 16:25:33 +02005381__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005382{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005383 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005384 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005385 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005386 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005387 struct htx *htx;
5388 struct htx_sl *sl;
5389 struct h1m h1m;
5390 const char *status, *reason;
5391 const char *name, *value;
5392 size_t nlen, vlen;
5393 unsigned int flags;
5394
5395 /* Send the message at once. */
5396 htx = htx_from_buf(&res->buf);
5397 h1m_init_res(&h1m);
5398
5399 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005400 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5401 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005402 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005403 reason = http_get_reason(http_ctx->status);
5404 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005405 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5406 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5407 }
5408 else {
5409 flags = HTX_SL_F_IS_RESP;
5410 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5411 }
5412 if (!sl) {
5413 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005414 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005415 WILL_LJMP(lua_error(L));
5416 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005417 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005418
5419 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005420 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5421 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005422 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005423 WILL_LJMP(lua_error(L));
5424 }
5425
5426 /* Browse the list of headers. */
5427 lua_pushnil(L);
5428 while(lua_next(L, -2) != 0) {
5429 /* We expect a string as -2. */
5430 if (lua_type(L, -2) != LUA_TSTRING) {
5431 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005432 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005433 lua_typename(L, lua_type(L, -2)));
5434 WILL_LJMP(lua_error(L));
5435 }
5436 name = lua_tolstring(L, -2, &nlen);
5437
5438 /* We expect an array as -1. */
5439 if (lua_type(L, -1) != LUA_TTABLE) {
5440 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 +02005441 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005442 name,
5443 lua_typename(L, lua_type(L, -1)));
5444 WILL_LJMP(lua_error(L));
5445 }
5446
5447 /* Browse the table who is on the top of the stack. */
5448 lua_pushnil(L);
5449 while(lua_next(L, -2) != 0) {
5450 int id;
5451
5452 /* We expect a number as -2. */
5453 if (lua_type(L, -2) != LUA_TNUMBER) {
5454 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 +02005455 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005456 name,
5457 lua_typename(L, lua_type(L, -2)));
5458 WILL_LJMP(lua_error(L));
5459 }
5460 id = lua_tointeger(L, -2);
5461
5462 /* We expect a string as -2. */
5463 if (lua_type(L, -1) != LUA_TSTRING) {
5464 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 +02005465 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005466 name, id,
5467 lua_typename(L, lua_type(L, -1)));
5468 WILL_LJMP(lua_error(L));
5469 }
5470 value = lua_tolstring(L, -1, &vlen);
5471
5472 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005473 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5474 int ret;
5475
5476 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5477 if (ret < 0) {
5478 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5479 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5480 name);
5481 WILL_LJMP(lua_error(L));
5482 }
5483 else if (ret == 0)
5484 goto next; /* Skip it */
5485 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005486 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5487 struct ist v = ist2(value, vlen);
5488 int ret;
5489
5490 ret = h1_parse_cont_len_header(&h1m, &v);
5491 if (ret < 0) {
5492 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005493 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005494 name);
5495 WILL_LJMP(lua_error(L));
5496 }
5497 else if (ret == 0)
5498 goto next; /* Skip it */
5499 }
5500
5501 /* Add a new header */
5502 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5503 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005504 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005505 name);
5506 WILL_LJMP(lua_error(L));
5507 }
5508 next:
5509 /* Remove the array from the stack, and get next element with a remaining string. */
5510 lua_pop(L, 1);
5511 }
5512
5513 /* Remove the array from the stack, and get next element with a remaining string. */
5514 lua_pop(L, 1);
5515 }
5516
5517 if (h1m.flags & H1_MF_CHNK)
5518 h1m.flags &= ~H1_MF_CLEN;
5519 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5520 h1m.flags |= H1_MF_XFER_LEN;
5521
5522 /* Uset HTX start-line flags */
5523 if (h1m.flags & H1_MF_XFER_ENC)
5524 flags |= HTX_SL_F_XFER_ENC;
5525 if (h1m.flags & H1_MF_XFER_LEN) {
5526 flags |= HTX_SL_F_XFER_LEN;
5527 if (h1m.flags & H1_MF_CHNK)
5528 flags |= HTX_SL_F_CHNK;
5529 else if (h1m.flags & H1_MF_CLEN)
5530 flags |= HTX_SL_F_CLEN;
5531 if (h1m.body_len == 0)
5532 flags |= HTX_SL_F_BODYLESS;
5533 }
5534 sl->flags |= flags;
5535
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005536 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005537 * and the status code implies the presence of a message body, we must
5538 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005539 * for the keepalive compliance. If the applet announces a transfer-encoding
5540 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005541 */
5542 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005543 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005544 /* Add a new header */
5545 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5546 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5547 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005548 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549 WILL_LJMP(lua_error(L));
5550 }
5551 }
5552
5553 /* Finalize headers. */
5554 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5555 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005556 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005557 WILL_LJMP(lua_error(L));
5558 }
5559
5560 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5561 b_reset(&res->buf);
5562 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5563 WILL_LJMP(lua_error(L));
5564 }
5565
5566 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005567 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005568
5569 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005570 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005571 return 0;
5572
5573}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005574/* We will build the status line and the headers of the HTTP response.
5575 * We will try send at once if its not possible, we give back the hand
5576 * waiting for more room.
5577 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005578__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005579{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005580 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005581 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005582 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005583
5584 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005585 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005586 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005587 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005588 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005589}
5590
5591
Christopher Fauleta2097962019-07-15 16:25:33 +02005592__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005593{
Christopher Fauleta2097962019-07-15 16:25:33 +02005594 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005595}
5596
Christopher Fauleta2097962019-07-15 16:25:33 +02005597/*
5598 *
5599 *
5600 * Class HTTP
5601 *
5602 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005603 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005604
5605/* Returns a struct hlua_txn if the stack entry "ud" is
5606 * a class stream, otherwise it throws an error.
5607 */
5608__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005609{
Christopher Fauleta2097962019-07-15 16:25:33 +02005610 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5611}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005612
Christopher Fauleta2097962019-07-15 16:25:33 +02005613/* This function creates and push in the stack a HTTP object
5614 * according with a current TXN.
5615 */
5616static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5617{
5618 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005619
Christopher Fauleta2097962019-07-15 16:25:33 +02005620 /* Check stack size. */
5621 if (!lua_checkstack(L, 3))
5622 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005623
Christopher Fauleta2097962019-07-15 16:25:33 +02005624 /* Create the object: obj[0] = userdata.
5625 * Note that the base of the Converters object is the
5626 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005628 lua_newtable(L);
5629 htxn = lua_newuserdata(L, sizeof(*htxn));
5630 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005631
5632 htxn->s = txn->s;
5633 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005634 htxn->dir = txn->dir;
5635 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005636
5637 /* Pop a class stream metatable and affect it to the table. */
5638 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5639 lua_setmetatable(L, -2);
5640
5641 return 1;
5642}
5643
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005644/* This function creates and returns an array containing the status-line
5645 * elements. This function does not fails.
5646 */
5647__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5648{
5649 /* Create the table. */
5650 lua_newtable(L);
5651
5652 if (sl->flags & HTX_SL_F_IS_RESP) {
5653 lua_pushstring(L, "version");
5654 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5655 lua_settable(L, -3);
5656 lua_pushstring(L, "code");
5657 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5658 lua_settable(L, -3);
5659 lua_pushstring(L, "reason");
5660 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5661 lua_settable(L, -3);
5662 }
5663 else {
5664 lua_pushstring(L, "method");
5665 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5666 lua_settable(L, -3);
5667 lua_pushstring(L, "uri");
5668 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5669 lua_settable(L, -3);
5670 lua_pushstring(L, "version");
5671 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5672 lua_settable(L, -3);
5673 }
5674 return 1;
5675}
5676
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005677/* This function creates ans returns an array of HTTP headers.
5678 * This function does not fails. It is used as wrapper with the
5679 * 2 following functions.
5680 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005681__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005682{
Christopher Fauleta2097962019-07-15 16:25:33 +02005683 struct htx *htx;
5684 int32_t pos;
5685
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005686 /* Create the table. */
5687 lua_newtable(L);
5688
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005689
Christopher Fauleta2097962019-07-15 16:25:33 +02005690 htx = htxbuf(&msg->chn->buf);
5691 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5692 struct htx_blk *blk = htx_get_blk(htx, pos);
5693 enum htx_blk_type type = htx_get_blk_type(blk);
5694 struct ist n, v;
5695 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005696
Christopher Fauleta2097962019-07-15 16:25:33 +02005697 if (type == HTX_BLK_HDR) {
5698 n = htx_get_blk_name(htx,blk);
5699 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005700 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005701 else if (type == HTX_BLK_EOH)
5702 break;
5703 else
5704 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005705
Christopher Fauleta2097962019-07-15 16:25:33 +02005706 /* Check for existing entry:
5707 * assume that the table is on the top of the stack, and
5708 * push the key in the stack, the function lua_gettable()
5709 * perform the lookup.
5710 */
5711 lua_pushlstring(L, n.ptr, n.len);
5712 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005713
Christopher Fauleta2097962019-07-15 16:25:33 +02005714 switch (lua_type(L, -1)) {
5715 case LUA_TNIL:
5716 /* Table not found, create it. */
5717 lua_pop(L, 1); /* remove the nil value. */
5718 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5719 lua_newtable(L); /* create and push empty table. */
5720 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5721 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5722 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005723 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005724
Christopher Fauleta2097962019-07-15 16:25:33 +02005725 case LUA_TTABLE:
5726 /* Entry found: push the value in the table. */
5727 len = lua_rawlen(L, -1);
5728 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5729 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5730 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5731 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005732
Christopher Fauleta2097962019-07-15 16:25:33 +02005733 default:
5734 /* Other cases are errors. */
5735 hlua_pusherror(L, "internal error during the parsing of headers.");
5736 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005737 }
5738 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005739 return 1;
5740}
5741
5742__LJMP static int hlua_http_req_get_headers(lua_State *L)
5743{
5744 struct hlua_txn *htxn;
5745
5746 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5747 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5748
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005749 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005750 WILL_LJMP(lua_error(L));
5751
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005752 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005753}
5754
5755__LJMP static int hlua_http_res_get_headers(lua_State *L)
5756{
5757 struct hlua_txn *htxn;
5758
5759 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5760 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5761
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005762 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005763 WILL_LJMP(lua_error(L));
5764
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005765 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005766}
5767
5768/* This function replace full header, or just a value in
5769 * the request or in the response. It is a wrapper fir the
5770 * 4 following functions.
5771 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005772__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005773{
5774 size_t name_len;
5775 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5776 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5777 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005778 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005779 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005780
Dragan Dosen26743032019-04-30 15:54:36 +02005781 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005782 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5783
Christopher Fauleta2097962019-07-15 16:25:33 +02005784 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005785 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005786 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005787 return 0;
5788}
5789
5790__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5791{
5792 struct hlua_txn *htxn;
5793
5794 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5795 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5796
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005797 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005798 WILL_LJMP(lua_error(L));
5799
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005800 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005801}
5802
5803__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5804{
5805 struct hlua_txn *htxn;
5806
5807 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5808 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5809
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005810 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005811 WILL_LJMP(lua_error(L));
5812
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005813 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005814}
5815
5816__LJMP static int hlua_http_req_rep_val(lua_State *L)
5817{
5818 struct hlua_txn *htxn;
5819
5820 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5821 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5822
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005823 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005824 WILL_LJMP(lua_error(L));
5825
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005826 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005827}
5828
5829__LJMP static int hlua_http_res_rep_val(lua_State *L)
5830{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005831 struct hlua_txn *htxn;
5832
5833 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5834 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5835
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005836 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005837 WILL_LJMP(lua_error(L));
5838
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005839 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005840}
5841
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005842/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005843 * It is a wrapper for the 2 following functions.
5844 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005845__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005846{
5847 size_t len;
5848 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005849 struct htx *htx = htxbuf(&msg->chn->buf);
5850 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005851
Christopher Fauleta2097962019-07-15 16:25:33 +02005852 ctx.blk = NULL;
5853 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5854 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005855 return 0;
5856}
5857
5858__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5859{
5860 struct hlua_txn *htxn;
5861
5862 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5863 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5864
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005865 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005866 WILL_LJMP(lua_error(L));
5867
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005868 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005869}
5870
5871__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5872{
5873 struct hlua_txn *htxn;
5874
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005875 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005876 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5877
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005878 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005879 WILL_LJMP(lua_error(L));
5880
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005881 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005882}
5883
5884/* This function adds an header. It is a wrapper used by
5885 * the 2 following functions.
5886 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005887__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005888{
5889 size_t name_len;
5890 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5891 size_t value_len;
5892 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005893 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005894
Christopher Fauleta2097962019-07-15 16:25:33 +02005895 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5896 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005897 return 0;
5898}
5899
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005900__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5901{
5902 struct hlua_txn *htxn;
5903
5904 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5905 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5906
5907 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5908 WILL_LJMP(lua_error(L));
5909
5910 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5911}
5912
5913__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5914{
5915 struct hlua_txn *htxn;
5916
5917 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5918 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5919
5920 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5921 WILL_LJMP(lua_error(L));
5922
5923 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5924}
5925
5926static int hlua_http_req_set_hdr(lua_State *L)
5927{
5928 struct hlua_txn *htxn;
5929
5930 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5931 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5932
5933 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5934 WILL_LJMP(lua_error(L));
5935
5936 hlua_http_del_hdr(L, &htxn->s->txn->req);
5937 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5938}
5939
5940static int hlua_http_res_set_hdr(lua_State *L)
5941{
5942 struct hlua_txn *htxn;
5943
5944 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5945 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5946
5947 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5948 WILL_LJMP(lua_error(L));
5949
5950 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5951 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5952}
5953
5954/* This function set the method. */
5955static int hlua_http_req_set_meth(lua_State *L)
5956{
5957 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5958 size_t name_len;
5959 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5960
5961 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5962 WILL_LJMP(lua_error(L));
5963
5964 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5965 return 1;
5966}
5967
5968/* This function set the method. */
5969static int hlua_http_req_set_path(lua_State *L)
5970{
5971 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5972 size_t name_len;
5973 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5974
5975 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5976 WILL_LJMP(lua_error(L));
5977
5978 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5979 return 1;
5980}
5981
5982/* This function set the query-string. */
5983static int hlua_http_req_set_query(lua_State *L)
5984{
5985 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5986 size_t name_len;
5987 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5988
5989 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5990 WILL_LJMP(lua_error(L));
5991
5992 /* Check length. */
5993 if (name_len > trash.size - 1) {
5994 lua_pushboolean(L, 0);
5995 return 1;
5996 }
5997
5998 /* Add the mark question as prefix. */
5999 chunk_reset(&trash);
6000 trash.area[trash.data++] = '?';
6001 memcpy(trash.area + trash.data, name, name_len);
6002 trash.data += name_len;
6003
6004 lua_pushboolean(L,
6005 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6006 return 1;
6007}
6008
6009/* This function set the uri. */
6010static int hlua_http_req_set_uri(lua_State *L)
6011{
6012 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6013 size_t name_len;
6014 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6015
6016 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6017 WILL_LJMP(lua_error(L));
6018
6019 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6020 return 1;
6021}
6022
6023/* This function set the response code & optionally reason. */
6024static int hlua_http_res_set_status(lua_State *L)
6025{
6026 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6027 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6028 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6029 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6030
6031 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6032 WILL_LJMP(lua_error(L));
6033
6034 http_res_set_status(code, reason, htxn->s);
6035 return 0;
6036}
6037
6038/*
6039 *
6040 *
6041 * Class HTTPMessage
6042 *
6043 *
6044 */
6045
6046/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6047 * otherwise it throws an error.
6048 */
6049__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6050{
6051 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6052}
6053
6054/* Creates and pushes on the stack a HTTP object according with a current TXN.
6055 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006056static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006057{
6058 /* Check stack size. */
6059 if (!lua_checkstack(L, 3))
6060 return 0;
6061
6062 lua_newtable(L);
6063 lua_pushlightuserdata(L, msg);
6064 lua_rawseti(L, -2, 0);
6065
6066 /* Create the "channel" field that contains the request channel object. */
6067 lua_pushstring(L, "channel");
6068 if (!hlua_channel_new(L, msg->chn))
6069 return 0;
6070 lua_rawset(L, -3);
6071
6072 /* Pop a class stream metatable and affect it to the table. */
6073 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6074 lua_setmetatable(L, -2);
6075
6076 return 1;
6077}
6078
6079/* Helper function returning a filter attached to the HTTP message at the
6080 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006081 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006082 * filled with output and input length respectively.
6083 */
6084static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6085{
6086 struct channel *chn = msg->chn;
6087 struct htx *htx = htxbuf(&chn->buf);
6088 struct filter *filter = NULL;
6089
6090 *offset = co_data(msg->chn);
6091 *len = htx->data - co_data(msg->chn);
6092
6093 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6094 filter = lua_touserdata (L, -1);
6095 if (msg->msg_state >= HTTP_MSG_DATA) {
6096 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6097
6098 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6099 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6100 }
6101 }
6102
6103 lua_pop(L, 1);
6104 return filter;
6105}
6106
6107/* Returns true if the channel attached to the HTTP message is the response
6108 * channel.
6109 */
6110__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6111{
6112 struct http_msg *msg;
6113
6114 MAY_LJMP(check_args(L, 1, "is_resp"));
6115 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6116
6117 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6118 return 1;
6119}
6120
6121/* Returns an array containing the elements status-line of the HTTP message. It relies
6122 * on hlua_http_get_stline().
6123 */
6124__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6125{
6126 struct http_msg *msg;
6127 struct htx *htx;
6128 struct htx_sl *sl;
6129
6130 MAY_LJMP(check_args(L, 1, "get_stline"));
6131 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6132
6133 if (msg->msg_state > HTTP_MSG_BODY)
6134 WILL_LJMP(lua_error(L));
6135
6136 htx = htxbuf(&msg->chn->buf);
6137 sl = http_get_stline(htx);
6138 if (!sl)
6139 return 0;
6140 return hlua_http_get_stline(L, sl);
6141}
6142
6143/* Returns an array containing all headers of the HTTP message. it relies on
6144 * hlua_http_get_headers().
6145 */
6146__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6147{
6148 struct http_msg *msg;
6149
6150 MAY_LJMP(check_args(L, 1, "get_headers"));
6151 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6152
6153 if (msg->msg_state > HTTP_MSG_BODY)
6154 WILL_LJMP(lua_error(L));
6155
6156 return hlua_http_get_headers(L, msg);
6157}
6158
6159/* Deletes all occurrences of an header in the HTTP message matching on its
6160 * name. It relies on hlua_http_del_hdr().
6161 */
6162__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6163{
6164 struct http_msg *msg;
6165
6166 MAY_LJMP(check_args(L, 2, "del_header"));
6167 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6168
6169 if (msg->msg_state > HTTP_MSG_BODY)
6170 WILL_LJMP(lua_error(L));
6171
6172 return hlua_http_del_hdr(L, msg);
6173}
6174
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006175/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006176 * message given its name against a regex and replaces it if it matches. It
6177 * relies on hlua_http_rep_hdr().
6178 */
6179__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6180{
6181 struct http_msg *msg;
6182
6183 MAY_LJMP(check_args(L, 4, "rep_header"));
6184 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6185
6186 if (msg->msg_state > HTTP_MSG_BODY)
6187 WILL_LJMP(lua_error(L));
6188
6189 return hlua_http_rep_hdr(L, msg, 1);
6190}
6191
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006192/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006193 * message given its name against a regex and replaces it if it matches. It
6194 * relies on hlua_http_rep_hdr().
6195 */
6196__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6197{
6198 struct http_msg *msg;
6199
6200 MAY_LJMP(check_args(L, 4, "rep_value"));
6201 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6202
6203 if (msg->msg_state > HTTP_MSG_BODY)
6204 WILL_LJMP(lua_error(L));
6205
6206 return hlua_http_rep_hdr(L, msg, 0);
6207}
6208
6209/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6210__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6211{
6212 struct http_msg *msg;
6213
6214 MAY_LJMP(check_args(L, 3, "add_header"));
6215 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6216
6217 if (msg->msg_state > HTTP_MSG_BODY)
6218 WILL_LJMP(lua_error(L));
6219
6220 return hlua_http_add_hdr(L, msg);
6221}
6222
6223/* Add an header in the HTTP message removing existing headers with the same
6224 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6225 */
6226__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6227{
6228 struct http_msg *msg;
6229
6230 MAY_LJMP(check_args(L, 3, "set_header"));
6231 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6232
6233 if (msg->msg_state > HTTP_MSG_BODY)
6234 WILL_LJMP(lua_error(L));
6235
6236 hlua_http_del_hdr(L, msg);
6237 return hlua_http_add_hdr(L, msg);
6238}
6239
6240/* Rewrites the request method. It relies on http_req_replace_stline(). */
6241__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6242{
6243 struct stream *s;
6244 struct http_msg *msg;
6245 const char *name;
6246 size_t name_len;
6247
6248 MAY_LJMP(check_args(L, 2, "set_method"));
6249 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6250 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6251
6252 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6253 WILL_LJMP(lua_error(L));
6254
6255 s = chn_strm(msg->chn);
6256 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6257 return 1;
6258}
6259
6260/* Rewrites the request path. It relies on http_req_replace_stline(). */
6261__LJMP static int hlua_http_msg_set_path(lua_State *L)
6262{
6263 struct stream *s;
6264 struct http_msg *msg;
6265 const char *name;
6266 size_t name_len;
6267
6268 MAY_LJMP(check_args(L, 2, "set_path"));
6269 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6270 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6271
6272 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6273 WILL_LJMP(lua_error(L));
6274
6275 s = chn_strm(msg->chn);
6276 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6277 return 1;
6278}
6279
6280/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6281__LJMP static int hlua_http_msg_set_query(lua_State *L)
6282{
6283 struct stream *s;
6284 struct http_msg *msg;
6285 const char *name;
6286 size_t name_len;
6287
6288 MAY_LJMP(check_args(L, 2, "set_query"));
6289 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6290 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6291
6292 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6293 WILL_LJMP(lua_error(L));
6294
6295 /* Check length. */
6296 if (name_len > trash.size - 1) {
6297 lua_pushboolean(L, 0);
6298 return 1;
6299 }
6300
6301 /* Add the mark question as prefix. */
6302 chunk_reset(&trash);
6303 trash.area[trash.data++] = '?';
6304 memcpy(trash.area + trash.data, name, name_len);
6305 trash.data += name_len;
6306
6307 s = chn_strm(msg->chn);
6308 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6309 return 1;
6310}
6311
6312/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6313__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6314{
6315 struct stream *s;
6316 struct http_msg *msg;
6317 const char *name;
6318 size_t name_len;
6319
6320 MAY_LJMP(check_args(L, 2, "set_uri"));
6321 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6322 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6323
6324 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6325 WILL_LJMP(lua_error(L));
6326
6327 s = chn_strm(msg->chn);
6328 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6329 return 1;
6330}
6331
6332/* Rewrites the response status code. It relies on http_res_set_status(). */
6333__LJMP static int hlua_http_msg_set_status(lua_State *L)
6334{
6335 struct http_msg *msg;
6336 unsigned int code;
6337 const char *reason;
6338 size_t reason_len;
6339
6340 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6341 code = MAY_LJMP(luaL_checkinteger(L, 2));
6342 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6343
6344 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6345 WILL_LJMP(lua_error(L));
6346
6347 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6348 return 1;
6349}
6350
6351/* Returns true if the HTTP message is full. */
6352__LJMP static int hlua_http_msg_is_full(lua_State *L)
6353{
6354 struct http_msg *msg;
6355
6356 MAY_LJMP(check_args(L, 1, "is_full"));
6357 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6358 lua_pushboolean(L, channel_full(msg->chn, 0));
6359 return 1;
6360}
6361
6362/* Returns true if the HTTP message may still receive data. */
6363__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6364{
6365 struct http_msg *msg;
6366 struct htx *htx;
6367
6368 MAY_LJMP(check_args(L, 1, "may_recv"));
6369 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6370 htx = htxbuf(&msg->chn->buf);
6371 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6372 return 1;
6373}
6374
6375/* Returns true if the HTTP message EOM was received */
6376__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6377{
6378 struct http_msg *msg;
6379 struct htx *htx;
6380
6381 MAY_LJMP(check_args(L, 1, "may_recv"));
6382 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6383 htx = htxbuf(&msg->chn->buf);
6384 lua_pushboolean(L, !htx_expect_more(htx));
6385 return 1;
6386}
6387
6388/* Returns the number of bytes available in the input side of the HTTP
6389 * message. This function never fails.
6390 */
6391__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6392{
6393 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006394 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006395
6396 MAY_LJMP(check_args(L, 1, "input"));
6397 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006398 hlua_http_msg_filter(L, 1, msg, &output, &input);
6399 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006400 return 1;
6401}
6402
6403/* Returns the number of bytes available in the output side of the HTTP
6404 * message. This function never fails.
6405 */
6406__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6407{
6408 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006409 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006410
6411 MAY_LJMP(check_args(L, 1, "output"));
6412 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006413 hlua_http_msg_filter(L, 1, msg, &output, &input);
6414 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006415 return 1;
6416}
6417
6418/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6419 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006420 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006421 * block. This function is called during the payload filtering, so the headers
6422 * are already scheduled for output (from the filter point of view).
6423 */
6424static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6425{
6426 struct htx *htx = htxbuf(&msg->chn->buf);
6427 struct htx_blk *blk;
6428 struct htx_ret htxret;
6429 luaL_Buffer b;
6430 int ret = 0;
6431
6432 luaL_buffinit(L, &b);
6433 htxret = htx_find_offset(htx, offset);
6434 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6435 enum htx_blk_type type = htx_get_blk_type(blk);
6436 struct ist v;
6437
6438 switch (type) {
6439 case HTX_BLK_UNUSED:
6440 break;
6441
6442 case HTX_BLK_DATA:
6443 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006444 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006445 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006446
6447 luaL_addlstring(&b, v.ptr, v.len);
6448 ret += v.len;
6449 break;
6450
6451 default:
vishnu0af4bd72021-10-24 06:46:24 +05306452 if (!ret)
6453 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006454 goto end;
6455 }
6456 offset = 0;
6457 }
6458
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006459end:
vishnu0af4bd72021-10-24 06:46:24 +05306460 if (!ret && (htx->flags & HTX_FL_EOM))
6461 goto no_data;
6462 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006463 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306464
6465 no_data:
6466 /* Remove the empty string and push nil on the stack */
6467 lua_pop(L, 1);
6468 lua_pushnil(L);
6469 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006470}
6471
6472/* Copies the string <str> to the HTTP message <msg> at the offset
6473 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006474 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006475 * the filter context.
6476 */
6477static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6478{
6479 struct htx *htx = htx_from_buf(&msg->chn->buf);
6480 struct htx_ret htxret;
6481 int /*max, */ret = 0;
6482
6483 /* Nothing to do, just return */
6484 if (unlikely(istlen(str) == 0))
6485 goto end;
6486
6487 if (istlen(str) > htx_free_data_space(htx)) {
6488 ret = -1;
6489 goto end;
6490 }
6491
6492 htxret = htx_find_offset(htx, offset);
6493 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6494 if (!htx_add_last_data(htx, str))
6495 goto end;
6496 }
6497 else {
6498 struct ist v = htx_get_blk_value(htx, htxret.blk);
6499 v.ptr += htxret.ret;
6500 v.len = 0;
6501 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6502 goto end;
6503 }
6504 ret = str.len;
6505 if (ret) {
6506 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6507 flt_update_offsets(filter, msg->chn, ret);
6508 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6509 }
6510
6511 end:
6512 htx_to_buf(htx, &msg->chn->buf);
6513 return ret;
6514}
6515
6516/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6517 * position <offset>. It stops on the first non-DATA HTX block. This function is
6518 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006519 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006520 * update the filter context.
6521 */
6522static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6523{
6524 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6525 struct htx *htx = htx_from_buf(&msg->chn->buf);
6526 struct htx_blk *blk;
6527 struct htx_ret htxret;
6528 size_t ret = 0;
6529
6530 /* Be sure <len> is always the amount of DATA to remove */
6531 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006532 /* When htx tail type == HTX_BLK_DATA, no need to take care
6533 * of special blocks like HTX_BLK_EOT.
6534 * We simply truncate after offset
6535 * (truncate targeted blk and discard the following ones)
6536 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006537 htx_truncate(htx, offset);
6538 ret = len;
6539 goto end;
6540 }
6541
6542 htxret = htx_find_offset(htx, offset);
6543 blk = htxret.blk;
6544 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006545 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006546 struct ist v;
6547
6548 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6549 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006550
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006551 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006552 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006553
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006554 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006555 /* trimming data in blk: discard everything after the offset
6556 * (replace 'v' with 'IST_NULL')
6557 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006558 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006559 if (blk && v.len < len) {
6560 /* In this case, caller wants to keep removing data,
6561 * but we need to spare current blk
6562 * because it was already trimmed
6563 */
6564 blk = htx_get_next_blk(htx, blk);
6565 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006566 len -= v.len;
6567 ret += v.len;
6568 }
6569
6570
6571 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006572 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006573 enum htx_blk_type type = htx_get_blk_type(blk);
6574 uint32_t sz = htx_get_blksz(blk);
6575
6576 switch (type) {
6577 case HTX_BLK_UNUSED:
6578 break;
6579
6580 case HTX_BLK_DATA:
6581 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006582 /* don't discard whole blk, only part of it
6583 * (from the beginning)
6584 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006585 htx_cut_data_blk(htx, blk, len);
6586 ret += len;
6587 goto end;
6588 }
6589 break;
6590
6591 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006592 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006593 goto end;
6594 }
6595
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006596 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006597 len -= sz;
6598 ret += sz;
6599 blk = htx_remove_blk(htx, blk);
6600 }
6601
6602end:
6603 flt_update_offsets(filter, msg->chn, -ret);
6604 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6605 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6606 * to loose the EOM flag if the message is empty.
6607 */
6608}
6609
6610/* Copies input data found in an HTTP message. Unlike the channel function used
6611 * to duplicate raw data, this one can only be called inside a filter, from
6612 * http_payload callback. So it cannot yield. An exception is returned if it is
6613 * called from another callback. If nothing was copied, a nil value is pushed on
6614 * the stack.
6615 */
6616__LJMP static int hlua_http_msg_get_body(lua_State *L)
6617{
6618 struct http_msg *msg;
6619 struct filter *filter;
6620 size_t output, input;
6621 int offset, len;
6622
6623 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6624 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6625 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6626
6627 if (msg->msg_state < HTTP_MSG_DATA)
6628 WILL_LJMP(lua_error(L));
6629
6630 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6631 if (!filter || !hlua_filter_from_payload(filter))
6632 WILL_LJMP(lua_error(L));
6633
6634 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6635 lua_pushnil(L);
6636 return 1;
6637 }
6638
6639 offset = output;
6640 if (lua_gettop(L) > 1) {
6641 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6642 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006643 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006644 offset += output;
6645 if (offset < output || offset > input + output) {
6646 lua_pushfstring(L, "offset out of range.");
6647 WILL_LJMP(lua_error(L));
6648 }
6649 }
6650 len = output + input - offset;
6651 if (lua_gettop(L) == 3) {
6652 len = MAY_LJMP(luaL_checkinteger(L, 3));
6653 if (!len)
6654 goto dup;
6655 if (len == -1)
6656 len = global.tune.bufsize;
6657 if (len < 0) {
6658 lua_pushfstring(L, "length out of range.");
6659 WILL_LJMP(lua_error(L));
6660 }
6661 }
6662
6663 dup:
6664 _hlua_http_msg_dup(msg, L, offset, len);
6665 return 1;
6666}
6667
6668/* Appends a string to the HTTP message, after all existing DATA blocks but
6669 * before the trailers, if any. It returns the amount of data written or -1 if
6670 * nothing was copied. Unlike the channel function used to append data, this one
6671 * can only be called inside a filter, from http_payload callback. So it cannot
6672 * yield. An exception is returned if it is called from another callback.
6673 */
6674__LJMP static int hlua_http_msg_append(lua_State *L)
6675{
6676 struct http_msg *msg;
6677 struct filter *filter;
6678 const char *str;
6679 size_t offset, len, sz;
6680 int ret;
6681
6682 MAY_LJMP(check_args(L, 2, "append"));
6683 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6684
6685 if (msg->msg_state < HTTP_MSG_DATA)
6686 WILL_LJMP(lua_error(L));
6687
6688 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6689 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6690 if (!filter || !hlua_filter_from_payload(filter))
6691 WILL_LJMP(lua_error(L));
6692
6693 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6694 lua_pushinteger(L, ret);
6695 return 1;
6696}
6697
6698/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6699 * returns the amount of data written or -1 if nothing was copied. Unlike the
6700 * channel function used to prepend data, this one can only be called inside a
6701 * filter, from http_payload callback. So it cannot yield. An exception is
6702 * returned if it is called from another callback.
6703 */
6704__LJMP static int hlua_http_msg_prepend(lua_State *L)
6705{
6706 struct http_msg *msg;
6707 struct filter *filter;
6708 const char *str;
6709 size_t offset, len, sz;
6710 int ret;
6711
6712 MAY_LJMP(check_args(L, 2, "prepend"));
6713 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006714
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 if (msg->msg_state < HTTP_MSG_DATA)
6716 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006717
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006718 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6719 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6720 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006721 WILL_LJMP(lua_error(L));
6722
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006723 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6724 lua_pushinteger(L, ret);
6725 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006726}
6727
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006728/* Inserts a string to the HTTP message at a given offset. By default the string
6729 * is appended at the end of DATA blocks. It returns the amount of data written
6730 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6731 * this one can only be called inside a filter, from http_payload callback. So
6732 * it cannot yield. An exception is returned if it is called from another
6733 * callback.
6734 */
6735__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006736{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006737 struct http_msg *msg;
6738 struct filter *filter;
6739 const char *str;
6740 size_t input, output, sz;
6741 int offset;
6742 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006743
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006744 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6745 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006747
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006748 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006749 WILL_LJMP(lua_error(L));
6750
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006751 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006752 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006753 if (!filter || !hlua_filter_from_payload(filter))
6754 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006755
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006756 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006757 if (lua_gettop(L) > 2) {
6758 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6759 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006760 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006761 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006762 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006763 lua_pushfstring(L, "offset out of range.");
6764 WILL_LJMP(lua_error(L));
6765 }
6766 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006767
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006768 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6769 lua_pushinteger(L, ret);
6770 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006771}
6772
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006773/* Removes a given amount of data from the HTTP message at a given offset. By
6774 * default all DATA blocks are removed. It returns the amount of data
6775 * removed. Unlike the channel function used to remove data, this one can only
6776 * be called inside a filter, from http_payload callback. So it cannot yield. An
6777 * exception is returned if it is called from another callback.
6778 */
6779__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006780{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006781 struct http_msg *msg;
6782 struct filter *filter;
6783 size_t input, output;
6784 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006785
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006786 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006787 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006788 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006789
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006790 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006791 WILL_LJMP(lua_error(L));
6792
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006793 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006794 if (!filter || !hlua_filter_from_payload(filter))
6795 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006796
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006797 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006798 if (lua_gettop(L) > 1) {
6799 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006800 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006801 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006802 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006803 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006804 lua_pushfstring(L, "offset out of range.");
6805 WILL_LJMP(lua_error(L));
6806 }
6807 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006808
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006810 if (lua_gettop(L) == 3) {
6811 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006812 if (!len)
6813 goto end;
6814 if (len == -1)
6815 len = output + input - offset;
6816 if (len < 0 || offset + len > output + input) {
6817 lua_pushfstring(L, "length out of range.");
6818 WILL_LJMP(lua_error(L));
6819 }
6820 }
6821
6822 _hlua_http_msg_delete(msg, filter, offset, len);
6823
6824 end:
6825 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006826 return 1;
6827}
6828
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006829/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006830 * all remaining data are removed, accordingly to the filter context. It returns
6831 * the amount of data written or -1 if nothing was copied. Unlike the channel
6832 * function used to replace data, this one can only be called inside a filter,
6833 * from http_payload callback. So it cannot yield. An exception is returned if
6834 * it is called from another callback.
6835 */
6836__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006837{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006838 struct http_msg *msg;
6839 struct filter *filter;
6840 struct htx *htx;
6841 const char *str;
6842 size_t input, output, sz;
6843 int offset, len;
6844 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006845
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006846 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6847 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6848 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6849
6850 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006851 WILL_LJMP(lua_error(L));
6852
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006853 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6854 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6855 if (!filter || !hlua_filter_from_payload(filter))
6856 WILL_LJMP(lua_error(L));
6857
6858 offset = output;
6859 if (lua_gettop(L) > 2) {
6860 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6861 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006862 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006863 offset += output;
6864 if (offset < output || offset > input + output) {
6865 lua_pushfstring(L, "offset out of range.");
6866 WILL_LJMP(lua_error(L));
6867 }
6868 }
6869
6870 len = output + input - offset;
6871 if (lua_gettop(L) == 4) {
6872 len = MAY_LJMP(luaL_checkinteger(L, 4));
6873 if (!len)
6874 goto set;
6875 if (len == -1)
6876 len = output + input - offset;
6877 if (len < 0 || offset + len > output + input) {
6878 lua_pushfstring(L, "length out of range.");
6879 WILL_LJMP(lua_error(L));
6880 }
6881 }
6882
6883 set:
6884 /* Be sure we can copied the string once input data will be removed. */
6885 htx = htx_from_buf(&msg->chn->buf);
6886 if (sz > htx_free_data_space(htx) + len)
6887 lua_pushinteger(L, -1);
6888 else {
6889 _hlua_http_msg_delete(msg, filter, offset, len);
6890 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6891 lua_pushinteger(L, ret);
6892 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006893 return 1;
6894}
6895
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006896/* Prepends data into an HTTP message and forward it, from the filter point of
6897 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6898 * the channel function used to send data, this one can only be called inside a
6899 * filter, from http_payload callback. So it cannot yield. An exception is
6900 * returned if it is called from another callback.
6901 */
6902__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006903{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006904 struct http_msg *msg;
6905 struct filter *filter;
6906 struct htx *htx;
6907 const char *str;
6908 size_t offset, len, sz;
6909 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006910
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006911 MAY_LJMP(check_args(L, 2, "send"));
6912 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6913
6914 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006915 WILL_LJMP(lua_error(L));
6916
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006917 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6918 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6919 if (!filter || !hlua_filter_from_payload(filter))
6920 WILL_LJMP(lua_error(L));
6921
6922 /* Return an error if the channel's output is closed */
6923 if (unlikely(channel_output_closed(msg->chn))) {
6924 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006925 return 1;
6926 }
6927
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006928 htx = htx_from_buf(&msg->chn->buf);
6929 if (sz > htx_free_data_space(htx)) {
6930 lua_pushinteger(L, -1);
6931 return 1;
6932 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006933
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006934 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6935 if (ret > 0) {
6936 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6937
6938 FLT_OFF(filter, msg->chn) += ret;
6939 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6940 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6941 }
6942
6943 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006944 return 1;
6945}
6946
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006947/* Forwards a given amount of bytes. It return -1 if the channel's output is
6948 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6949 * channel function used to forward data, this one can only be called inside a
6950 * filter, from http_payload callback. So it cannot yield. An exception is
6951 * returned if it is called from another callback. All other functions deal with
6952 * DATA block, this one not.
6953*/
6954__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006955{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006956 struct http_msg *msg;
6957 struct filter *filter;
6958 size_t offset, len;
6959 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006960
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006961 MAY_LJMP(check_args(L, 2, "forward"));
6962 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6963
6964 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006965 WILL_LJMP(lua_error(L));
6966
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006967 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6968 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6969 if (!filter || !hlua_filter_from_payload(filter))
6970 WILL_LJMP(lua_error(L));
6971
6972 /* Nothing to do, just return */
6973 if (!fwd)
6974 goto end;
6975
6976 /* Return an error if the channel's output is closed */
6977 if (unlikely(channel_output_closed(msg->chn))) {
6978 ret = -1;
6979 goto end;
6980 }
6981
6982 ret = fwd;
6983 if (ret > len)
6984 ret = len;
6985
6986 if (ret) {
6987 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6988
6989 FLT_OFF(filter, msg->chn) += ret;
6990 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6991 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6992 }
6993
6994 end:
6995 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006996 return 1;
6997}
6998
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006999/* Set EOM flag on the HTX message.
7000 *
7001 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7002 * really know how to do without this feature.
7003 */
7004__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007005{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007006 struct http_msg *msg;
7007 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007008
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007009 MAY_LJMP(check_args(L, 1, "set_eom"));
7010 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7011 htx = htxbuf(&msg->chn->buf);
7012 htx->flags |= HTX_FL_EOM;
7013 return 0;
7014}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007015
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007016/* Unset EOM flag on the HTX message.
7017 *
7018 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7019 * really know how to do without this feature.
7020 */
7021__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7022{
7023 struct http_msg *msg;
7024 struct htx *htx;
7025
7026 MAY_LJMP(check_args(L, 1, "set_eom"));
7027 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7028 htx = htxbuf(&msg->chn->buf);
7029 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007030 return 0;
7031}
7032
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007033/*
7034 *
7035 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007036 * Class HTTPClient
7037 *
7038 *
7039 */
7040__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7041{
7042 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7043}
7044
William Lallemandf77f1de2021-09-28 19:10:38 +02007045
7046/* stops the httpclient and ask it to kill itself */
7047__LJMP static int hlua_httpclient_gc(lua_State *L)
7048{
7049 struct hlua_httpclient *hlua_hc;
7050
7051 MAY_LJMP(check_args(L, 1, "__gc"));
7052
7053 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7054
William Lallemandbb581422022-10-20 10:57:28 +02007055 if (hlua_hc->hc)
7056 httpclient_stop_and_destroy(hlua_hc->hc);
7057
William Lallemandf77f1de2021-09-28 19:10:38 +02007058 hlua_hc->hc = NULL;
William Lallemand94dbfed2022-12-08 11:11:36 +01007059 LIST_DEL_INIT(&hlua_hc->by_hlua);
William Lallemandf77f1de2021-09-28 19:10:38 +02007060
7061 return 0;
7062}
7063
7064
William Lallemand3956c4e2021-09-21 16:25:15 +02007065__LJMP static int hlua_httpclient_new(lua_State *L)
7066{
7067 struct hlua_httpclient *hlua_hc;
7068 struct hlua *hlua;
7069
7070 /* Get hlua struct, or NULL if we execute from main lua state */
7071 hlua = hlua_gethlua(L);
7072 if (!hlua)
7073 return 0;
7074
7075 /* Check stack size. */
7076 if (!lua_checkstack(L, 3)) {
7077 hlua_pusherror(L, "httpclient: full stack");
7078 goto err;
7079 }
7080 /* Create the object: obj[0] = userdata. */
7081 lua_newtable(L);
7082 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7083 lua_rawseti(L, -2, 0);
7084 memset(hlua_hc, 0, sizeof(*hlua_hc));
7085
7086 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7087 if (!hlua_hc->hc)
7088 goto err;
7089
William Lallemandbb581422022-10-20 10:57:28 +02007090 LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
7091
William Lallemand3956c4e2021-09-21 16:25:15 +02007092 /* Pop a class stream metatable and affect it to the userdata. */
7093 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7094 lua_setmetatable(L, -2);
7095
7096 return 1;
7097
7098 err:
7099 WILL_LJMP(lua_error(L));
7100 return 0;
7101}
7102
7103
7104/*
7105 * Callback of the httpclient, this callback wakes the lua task up, once the
7106 * httpclient receives some data
7107 *
7108 */
7109
William Lallemandbd5739e2021-10-28 15:41:38 +02007110static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007111{
7112 struct hlua *hlua = hc->caller;
7113
7114 if (!hlua || !hlua->task)
7115 return;
7116
7117 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7118}
7119
7120/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007121 * Fill the lua stack with headers from the httpclient response
7122 * This works the same way as the hlua_http_get_headers() function
7123 */
7124__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7125{
7126 struct http_hdr *hdr;
7127
7128 lua_newtable(L);
7129
William Lallemandef574b22021-10-05 16:19:31 +02007130 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007131 struct ist n, v;
7132 int len;
7133
7134 n = hdr->n;
7135 v = hdr->v;
7136
7137 /* Check for existing entry:
7138 * assume that the table is on the top of the stack, and
7139 * push the key in the stack, the function lua_gettable()
7140 * perform the lookup.
7141 */
7142
7143 lua_pushlstring(L, n.ptr, n.len);
7144 lua_gettable(L, -2);
7145
7146 switch (lua_type(L, -1)) {
7147 case LUA_TNIL:
7148 /* Table not found, create it. */
7149 lua_pop(L, 1); /* remove the nil value. */
7150 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7151 lua_newtable(L); /* create and push empty table. */
7152 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7153 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7154 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7155 break;
7156
7157 case LUA_TTABLE:
7158 /* Entry found: push the value in the table. */
7159 len = lua_rawlen(L, -1);
7160 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7161 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7162 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7163 break;
7164
7165 default:
7166 /* Other cases are errors. */
7167 hlua_pusherror(L, "internal error during the parsing of headers.");
7168 WILL_LJMP(lua_error(L));
7169 }
7170 }
7171 return 1;
7172}
7173
7174/*
William Lallemand746e6f32021-10-06 10:57:44 +02007175 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7176 *
7177 * Caller must free the result
7178 */
7179struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7180{
7181 struct http_hdr hdrs[global.tune.max_http_hdr];
7182 struct http_hdr *result = NULL;
7183 uint32_t hdr_num = 0;
7184
7185 lua_pushnil(L);
7186 while (lua_next(L, -2) != 0) {
7187 struct ist name, value;
7188 const char *n, *v;
7189 size_t nlen, vlen;
7190
7191 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7192 /* Skip element if the key is not a string or if the value is not a table */
7193 goto next_hdr;
7194 }
7195
7196 n = lua_tolstring(L, -2, &nlen);
7197 name = ist2(n, nlen);
7198
7199 /* Loop on header's values */
7200 lua_pushnil(L);
7201 while (lua_next(L, -2)) {
7202 if (!lua_isstring(L, -1)) {
7203 /* Skip the value if it is not a string */
7204 goto next_value;
7205 }
7206
7207 v = lua_tolstring(L, -1, &vlen);
7208 value = ist2(v, vlen);
7209 name = ist2(n, nlen);
7210
7211 hdrs[hdr_num].n = istdup(name);
7212 hdrs[hdr_num].v = istdup(value);
7213
7214 hdr_num++;
7215
7216 next_value:
7217 lua_pop(L, 1);
7218 }
7219
7220 next_hdr:
7221 lua_pop(L, 1);
7222
7223 }
7224
7225 if (hdr_num) {
7226 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007227 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007228 if (!result)
7229 goto skip_headers;
7230 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7231
7232 result[hdr_num].n = IST_NULL;
7233 result[hdr_num].v = IST_NULL;
7234 }
7235
7236skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007237
7238 return result;
7239}
7240
7241
William Lallemandbd5739e2021-10-28 15:41:38 +02007242/*
7243 * For each yield, checks if there is some data in the httpclient and push them
7244 * in the lua buffer, once the httpclient finished its job, push the result on
7245 * the stack
7246 */
7247__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7248{
7249 struct buffer *tr;
7250 int res;
7251 struct hlua *hlua = hlua_gethlua(L);
7252 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7253
7254
7255 tr = get_trash_chunk();
7256
7257 res = httpclient_res_xfer(hlua_hc->hc, tr);
7258 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7259
7260 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7261
7262 luaL_pushresult(&hlua_hc->b);
7263 lua_settable(L, -3);
7264
7265 lua_pushstring(L, "status");
7266 lua_pushinteger(L, hlua_hc->hc->res.status);
7267 lua_settable(L, -3);
7268
7269
7270 lua_pushstring(L, "reason");
7271 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7272 lua_settable(L, -3);
7273
7274 lua_pushstring(L, "headers");
7275 hlua_httpclient_get_headers(L, hlua_hc);
7276 lua_settable(L, -3);
7277
7278 return 1;
7279 }
7280
7281 if (httpclient_data(hlua_hc->hc))
7282 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7283
7284 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7285
7286 return 0;
7287}
7288
7289/*
7290 * Call this when trying to stream a body during a request
7291 */
7292__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7293{
7294 struct hlua *hlua;
7295 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7296 const char *body_str = NULL;
7297 int ret;
7298 int end = 0;
7299 size_t buf_len;
7300 size_t to_send = 0;
7301
7302 hlua = hlua_gethlua(L);
7303
7304 if (!hlua || !hlua->task)
7305 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7306 "'frontend', 'backend' or 'task'"));
7307
7308 ret = lua_getfield(L, -1, "body");
7309 if (ret != LUA_TSTRING)
7310 goto rcv;
7311
7312 body_str = lua_tolstring(L, -1, &buf_len);
7313 lua_pop(L, 1);
7314
Christopher Fauletfc591292022-01-12 14:46:03 +01007315 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007316
7317 if ((hlua_hc->sent + to_send) >= buf_len)
7318 end = 1;
7319
7320 /* the end flag is always set since we are using the whole remaining size */
7321 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7322
7323 if (buf_len > hlua_hc->sent) {
7324 /* still need to process the buffer */
7325 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7326 } else {
7327 goto rcv;
7328 /* we sent the whole request buffer we can recv */
7329 }
7330 return 0;
7331
7332rcv:
7333
7334 /* we return a "res" object */
7335 lua_newtable(L);
7336
William Lallemandbd5739e2021-10-28 15:41:38 +02007337 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007338 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007339
William Lallemand933fe392021-11-04 09:45:58 +01007340 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007341 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7342
7343 return 1;
7344}
William Lallemand746e6f32021-10-06 10:57:44 +02007345
William Lallemand3956c4e2021-09-21 16:25:15 +02007346/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007347 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007348 */
7349
William Lallemanddc2cc902021-10-26 11:43:26 +02007350__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007351{
7352 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007353 struct http_hdr *hdrs = NULL;
7354 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007355 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007356 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007357 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007358 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007359 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007360
7361 hlua = hlua_gethlua(L);
7362
7363 if (!hlua || !hlua->task)
7364 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7365 "'frontend', 'backend' or 'task'"));
7366
William Lallemand746e6f32021-10-06 10:57:44 +02007367 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7368 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7369
William Lallemand4f4f2b72022-02-17 20:00:23 +01007370 hlua_hc = hlua_checkhttpclient(L, 1);
7371
William Lallemand7177a952022-03-03 15:33:12 +01007372 lua_pushnil(L); /* first key */
7373 while (lua_next(L, 2)) {
7374 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7375 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7376 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007377
William Lallemand7177a952022-03-03 15:33:12 +01007378 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7379 if (lua_type(L, -1) != LUA_TSTRING)
7380 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7381 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007382
William Lallemand7177a952022-03-03 15:33:12 +01007383 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7384 if (lua_type(L, -1) != LUA_TNUMBER)
7385 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7386 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007387
William Lallemand7177a952022-03-03 15:33:12 +01007388 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7389 if (lua_type(L, -1) != LUA_TTABLE)
7390 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7391 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007392
William Lallemand7177a952022-03-03 15:33:12 +01007393 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7394 if (lua_type(L, -1) != LUA_TSTRING)
7395 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7396 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007397
William Lallemand7177a952022-03-03 15:33:12 +01007398 } else {
7399 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7400 }
7401 /* removes 'value'; keeps 'key' for next iteration */
7402 lua_pop(L, 1);
7403 }
William Lallemanddec25c32021-10-25 19:48:37 +02007404
William Lallemand746e6f32021-10-06 10:57:44 +02007405 if (!url_str) {
7406 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7407 return 0;
7408 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007409
William Lallemand10a37362022-03-02 16:18:26 +01007410 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007411
7412 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007413 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007414
7415 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007416 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7417 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7418 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007419 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007420
William Lallemandbd5739e2021-10-28 15:41:38 +02007421 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007422 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007423 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7424 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007425
William Lallemandbd5739e2021-10-28 15:41:38 +02007426 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007427
William Lallemand746e6f32021-10-06 10:57:44 +02007428 /* free the temporary headers array */
7429 hdrs_i = hdrs;
7430 while (hdrs_i && isttest(hdrs_i->n)) {
7431 istfree(&hdrs_i->n);
7432 istfree(&hdrs_i->v);
7433 hdrs_i++;
7434 }
7435 ha_free(&hdrs);
7436
7437
William Lallemand6137a9e2021-10-26 15:01:53 +02007438 if (ret != ERR_NONE) {
7439 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7440 return 0;
7441 }
7442
William Lallemandc2d3db42022-04-26 11:46:13 +02007443 if (!httpclient_start(hlua_hc->hc))
7444 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007445
William Lallemandbd5739e2021-10-28 15:41:38 +02007446 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007447
William Lallemand3956c4e2021-09-21 16:25:15 +02007448 return 0;
7449}
7450
7451/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007452 * Sends an HTTP HEAD request and wait for a response
7453 *
7454 * httpclient:head(url, headers, payload)
7455 */
7456__LJMP static int hlua_httpclient_head(lua_State *L)
7457{
7458 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7459}
7460
7461/*
7462 * Send an HTTP GET request and wait for a response
7463 *
7464 * httpclient:get(url, headers, payload)
7465 */
7466__LJMP static int hlua_httpclient_get(lua_State *L)
7467{
7468 return hlua_httpclient_send(L, HTTP_METH_GET);
7469
7470}
7471
7472/*
7473 * Sends an HTTP PUT request and wait for a response
7474 *
7475 * httpclient:put(url, headers, payload)
7476 */
7477__LJMP static int hlua_httpclient_put(lua_State *L)
7478{
7479 return hlua_httpclient_send(L, HTTP_METH_PUT);
7480}
7481
7482/*
7483 * Send an HTTP POST request and wait for a response
7484 *
7485 * httpclient:post(url, headers, payload)
7486 */
7487__LJMP static int hlua_httpclient_post(lua_State *L)
7488{
7489 return hlua_httpclient_send(L, HTTP_METH_POST);
7490}
7491
7492
7493/*
7494 * Sends an HTTP DELETE request and wait for a response
7495 *
7496 * httpclient:delete(url, headers, payload)
7497 */
7498__LJMP static int hlua_httpclient_delete(lua_State *L)
7499{
7500 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7501}
7502
7503/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007504 *
7505 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007506 * Class TXN
7507 *
7508 *
7509 */
7510
7511/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007512 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007513 */
7514__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7515{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007516 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007517}
7518
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007519__LJMP static int hlua_set_var(lua_State *L)
7520{
7521 struct hlua_txn *htxn;
7522 const char *name;
7523 size_t len;
7524 struct sample smp;
7525
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007526 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7527 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007528
7529 /* It is useles to retrieve the stream, but this function
7530 * runs only in a stream context.
7531 */
7532 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7533 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7534
7535 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007536 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007537 hlua_lua2smp(L, 3, &smp);
7538
7539 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007540 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007541
7542 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7543 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7544 else
7545 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7546
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007547 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007548}
7549
Christopher Faulet85d79c92016-11-09 16:54:56 +01007550__LJMP static int hlua_unset_var(lua_State *L)
7551{
7552 struct hlua_txn *htxn;
7553 const char *name;
7554 size_t len;
7555 struct sample smp;
7556
7557 MAY_LJMP(check_args(L, 2, "unset_var"));
7558
7559 /* It is useles to retrieve the stream, but this function
7560 * runs only in a stream context.
7561 */
7562 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7563 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7564
7565 /* Unset the variable. */
7566 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007567 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7568 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007569}
7570
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007571__LJMP static int hlua_get_var(lua_State *L)
7572{
7573 struct hlua_txn *htxn;
7574 const char *name;
7575 size_t len;
7576 struct sample smp;
7577
7578 MAY_LJMP(check_args(L, 2, "get_var"));
7579
7580 /* It is useles to retrieve the stream, but this function
7581 * runs only in a stream context.
7582 */
7583 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7584 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7585
Willy Tarreau7560dd42016-03-10 16:28:58 +01007586 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007587 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007588 lua_pushnil(L);
7589 return 1;
7590 }
7591
7592 return hlua_smp2lua(L, &smp);
7593}
7594
Willy Tarreau59551662015-03-10 14:23:13 +01007595__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007596{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007597 struct hlua *hlua;
7598
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007599 MAY_LJMP(check_args(L, 2, "set_priv"));
7600
Willy Tarreau87b09662015-04-03 00:22:06 +02007601 /* It is useles to retrieve the stream, but this function
7602 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007603 */
7604 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007605
7606 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007607 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007608 if (!hlua)
7609 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007610
7611 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007612 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007613
7614 /* Get and store new value. */
7615 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7616 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7617
7618 return 0;
7619}
7620
Willy Tarreau59551662015-03-10 14:23:13 +01007621__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007622{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007623 struct hlua *hlua;
7624
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007625 MAY_LJMP(check_args(L, 1, "get_priv"));
7626
Willy Tarreau87b09662015-04-03 00:22:06 +02007627 /* It is useles to retrieve the stream, but this function
7628 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007629 */
7630 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007631
7632 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007633 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007634 if (!hlua) {
7635 lua_pushnil(L);
7636 return 1;
7637 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007638
7639 /* Push configuration index in the stack. */
7640 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7641
7642 return 1;
7643}
7644
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007645/* Create stack entry containing a class TXN. This function
7646 * return 0 if the stack does not contains free slots,
7647 * otherwise it returns 1.
7648 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007649static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007650{
Willy Tarreaude491382015-04-06 11:04:28 +02007651 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007652
7653 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007654 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007655 return 0;
7656
7657 /* NOTE: The allocation never fails. The failure
7658 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007659 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007660 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007661 /* Create the object: obj[0] = userdata. */
7662 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007663 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007664 lua_rawseti(L, -2, 0);
7665
Willy Tarreaude491382015-04-06 11:04:28 +02007666 htxn->s = s;
7667 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007668 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007669 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007670
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007671 /* Create the "f" field that contains a list of fetches. */
7672 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007673 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007674 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007675 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007676
7677 /* Create the "sf" field that contains a list of stringsafe fetches. */
7678 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007679 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007680 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007681 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007682
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007683 /* Create the "c" field that contains a list of converters. */
7684 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007685 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007686 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007687 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007688
7689 /* Create the "sc" field that contains a list of stringsafe converters. */
7690 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007691 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007692 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007693 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007694
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007695 /* Create the "req" field that contains the request channel object. */
7696 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007697 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007698 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007699 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007700
7701 /* Create the "res" field that contains the response channel object. */
7702 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007703 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007704 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007705 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007706
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007707 /* Creates the HTTP object is the current proxy allows http. */
7708 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007709 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007710 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007711 return 0;
7712 }
7713 else
7714 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007715 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007716
Christopher Faulet78c35472020-02-26 17:14:08 +01007717 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7718 /* HTTPMessage object are created when a lua TXN is created from
7719 * a filter context only
7720 */
7721
7722 /* Creates the HTTP-Request object is the current proxy allows http. */
7723 lua_pushstring(L, "http_req");
7724 if (p->mode == PR_MODE_HTTP) {
7725 if (!hlua_http_msg_new(L, &s->txn->req))
7726 return 0;
7727 }
7728 else
7729 lua_pushnil(L);
7730 lua_rawset(L, -3);
7731
7732 /* Creates the HTTP-Response object is the current proxy allows http. */
7733 lua_pushstring(L, "http_res");
7734 if (p->mode == PR_MODE_HTTP) {
7735 if (!hlua_http_msg_new(L, &s->txn->rsp))
7736 return 0;
7737 }
7738 else
7739 lua_pushnil(L);
7740 lua_rawset(L, -3);
7741 }
7742
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007743 /* Pop a class sesison metatable and affect it to the userdata. */
7744 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7745 lua_setmetatable(L, -2);
7746
7747 return 1;
7748}
7749
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007750__LJMP static int hlua_txn_deflog(lua_State *L)
7751{
7752 const char *msg;
7753 struct hlua_txn *htxn;
7754
7755 MAY_LJMP(check_args(L, 2, "deflog"));
7756 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7757 msg = MAY_LJMP(luaL_checkstring(L, 2));
7758
7759 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7760 return 0;
7761}
7762
7763__LJMP static int hlua_txn_log(lua_State *L)
7764{
7765 int level;
7766 const char *msg;
7767 struct hlua_txn *htxn;
7768
7769 MAY_LJMP(check_args(L, 3, "log"));
7770 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7771 level = MAY_LJMP(luaL_checkinteger(L, 2));
7772 msg = MAY_LJMP(luaL_checkstring(L, 3));
7773
7774 if (level < 0 || level >= NB_LOG_LEVELS)
7775 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7776
7777 hlua_sendlog(htxn->s->be, level, msg);
7778 return 0;
7779}
7780
7781__LJMP static int hlua_txn_log_debug(lua_State *L)
7782{
7783 const char *msg;
7784 struct hlua_txn *htxn;
7785
7786 MAY_LJMP(check_args(L, 2, "Debug"));
7787 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7788 msg = MAY_LJMP(luaL_checkstring(L, 2));
7789 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7790 return 0;
7791}
7792
7793__LJMP static int hlua_txn_log_info(lua_State *L)
7794{
7795 const char *msg;
7796 struct hlua_txn *htxn;
7797
7798 MAY_LJMP(check_args(L, 2, "Info"));
7799 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7800 msg = MAY_LJMP(luaL_checkstring(L, 2));
7801 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7802 return 0;
7803}
7804
7805__LJMP static int hlua_txn_log_warning(lua_State *L)
7806{
7807 const char *msg;
7808 struct hlua_txn *htxn;
7809
7810 MAY_LJMP(check_args(L, 2, "Warning"));
7811 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7812 msg = MAY_LJMP(luaL_checkstring(L, 2));
7813 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7814 return 0;
7815}
7816
7817__LJMP static int hlua_txn_log_alert(lua_State *L)
7818{
7819 const char *msg;
7820 struct hlua_txn *htxn;
7821
7822 MAY_LJMP(check_args(L, 2, "Alert"));
7823 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7824 msg = MAY_LJMP(luaL_checkstring(L, 2));
7825 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7826 return 0;
7827}
7828
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007829__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7830{
7831 struct hlua_txn *htxn;
7832 int ll;
7833
7834 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7835 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7836 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7837
7838 if (ll < 0 || ll > 7)
7839 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7840
7841 htxn->s->logs.level = ll;
7842 return 0;
7843}
7844
7845__LJMP static int hlua_txn_set_tos(lua_State *L)
7846{
7847 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007848 int tos;
7849
7850 MAY_LJMP(check_args(L, 2, "set_tos"));
7851 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7852 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7853
Willy Tarreau1a18b542018-12-11 16:37:42 +01007854 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007855 return 0;
7856}
7857
7858__LJMP static int hlua_txn_set_mark(lua_State *L)
7859{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007860 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007861 int mark;
7862
7863 MAY_LJMP(check_args(L, 2, "set_mark"));
7864 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7865 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7866
Lukas Tribus579e3e32019-08-11 18:03:45 +02007867 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007868 return 0;
7869}
7870
Patrick Hemmer268a7072018-05-11 12:52:31 -04007871__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7872{
7873 struct hlua_txn *htxn;
7874
7875 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7876 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7877 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7878 return 0;
7879}
7880
7881__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7882{
7883 struct hlua_txn *htxn;
7884
7885 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7886 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7887 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7888 return 0;
7889}
7890
Christopher Faulet700d9e82020-01-31 12:21:52 +01007891/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007892 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007893 * message and terminate the transaction. It returns 1 on success and 0 on
7894 * error. The Reply must be on top of the stack.
7895 */
7896__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7897{
7898 struct htx *htx;
7899 struct htx_sl *sl;
7900 struct h1m h1m;
7901 const char *status, *reason, *body;
7902 size_t status_len, reason_len, body_len;
7903 int ret, code, flags;
7904
7905 code = 200;
7906 status = "200";
7907 status_len = 3;
7908 ret = lua_getfield(L, -1, "status");
7909 if (ret == LUA_TNUMBER) {
7910 code = lua_tointeger(L, -1);
7911 status = lua_tolstring(L, -1, &status_len);
7912 }
7913 lua_pop(L, 1);
7914
7915 reason = http_get_reason(code);
7916 reason_len = strlen(reason);
7917 ret = lua_getfield(L, -1, "reason");
7918 if (ret == LUA_TSTRING)
7919 reason = lua_tolstring(L, -1, &reason_len);
7920 lua_pop(L, 1);
7921
7922 body = NULL;
7923 body_len = 0;
7924 ret = lua_getfield(L, -1, "body");
7925 if (ret == LUA_TSTRING)
7926 body = lua_tolstring(L, -1, &body_len);
7927 lua_pop(L, 1);
7928
7929 /* Prepare the response before inserting the headers */
7930 h1m_init_res(&h1m);
7931 htx = htx_from_buf(&s->res.buf);
7932 channel_htx_truncate(&s->res, htx);
7933 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7934 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7935 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7936 ist2(status, status_len), ist2(reason, reason_len));
7937 }
7938 else {
7939 flags = HTX_SL_F_IS_RESP;
7940 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7941 ist2(status, status_len), ist2(reason, reason_len));
7942 }
7943 if (!sl)
7944 goto fail;
7945 sl->info.res.status = code;
7946
7947 /* Push in the stack the "headers" entry. */
7948 ret = lua_getfield(L, -1, "headers");
7949 if (ret != LUA_TTABLE)
7950 goto skip_headers;
7951
7952 lua_pushnil(L);
7953 while (lua_next(L, -2) != 0) {
7954 struct ist name, value;
7955 const char *n, *v;
7956 size_t nlen, vlen;
7957
7958 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7959 /* Skip element if the key is not a string or if the value is not a table */
7960 goto next_hdr;
7961 }
7962
7963 n = lua_tolstring(L, -2, &nlen);
7964 name = ist2(n, nlen);
7965 if (isteqi(name, ist("content-length"))) {
7966 /* Always skip content-length header. It will be added
7967 * later with the correct len
7968 */
7969 goto next_hdr;
7970 }
7971
7972 /* Loop on header's values */
7973 lua_pushnil(L);
7974 while (lua_next(L, -2)) {
7975 if (!lua_isstring(L, -1)) {
7976 /* Skip the value if it is not a string */
7977 goto next_value;
7978 }
7979
7980 v = lua_tolstring(L, -1, &vlen);
7981 value = ist2(v, vlen);
7982
7983 if (isteqi(name, ist("transfer-encoding")))
7984 h1_parse_xfer_enc_header(&h1m, value);
7985 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7986 goto fail;
7987
7988 next_value:
7989 lua_pop(L, 1);
7990 }
7991
7992 next_hdr:
7993 lua_pop(L, 1);
7994 }
7995 skip_headers:
7996 lua_pop(L, 1);
7997
7998 /* Update h1m flags: CLEN is set if CHNK is not present */
7999 if (!(h1m.flags & H1_MF_CHNK)) {
8000 const char *clen = ultoa(body_len);
8001
8002 h1m.flags |= H1_MF_CLEN;
8003 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8004 goto fail;
8005 }
8006 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8007 h1m.flags |= H1_MF_XFER_LEN;
8008
8009 /* Update HTX start-line flags */
8010 if (h1m.flags & H1_MF_XFER_ENC)
8011 flags |= HTX_SL_F_XFER_ENC;
8012 if (h1m.flags & H1_MF_XFER_LEN) {
8013 flags |= HTX_SL_F_XFER_LEN;
8014 if (h1m.flags & H1_MF_CHNK)
8015 flags |= HTX_SL_F_CHNK;
8016 else if (h1m.flags & H1_MF_CLEN)
8017 flags |= HTX_SL_F_CLEN;
8018 if (h1m.body_len == 0)
8019 flags |= HTX_SL_F_BODYLESS;
8020 }
8021 sl->flags |= flags;
8022
8023
8024 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008025 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008026 goto fail;
8027
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008028 htx->flags |= HTX_FL_EOM;
8029
Christopher Faulet700d9e82020-01-31 12:21:52 +01008030 /* Now, forward the response and terminate the transaction */
8031 s->txn->status = code;
8032 htx_to_buf(htx, &s->res.buf);
8033 if (!http_forward_proxy_resp(s, 1))
8034 goto fail;
8035
8036 return 1;
8037
8038 fail:
8039 channel_htx_truncate(&s->res, htx);
8040 return 0;
8041}
8042
8043/* Terminate a transaction if called from a lua action. For TCP streams,
8044 * processing is just aborted. Nothing is returned to the client and all
8045 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8046 * is forwarded to the client before terminating the transaction. On success,
8047 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8048 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8049 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008050 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008051__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008052{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008053 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008054 struct stream *s;
8055 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008056
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008057 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008058
Christopher Faulet700d9e82020-01-31 12:21:52 +01008059 /* If the flags NOTERM is set, we cannot terminate the session, so we
8060 * just end the execution of the current lua code. */
8061 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008062 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008063
Christopher Faulet700d9e82020-01-31 12:21:52 +01008064 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008065 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008066 struct channel *req = &s->req;
8067 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008068
Christopher Faulet700d9e82020-01-31 12:21:52 +01008069 channel_auto_read(req);
8070 channel_abort(req);
8071 channel_auto_close(req);
8072 channel_erase(req);
8073
8074 res->wex = tick_add_ifset(now_ms, res->wto);
8075 channel_auto_read(res);
8076 channel_auto_close(res);
8077 channel_shutr_now(res);
8078
8079 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8080 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008081 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008082
Christopher Faulet700d9e82020-01-31 12:21:52 +01008083 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8084 /* No reply or invalid reply */
8085 s->txn->status = 0;
8086 http_reply_and_close(s, 0, NULL);
8087 }
8088 else {
8089 /* Remove extra args to have the reply on top of the stack */
8090 if (lua_gettop(L) > 2)
8091 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008092
Christopher Faulet700d9e82020-01-31 12:21:52 +01008093 if (!hlua_txn_forward_reply(L, s)) {
8094 if (!(s->flags & SF_ERR_MASK))
8095 s->flags |= SF_ERR_PRXCOND;
8096 lua_pushinteger(L, ACT_RET_ERR);
8097 WILL_LJMP(hlua_done(L));
8098 return 0; /* Never reached */
8099 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008100 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008101
Christopher Faulet700d9e82020-01-31 12:21:52 +01008102 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8103 if (htxn->dir == SMP_OPT_DIR_REQ) {
8104 /* let's log the request time */
8105 s->logs.tv_request = now;
8106 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008107 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008108 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008109
Christopher Faulet700d9e82020-01-31 12:21:52 +01008110 done:
8111 if (!(s->flags & SF_ERR_MASK))
8112 s->flags |= SF_ERR_LOCAL;
8113 if (!(s->flags & SF_FINST_MASK))
8114 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008115
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008116 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8117 lua_pushinteger(L, -1);
8118 else
8119 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008120 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008121 return 0;
8122}
8123
Christopher Faulet700d9e82020-01-31 12:21:52 +01008124/*
8125 *
8126 *
8127 * Class REPLY
8128 *
8129 *
8130 */
8131
8132/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8133 * free slots, the function fails and returns 0;
8134 */
8135static int hlua_txn_reply_new(lua_State *L)
8136{
8137 struct hlua_txn *htxn;
8138 const char *reason, *body = NULL;
8139 int ret, status;
8140
8141 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008142 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008143 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8144 WILL_LJMP(lua_error(L));
8145 }
8146
8147 /* Default value */
8148 status = 200;
8149 reason = http_get_reason(status);
8150
8151 if (lua_istable(L, 2)) {
8152 /* load status and reason from the table argument at index 2 */
8153 ret = lua_getfield(L, 2, "status");
8154 if (ret == LUA_TNIL)
8155 goto reason;
8156 else if (ret != LUA_TNUMBER) {
8157 /* invalid status: ignore the reason */
8158 goto body;
8159 }
8160 status = lua_tointeger(L, -1);
8161
8162 reason:
8163 lua_pop(L, 1); /* restore the stack: remove status */
8164 ret = lua_getfield(L, 2, "reason");
8165 if (ret == LUA_TSTRING)
8166 reason = lua_tostring(L, -1);
8167
8168 body:
8169 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8170 ret = lua_getfield(L, 2, "body");
8171 if (ret == LUA_TSTRING)
8172 body = lua_tostring(L, -1);
8173 lua_pop(L, 1); /* restore the stack: remove body */
8174 }
8175
8176 /* Create the Reply table */
8177 lua_newtable(L);
8178
8179 /* Add status element */
8180 lua_pushstring(L, "status");
8181 lua_pushinteger(L, status);
8182 lua_settable(L, -3);
8183
8184 /* Add reason element */
8185 reason = http_get_reason(status);
8186 lua_pushstring(L, "reason");
8187 lua_pushstring(L, reason);
8188 lua_settable(L, -3);
8189
8190 /* Add body element, nil if undefined */
8191 lua_pushstring(L, "body");
8192 if (body)
8193 lua_pushstring(L, body);
8194 else
8195 lua_pushnil(L);
8196 lua_settable(L, -3);
8197
8198 /* Add headers element */
8199 lua_pushstring(L, "headers");
8200 lua_newtable(L);
8201
8202 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8203 if (lua_istable(L, 2)) {
8204 /* load headers from the table argument at index 2. If it is a table, copy it. */
8205 ret = lua_getfield(L, 2, "headers");
8206 if (ret == LUA_TTABLE) {
8207 /* stack: [ ... <headers:table>, <table> ] */
8208 lua_pushnil(L);
8209 while (lua_next(L, -2) != 0) {
8210 /* stack: [ ... <headers:table>, <table>, k, v] */
8211 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8212 /* invalid value type, skip it */
8213 lua_pop(L, 1);
8214 continue;
8215 }
8216
8217
8218 /* Duplicate the key and swap it with the value. */
8219 lua_pushvalue(L, -2);
8220 lua_insert(L, -2);
8221 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8222
8223 lua_newtable(L);
8224 lua_insert(L, -2);
8225 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8226
8227 if (lua_isstring(L, -1)) {
8228 /* push the value in the inner table */
8229 lua_rawseti(L, -2, 1);
8230 }
8231 else { /* table */
8232 lua_pushnil(L);
8233 while (lua_next(L, -2) != 0) {
8234 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8235 if (!lua_isstring(L, -1)) {
8236 /* invalid value type, skip it*/
8237 lua_pop(L, 1);
8238 continue;
8239 }
8240 /* push the value in the inner table */
8241 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8242 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8243 }
8244 lua_pop(L, 1);
8245 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8246 }
8247
8248 /* push (k,v) on the stack in the headers table:
8249 * stack: [ ... <headers:table>, <table>, k, k, v ]
8250 */
8251 lua_settable(L, -5);
8252 /* stack: [ ... <headers:table>, <table>, k ] */
8253 }
8254 }
8255 lua_pop(L, 1);
8256 }
8257 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8258 lua_settable(L, -3);
8259 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8260
8261 /* Pop a class sesison metatable and affect it to the userdata. */
8262 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8263 lua_setmetatable(L, -2);
8264 return 1;
8265}
8266
8267/* Set the reply status code, and optionally the reason. If no reason is
8268 * provided, the default one corresponding to the status code is used.
8269 */
8270__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8271{
8272 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8273 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8274
8275 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008276 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008277
8278 if (status < 100 || status > 599) {
8279 lua_pushboolean(L, 0);
8280 return 1;
8281 }
8282 if (!reason)
8283 reason = http_get_reason(status);
8284
8285 lua_pushinteger(L, status);
8286 lua_setfield(L, 1, "status");
8287
8288 lua_pushstring(L, reason);
8289 lua_setfield(L, 1, "reason");
8290
8291 lua_pushboolean(L, 1);
8292 return 1;
8293}
8294
8295/* Add a header into the reply object. Each header name is associated to an
8296 * array of values in the "headers" table. If the header name is not found, a
8297 * new entry is created.
8298 */
8299__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8300{
8301 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8302 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8303 int ret;
8304
8305 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008306 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008307
8308 /* Push in the stack the "headers" entry. */
8309 ret = lua_getfield(L, 1, "headers");
8310 if (ret != LUA_TTABLE) {
8311 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8312 WILL_LJMP(lua_error(L));
8313 }
8314
8315 /* check if the header is already registered. If not, register it. */
8316 ret = lua_getfield(L, -1, name);
8317 if (ret == LUA_TNIL) {
8318 /* Entry not found. */
8319 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8320
8321 /* Insert the new header name in the array in the top of the stack.
8322 * It left the new array in the top of the stack.
8323 */
8324 lua_newtable(L);
8325 lua_pushstring(L, name);
8326 lua_pushvalue(L, -2);
8327 lua_settable(L, -4);
8328 }
8329 else if (ret != LUA_TTABLE) {
8330 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8331 WILL_LJMP(lua_error(L));
8332 }
8333
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008334 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008335 * the header value as new entry.
8336 */
8337 lua_pushstring(L, value);
8338 ret = lua_rawlen(L, -2);
8339 lua_rawseti(L, -2, ret + 1);
8340
8341 lua_pushboolean(L, 1);
8342 return 1;
8343}
8344
8345/* Remove all occurrences of a given header name. */
8346__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8347{
8348 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8349 int ret;
8350
8351 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008352 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008353
8354 /* Push in the stack the "headers" entry. */
8355 ret = lua_getfield(L, 1, "headers");
8356 if (ret != LUA_TTABLE) {
8357 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8358 WILL_LJMP(lua_error(L));
8359 }
8360
8361 lua_pushstring(L, name);
8362 lua_pushnil(L);
8363 lua_settable(L, -3);
8364
8365 lua_pushboolean(L, 1);
8366 return 1;
8367}
8368
8369/* Set the reply's body. Overwrite any existing entry. */
8370__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8371{
8372 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8373
8374 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008375 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008376
8377 lua_pushstring(L, payload);
8378 lua_setfield(L, 1, "body");
8379
8380 lua_pushboolean(L, 1);
8381 return 1;
8382}
8383
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008384__LJMP static int hlua_log(lua_State *L)
8385{
8386 int level;
8387 const char *msg;
8388
8389 MAY_LJMP(check_args(L, 2, "log"));
8390 level = MAY_LJMP(luaL_checkinteger(L, 1));
8391 msg = MAY_LJMP(luaL_checkstring(L, 2));
8392
8393 if (level < 0 || level >= NB_LOG_LEVELS)
8394 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8395
8396 hlua_sendlog(NULL, level, msg);
8397 return 0;
8398}
8399
8400__LJMP static int hlua_log_debug(lua_State *L)
8401{
8402 const char *msg;
8403
8404 MAY_LJMP(check_args(L, 1, "debug"));
8405 msg = MAY_LJMP(luaL_checkstring(L, 1));
8406 hlua_sendlog(NULL, LOG_DEBUG, msg);
8407 return 0;
8408}
8409
8410__LJMP static int hlua_log_info(lua_State *L)
8411{
8412 const char *msg;
8413
8414 MAY_LJMP(check_args(L, 1, "info"));
8415 msg = MAY_LJMP(luaL_checkstring(L, 1));
8416 hlua_sendlog(NULL, LOG_INFO, msg);
8417 return 0;
8418}
8419
8420__LJMP static int hlua_log_warning(lua_State *L)
8421{
8422 const char *msg;
8423
8424 MAY_LJMP(check_args(L, 1, "warning"));
8425 msg = MAY_LJMP(luaL_checkstring(L, 1));
8426 hlua_sendlog(NULL, LOG_WARNING, msg);
8427 return 0;
8428}
8429
8430__LJMP static int hlua_log_alert(lua_State *L)
8431{
8432 const char *msg;
8433
8434 MAY_LJMP(check_args(L, 1, "alert"));
8435 msg = MAY_LJMP(luaL_checkstring(L, 1));
8436 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008437 return 0;
8438}
8439
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008440__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008441{
8442 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008443 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008444 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008445 return 0;
8446}
8447
8448__LJMP static int hlua_sleep(lua_State *L)
8449{
8450 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008451 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008452
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008453 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008454
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008455 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008456 wakeup_ms = tick_add(now_ms, delay);
8457 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008458
Willy Tarreau9635e032018-10-16 17:52:55 +02008459 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008460 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008461}
8462
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008463__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008464{
8465 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008466 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008467
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008468 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008469
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008470 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008471 wakeup_ms = tick_add(now_ms, delay);
8472 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008473
Willy Tarreau9635e032018-10-16 17:52:55 +02008474 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008475 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008476}
8477
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008478/* This functionis an LUA binding. it permits to give back
8479 * the hand at the HAProxy scheduler. It is used when the
8480 * LUA processing consumes a lot of time.
8481 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008482__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008483{
8484 return 0;
8485}
8486
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008487__LJMP static int hlua_yield(lua_State *L)
8488{
Willy Tarreau9635e032018-10-16 17:52:55 +02008489 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008490 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008491}
8492
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008493/* This function change the nice of the currently executed
8494 * task. It is used set low or high priority at the current
8495 * task.
8496 */
Willy Tarreau59551662015-03-10 14:23:13 +01008497__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008498{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008499 struct hlua *hlua;
8500 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008501
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008502 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008503 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008504
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008505 /* Get hlua struct, or NULL if we execute from main lua state */
8506 hlua = hlua_gethlua(L);
8507
8508 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008509 if (!hlua || !hlua->task)
8510 return 0;
8511
8512 if (nice < -1024)
8513 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008514 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008515 nice = 1024;
8516
8517 hlua->task->nice = nice;
8518 return 0;
8519}
8520
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008521/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008522 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8523 * return an E_AGAIN signal, the emmiter of this signal must set a
8524 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008525 *
8526 * Task wrapper are longjmp safe because the only one Lua code
8527 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008528 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008529struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008531 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008532 enum hlua_exec status;
8533
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008534 if (task->tid < 0)
8535 task->tid = tid;
8536
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008537 /* If it is the first call to the task, we must initialize the
8538 * execution timeouts.
8539 */
8540 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008541 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008542
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008543 /* Execute the Lua code. */
8544 status = hlua_ctx_resume(hlua, 1);
8545
8546 switch (status) {
8547 /* finished or yield */
8548 case HLUA_E_OK:
8549 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008550 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008551 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008552 break;
8553
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008554 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008555 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008556 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008557 break;
8558
8559 /* finished with error. */
8560 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008561 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008562 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008563 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008564 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008565 break;
8566
8567 case HLUA_E_ERR:
8568 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008569 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008570 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008571 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008572 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008573 break;
8574 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008575 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008576}
8577
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008578/* This function is an LUA binding that register LUA function to be
8579 * executed after the HAProxy configuration parsing and before the
8580 * HAProxy scheduler starts. This function expect only one LUA
8581 * argument that is a function. This function returns nothing, but
8582 * throws if an error is encountered.
8583 */
8584__LJMP static int hlua_register_init(lua_State *L)
8585{
8586 struct hlua_init_function *init;
8587 int ref;
8588
8589 MAY_LJMP(check_args(L, 1, "register_init"));
8590
8591 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8592
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008593 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008594 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008595 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008596
8597 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008598 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008599 return 0;
8600}
8601
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008602/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008603 * executed in parallel of the main HAroxy activity. The task is
8604 * created and it is set in the HAProxy scheduler. It can be called
8605 * from the "init" section, "post init" or during the runtime.
8606 *
8607 * Lua prototype:
8608 *
8609 * <none> core.register_task(<function>)
8610 */
8611static int hlua_register_task(lua_State *L)
8612{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008613 struct hlua *hlua = NULL;
8614 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008615 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008616 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008617
8618 MAY_LJMP(check_args(L, 1, "register_task"));
8619
8620 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8621
Thierry Fournier75fc0292020-11-28 13:18:56 +01008622 /* Get the reference state. If the reference is NULL, L is the master
8623 * state, otherwise hlua->T is.
8624 */
8625 hlua = hlua_gethlua(L);
8626 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008627 /* we are in runtime processing */
8628 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008629 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008630 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008631 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008632
Willy Tarreaubafbe012017-11-24 17:34:44 +01008633 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008634 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008635 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008636 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008637
Thierry Fournier59f11be2020-11-29 00:37:41 +01008638 /* We are in the common lua state, execute the task anywhere,
8639 * otherwise, inherit the current thread identifier
8640 */
8641 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008642 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008643 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008644 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008645 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008646 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008647
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008648 task->context = hlua;
8649 task->process = hlua_process_task;
8650
Thierry Fournier021d9862020-11-28 23:42:03 +01008651 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008652 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008653
8654 /* Restore the function in the stack. */
8655 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8656 hlua->nargs = 0;
8657
8658 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008659 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008660
8661 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008662
8663 alloc_error:
8664 task_destroy(task);
8665 hlua_ctx_destroy(hlua);
8666 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8667 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008668}
8669
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008670/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8671 * doesn't allow "yield" functions because the HAProxy engine cannot
8672 * resume converters.
8673 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008674static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008675{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008676 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008677 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008678 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008679
Willy Tarreaube508f12016-03-10 11:47:01 +01008680 if (!stream)
8681 return 0;
8682
Willy Tarreau87b09662015-04-03 00:22:06 +02008683 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008684 * Lua context can be not initialized. This behavior
8685 * permits to save performances because a systematic
8686 * Lua initialization cause 5% performances loss.
8687 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008688 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008689 struct hlua *hlua;
8690
8691 hlua = pool_alloc(pool_head_hlua);
8692 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008693 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8694 return 0;
8695 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008696 HLUA_INIT(hlua);
8697 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008698 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008699 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8700 return 0;
8701 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008702 }
8703
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008704 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008705 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008706
8707 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008708 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008709 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8710 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008711 else
8712 error = "critical error";
8713 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008714 return 0;
8715 }
8716
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008717 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008718 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008719 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008720 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008721 return 0;
8722 }
8723
8724 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008725 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008726
8727 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008728 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008729 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008730 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008731 return 0;
8732 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008733 hlua_smp2lua(stream->hlua->T, smp);
8734 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008735
8736 /* push keywords in the stack. */
8737 if (arg_p) {
8738 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008739 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008740 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008741 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008742 return 0;
8743 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008744 hlua_arg2lua(stream->hlua->T, arg_p);
8745 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008746 }
8747 }
8748
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008749 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008750 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008751
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008752 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008753 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008754 }
8755
8756 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008757 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008758 /* finished. */
8759 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008760 /* If the stack is empty, the function fails. */
8761 if (lua_gettop(stream->hlua->T) <= 0)
8762 return 0;
8763
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008764 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008765 hlua_lua2smp(stream->hlua->T, -1, smp);
8766 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008767 return 1;
8768
8769 /* yield. */
8770 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008771 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008772 return 0;
8773
8774 /* finished with error. */
8775 case HLUA_E_ERRMSG:
8776 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008777 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008778 fcn->name, lua_tostring(stream->hlua->T, -1));
8779 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008780 return 0;
8781
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008782 case HLUA_E_ETMOUT:
8783 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8784 return 0;
8785
8786 case HLUA_E_NOMEM:
8787 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8788 return 0;
8789
8790 case HLUA_E_YIELD:
8791 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8792 return 0;
8793
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008794 case HLUA_E_ERR:
8795 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008796 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008797 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008798
8799 default:
8800 return 0;
8801 }
8802}
8803
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008804/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8805 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008806 * resume sample-fetches. This function will be called by the sample
8807 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008808 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008809static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8810 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008811{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008812 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008813 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008814 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008815 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008816
Willy Tarreaube508f12016-03-10 11:47:01 +01008817 if (!stream)
8818 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008819
Willy Tarreau87b09662015-04-03 00:22:06 +02008820 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008821 * Lua context can be not initialized. This behavior
8822 * permits to save performances because a systematic
8823 * Lua initialization cause 5% performances loss.
8824 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008825 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008826 struct hlua *hlua;
8827
8828 hlua = pool_alloc(pool_head_hlua);
8829 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008830 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8831 return 0;
8832 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008833 hlua->T = NULL;
8834 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008835 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008836 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8837 return 0;
8838 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008839 }
8840
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008841 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008842 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008843
8844 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008845 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008846 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8847 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008848 else
8849 error = "critical error";
8850 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008851 return 0;
8852 }
8853
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008854 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008855 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008856 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008857 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008858 return 0;
8859 }
8860
8861 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008862 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008863
8864 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008865 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008866 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008867 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008868 return 0;
8869 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008870 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008871
8872 /* push keywords in the stack. */
8873 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8874 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008875 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008876 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008877 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008878 return 0;
8879 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008880 hlua_arg2lua(stream->hlua->T, arg_p);
8881 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008882 }
8883
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008884 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008885 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008886
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008887 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008888 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008889 }
8890
8891 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008892 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008893 /* finished. */
8894 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008895 /* If the stack is empty, the function fails. */
8896 if (lua_gettop(stream->hlua->T) <= 0)
8897 return 0;
8898
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008899 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008900 hlua_lua2smp(stream->hlua->T, -1, smp);
8901 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008902
8903 /* Set the end of execution flag. */
8904 smp->flags &= ~SMP_F_MAY_CHANGE;
8905 return 1;
8906
8907 /* yield. */
8908 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008909 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008910 return 0;
8911
8912 /* finished with error. */
8913 case HLUA_E_ERRMSG:
8914 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008915 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008916 fcn->name, lua_tostring(stream->hlua->T, -1));
8917 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008918 return 0;
8919
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008920 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008921 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8922 return 0;
8923
8924 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008925 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8926 return 0;
8927
8928 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008929 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8930 return 0;
8931
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008932 case HLUA_E_ERR:
8933 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008934 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008935 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008936
8937 default:
8938 return 0;
8939 }
8940}
8941
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008942/* This function is an LUA binding used for registering
8943 * "sample-conv" functions. It expects a converter name used
8944 * in the haproxy configuration file, and an LUA function.
8945 */
8946__LJMP static int hlua_register_converters(lua_State *L)
8947{
8948 struct sample_conv_kw_list *sck;
8949 const char *name;
8950 int ref;
8951 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008952 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008953 struct sample_conv *sc;
8954 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008955
8956 MAY_LJMP(check_args(L, 2, "register_converters"));
8957
8958 /* First argument : converter name. */
8959 name = MAY_LJMP(luaL_checkstring(L, 1));
8960
8961 /* Second argument : lua function. */
8962 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8963
Thierry Fournierf67442e2020-11-28 20:41:07 +01008964 /* Check if the converter is already registered */
8965 trash = get_trash_chunk();
8966 chunk_printf(trash, "lua.%s", name);
8967 sc = find_sample_conv(trash->area, trash->data);
8968 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008969 fcn = sc->private;
8970 if (fcn->function_ref[hlua_state_id] != -1) {
8971 ha_warning("Trying to register converter 'lua.%s' more than once. "
8972 "This will become a hard error in version 2.5.\n", name);
8973 }
8974 fcn->function_ref[hlua_state_id] = ref;
8975 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008976 }
8977
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008978 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008979 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008980 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008981 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008982 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008983 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008984 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008985
8986 /* Fill fcn. */
8987 fcn->name = strdup(name);
8988 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008989 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008990 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008991
8992 /* List head */
8993 sck->list.n = sck->list.p = NULL;
8994
8995 /* converter keyword. */
8996 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008997 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008998 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008999 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009000
9001 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9002 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009003 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 +01009004 sck->kw[0].val_args = NULL;
9005 sck->kw[0].in_type = SMP_T_STR;
9006 sck->kw[0].out_type = SMP_T_STR;
9007 sck->kw[0].private = fcn;
9008
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009009 /* Register this new converter */
9010 sample_register_convs(sck);
9011
9012 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009013
9014 alloc_error:
9015 release_hlua_function(fcn);
9016 ha_free(&sck);
9017 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9018 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009019}
9020
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009021/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009022 * "sample-fetch" functions. It expects a converter name used
9023 * in the haproxy configuration file, and an LUA function.
9024 */
9025__LJMP static int hlua_register_fetches(lua_State *L)
9026{
9027 const char *name;
9028 int ref;
9029 int len;
9030 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009031 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009032 struct sample_fetch *sf;
9033 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009034
9035 MAY_LJMP(check_args(L, 2, "register_fetches"));
9036
9037 /* First argument : sample-fetch name. */
9038 name = MAY_LJMP(luaL_checkstring(L, 1));
9039
9040 /* Second argument : lua function. */
9041 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9042
Thierry Fournierf67442e2020-11-28 20:41:07 +01009043 /* Check if the sample-fetch is already registered */
9044 trash = get_trash_chunk();
9045 chunk_printf(trash, "lua.%s", name);
9046 sf = find_sample_fetch(trash->area, trash->data);
9047 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009048 fcn = sf->private;
9049 if (fcn->function_ref[hlua_state_id] != -1) {
9050 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9051 "This will become a hard error in version 2.5.\n", name);
9052 }
9053 fcn->function_ref[hlua_state_id] = ref;
9054 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009055 }
9056
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009057 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009058 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009059 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009060 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009061 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009062 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009063 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009064
9065 /* Fill fcn. */
9066 fcn->name = strdup(name);
9067 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009068 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009069 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009070
9071 /* List head */
9072 sfk->list.n = sfk->list.p = NULL;
9073
9074 /* sample-fetch keyword. */
9075 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009076 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009077 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009078 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009079
9080 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9081 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009082 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 +01009083 sfk->kw[0].val_args = NULL;
9084 sfk->kw[0].out_type = SMP_T_STR;
9085 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9086 sfk->kw[0].val = 0;
9087 sfk->kw[0].private = fcn;
9088
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009089 /* Register this new fetch. */
9090 sample_register_fetches(sfk);
9091
9092 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009093
9094 alloc_error:
9095 release_hlua_function(fcn);
9096 ha_free(&sfk);
9097 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9098 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009099}
9100
Christopher Faulet501465d2020-02-26 14:54:16 +01009101/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009102 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009103__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009104{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009105 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009106 unsigned int delay;
9107 unsigned int wakeup_ms;
9108
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009109 /* Get hlua struct, or NULL if we execute from main lua state */
9110 hlua = hlua_gethlua(L);
9111 if (!hlua) {
9112 return 0;
9113 }
9114
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009115 MAY_LJMP(check_args(L, 1, "wake_time"));
9116
9117 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9118 wakeup_ms = tick_add(now_ms, delay);
9119 hlua->wake_time = wakeup_ms;
9120 return 0;
9121}
9122
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009123/* This function is a wrapper to execute each LUA function declared as an action
9124 * wrapper during the initialisation period. This function may return any
9125 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9126 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9127 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009128 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009129static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009130 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009131{
9132 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009133 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009134 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009135 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009136
9137 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009138 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9139 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9140 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9141 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009142 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009143 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009144 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009145 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009146
Willy Tarreau87b09662015-04-03 00:22:06 +02009147 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009148 * Lua context can be not initialized. This behavior
9149 * permits to save performances because a systematic
9150 * Lua initialization cause 5% performances loss.
9151 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009152 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009153 struct hlua *hlua;
9154
9155 hlua = pool_alloc(pool_head_hlua);
9156 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009157 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009158 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009159 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009160 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009161 HLUA_INIT(hlua);
9162 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009163 if (!hlua_ctx_init(s->hlua, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn), s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009164 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009165 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009166 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009167 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009168 }
9169
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009170 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009171 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009172
9173 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009174 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009175 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9176 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009177 else
9178 error = "critical error";
9179 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009180 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009181 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009182 }
9183
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009184 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009185 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009186 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009187 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009188 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009189 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009190 }
9191
9192 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009193 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009194
Willy Tarreau87b09662015-04-03 00:22:06 +02009195 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009196 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009197 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009198 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009199 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009200 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009201 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009202 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009203
9204 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009205 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009206 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009207 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009208 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009209 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009210 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009211 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009212 lua_pushstring(s->hlua->T, *arg);
9213 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009214 }
9215
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009216 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009217 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009218
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009219 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009220 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009221 }
9222
9223 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009224 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009225 /* finished. */
9226 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009227 /* Catch the return value */
9228 if (lua_gettop(s->hlua->T) > 0)
9229 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009230
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009231 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009232 if (act_ret == ACT_RET_YIELD) {
9233 if (flags & ACT_OPT_FINAL)
9234 goto err_yield;
9235
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009236 if (dir == SMP_OPT_DIR_REQ)
9237 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9238 s->hlua->wake_time);
9239 else
9240 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9241 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009242 }
9243 goto end;
9244
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009245 /* yield. */
9246 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009247 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009248 if (dir == SMP_OPT_DIR_REQ)
9249 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9250 s->hlua->wake_time);
9251 else
9252 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9253 s->hlua->wake_time);
9254
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009255 /* Some actions can be wake up when a "write" event
9256 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009257 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009258 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009259 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009260 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009261 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009262 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009263 act_ret = ACT_RET_YIELD;
9264 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009265
9266 /* finished with error. */
9267 case HLUA_E_ERRMSG:
9268 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009269 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009270 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009271 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009272 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009273
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009274 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009275 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009276 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009277
9278 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009279 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009280 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009281
9282 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009283 err_yield:
9284 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009285 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009286 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009287 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009288
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009289 case HLUA_E_ERR:
9290 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009291 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009292 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009293
9294 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009295 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009296 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009297
9298 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009299 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009300 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009301 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009302}
9303
Willy Tarreau144f84a2021-03-02 16:09:26 +01009304struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009305{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009306 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009307
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009308 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009309 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009310 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009311}
9312
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009313static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009314{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009315 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009316 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009317 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009318 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009319 struct task *task;
9320 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009321 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009322
Willy Tarreaubafbe012017-11-24 17:34:44 +01009323 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009324 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009325 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009326 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009327 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009328 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009329 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009330 tcp_ctx->hlua = hlua;
9331 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009332
9333 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009334 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009335 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009336 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009337 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009338 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009339 }
9340 task->nice = 0;
9341 task->context = ctx;
9342 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009343 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009344
9345 /* In the execution wrappers linked with a stream, the
9346 * Lua context can be not initialized. This behavior
9347 * permits to save performances because a systematic
9348 * Lua initialization cause 5% performances loss.
9349 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009350 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009351 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009352 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009353 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009354 }
9355
9356 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009357 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358
9359 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009360 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009361 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9362 error = lua_tostring(hlua->T, -1);
9363 else
9364 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009365 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009366 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009367 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009368 }
9369
9370 /* Check stack available size. */
9371 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009372 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009373 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009374 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009375 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009376 }
9377
9378 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009379 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009380
9381 /* Create and and push object stream in the stack. */
9382 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009383 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009384 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009385 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009386 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387 }
9388 hlua->nargs = 1;
9389
9390 /* push keywords in the stack. */
9391 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9392 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009393 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009394 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009395 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009396 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009397 }
9398 lua_pushstring(hlua->T, *arg);
9399 hlua->nargs++;
9400 }
9401
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009402 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009403
9404 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009405 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009406 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009407
Christopher Fauletc9929382022-05-12 11:52:27 +02009408 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009409}
9410
Willy Tarreau60409db2019-08-21 14:14:50 +02009411void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009412{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009413 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009414 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009415 struct stream *strm = __sc_strm(sc);
9416 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009417 struct act_rule *rule = ctx->rule;
9418 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009419 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009420
9421 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009422 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009423 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009424 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009425 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009426 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009427
9428 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009429 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009430 return;
9431
9432 /* Execute the function. */
9433 switch (hlua_ctx_resume(hlua, 1)) {
9434 /* finished. */
9435 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009436 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009437
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009438 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009439 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01009440 res->flags |= CF_READ_EVENT;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009441 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009442 return;
9443
9444 /* yield. */
9445 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009446 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009447 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009448 return;
9449
9450 /* finished with error. */
9451 case HLUA_E_ERRMSG:
9452 /* Display log. */
9453 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009454 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009455 lua_pop(hlua->T, 1);
9456 goto error;
9457
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009458 case HLUA_E_ETMOUT:
9459 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009460 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009461 goto error;
9462
9463 case HLUA_E_NOMEM:
9464 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009465 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009466 goto error;
9467
9468 case HLUA_E_YIELD: /* unexpected */
9469 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009470 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009471 goto error;
9472
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009473 case HLUA_E_ERR:
9474 /* Display log. */
9475 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009476 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009477 goto error;
9478
9479 default:
9480 goto error;
9481 }
9482
9483error:
9484
9485 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009486 sc_shutw(sc);
9487 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009488 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009489}
9490
9491static void hlua_applet_tcp_release(struct appctx *ctx)
9492{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009493 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9494
9495 task_destroy(tcp_ctx->task);
9496 tcp_ctx->task = NULL;
9497 hlua_ctx_destroy(tcp_ctx->hlua);
9498 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009499}
9500
Christopher Fauletc9929382022-05-12 11:52:27 +02009501/* The function returns 0 if the initialisation is complete or -1 if
9502 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009503 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009504static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009505{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009506 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009507 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009508 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009509 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009510 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009511 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009512 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009513 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009514
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009515 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009516 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009517 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009518 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009519 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009520 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009521 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009522 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009523 http_ctx->hlua = hlua;
9524 http_ctx->left_bytes = -1;
9525 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009526
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009527 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009528 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009529
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009530 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009531 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009532 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009533 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009534 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009535 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009536 }
9537 task->nice = 0;
9538 task->context = ctx;
9539 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009540 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009541
9542 /* In the execution wrappers linked with a stream, the
9543 * Lua context can be not initialized. This behavior
9544 * permits to save performances because a systematic
9545 * Lua initialization cause 5% performances loss.
9546 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009547 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009548 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009549 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009550 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009551 }
9552
9553 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009554 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009555
9556 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009557 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009558 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9559 error = lua_tostring(hlua->T, -1);
9560 else
9561 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009562 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009563 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009564 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009565 }
9566
9567 /* Check stack available size. */
9568 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009569 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009570 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009571 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009572 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009573 }
9574
9575 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009576 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009577
9578 /* Create and and push object stream in the stack. */
9579 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009580 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009581 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009582 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009583 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009584 }
9585 hlua->nargs = 1;
9586
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009587 /* push keywords in the stack. */
9588 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9589 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009590 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009591 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009592 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009593 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009594 }
9595 lua_pushstring(hlua->T, *arg);
9596 hlua->nargs++;
9597 }
9598
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009599 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009600
9601 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009602 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009603
Christopher Fauletc9929382022-05-12 11:52:27 +02009604 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009605}
9606
Willy Tarreau60409db2019-08-21 14:14:50 +02009607void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009608{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009609 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009610 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009611 struct stream *strm = __sc_strm(sc);
9612 struct channel *req = sc_oc(sc);
9613 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009614 struct act_rule *rule = ctx->rule;
9615 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009616 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009617 struct htx *req_htx, *res_htx;
9618
9619 res_htx = htx_from_buf(&res->buf);
9620
9621 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009622 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009623 goto out;
9624
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009625 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009626 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009627 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009628 goto out;
9629 }
9630 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009631 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009632 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009633
9634 /* Set the currently running flag. */
9635 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009636 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009637 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009638 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009639 goto out;
9640 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009641 }
9642
9643 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009644 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009645
9646 /* Execute the function. */
9647 switch (hlua_ctx_resume(hlua, 1)) {
9648 /* finished. */
9649 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009650 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009651 break;
9652
9653 /* yield. */
9654 case HLUA_E_AGAIN:
9655 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009656 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009657 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009658
9659 /* finished with error. */
9660 case HLUA_E_ERRMSG:
9661 /* Display log. */
9662 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009663 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009664 lua_pop(hlua->T, 1);
9665 goto error;
9666
9667 case HLUA_E_ETMOUT:
9668 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009669 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009670 goto error;
9671
9672 case HLUA_E_NOMEM:
9673 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009674 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009675 goto error;
9676
9677 case HLUA_E_YIELD: /* unexpected */
9678 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009679 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009680 goto error;
9681
9682 case HLUA_E_ERR:
9683 /* Display log. */
9684 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009685 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009686 goto error;
9687
9688 default:
9689 goto error;
9690 }
9691 }
9692
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009693 if (http_ctx->flags & APPLET_DONE) {
9694 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009695 goto done;
9696
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009697 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009698 goto error;
9699
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009700 /* no more data are expected. If the response buffer is empty
9701 * for a chunked message, be sure to add something (EOT block in
9702 * this case) to have something to send. It is important to be
9703 * sure the EOM flags will be handled by the endpoint.
9704 */
9705 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9706 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009707 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009708 goto out;
9709 }
9710 channel_add_input(res, 1);
9711 }
9712
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009713 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009714 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009715 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009716 strm->txn->status = http_ctx->status;
9717 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009718 }
9719
9720 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009721 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009722 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet6e1bbc42022-12-12 08:08:15 +01009723 res->flags |= CF_READ_EVENT;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009724 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009725 }
9726
9727 /* eat the whole request */
9728 if (co_data(req)) {
9729 req_htx = htx_from_buf(&req->buf);
9730 co_htx_skip(req, req_htx, co_data(req));
9731 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009732 }
9733 }
9734
9735 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009736 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009737 return;
9738
9739 error:
9740
9741 /* If we are in HTTP mode, and we are not send any
9742 * data, return a 500 server error in best effort:
9743 * if there is no room available in the buffer,
9744 * just close the connection.
9745 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009746 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009747 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009748
9749 channel_erase(res);
9750 res->buf.data = b_data(err);
9751 memcpy(res->buf.area, b_head(err), b_data(err));
9752 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009753 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009754 }
9755 if (!(strm->flags & SF_ERR_MASK))
9756 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009757 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009758 goto done;
9759}
9760
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009761static void hlua_applet_http_release(struct appctx *ctx)
9762{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009763 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9764
9765 task_destroy(http_ctx->task);
9766 http_ctx->task = NULL;
9767 hlua_ctx_destroy(http_ctx->hlua);
9768 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009769}
9770
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009771/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009772 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009773 *
9774 * This function can fail with an abort() due to an Lua critical error.
9775 * We are in the configuration parsing process of HAProxy, this abort() is
9776 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009777 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009778static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9779 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009780{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009781 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009782 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009783
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009784 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009785 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009786 if (!rule->arg.hlua_rule) {
9787 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009788 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009789 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009790
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009791 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009792 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9793 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009794 if (!rule->arg.hlua_rule->args) {
9795 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009796 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009797 }
9798
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009799 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009800 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009801
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009802 /* Expect some arguments */
9803 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009804 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009805 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009806 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009807 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009808 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009809 if (!rule->arg.hlua_rule->args[i]) {
9810 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009811 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009812 }
9813 (*cur_arg)++;
9814 }
9815 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009816
Thierry FOURNIER42148732015-09-02 17:17:33 +02009817 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009818 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009819 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009820
9821 error:
9822 if (rule->arg.hlua_rule) {
9823 if (rule->arg.hlua_rule->args) {
9824 for (i = 0; i < fcn->nargs; i++)
9825 ha_free(&rule->arg.hlua_rule->args[i]);
9826 ha_free(&rule->arg.hlua_rule->args);
9827 }
9828 ha_free(&rule->arg.hlua_rule);
9829 }
9830 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009831}
9832
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009833static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9834 struct act_rule *rule, char **err)
9835{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009836 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009837
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009838 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009839 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009840 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009841 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009842 * the call of this analyzer.
9843 */
9844 if (rule->from != ACT_F_HTTP_REQ) {
9845 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9846 return ACT_RET_PRS_ERR;
9847 }
9848
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009849 /* Memory for the rule. */
9850 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9851 if (!rule->arg.hlua_rule) {
9852 memprintf(err, "out of memory error");
9853 return ACT_RET_PRS_ERR;
9854 }
9855
9856 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009857 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009858
9859 /* TODO: later accept arguments. */
9860 rule->arg.hlua_rule->args = NULL;
9861
9862 /* Add applet pointer in the rule. */
9863 rule->applet.obj_type = OBJ_TYPE_APPLET;
9864 rule->applet.name = fcn->name;
9865 rule->applet.init = hlua_applet_http_init;
9866 rule->applet.fct = hlua_applet_http_fct;
9867 rule->applet.release = hlua_applet_http_release;
9868 rule->applet.timeout = hlua_timeout_applet;
9869
9870 return ACT_RET_PRS_OK;
9871}
9872
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009873/* This function is an LUA binding used for registering
9874 * "sample-conv" functions. It expects a converter name used
9875 * in the haproxy configuration file, and an LUA function.
9876 */
9877__LJMP static int hlua_register_action(lua_State *L)
9878{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009879 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009880 const char *name;
9881 int ref;
9882 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009883 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009884 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009885 struct buffer *trash;
9886 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009887
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009888 /* Initialise the number of expected arguments at 0. */
9889 nargs = 0;
9890
9891 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9892 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009893
9894 /* First argument : converter name. */
9895 name = MAY_LJMP(luaL_checkstring(L, 1));
9896
9897 /* Second argument : environment. */
9898 if (lua_type(L, 2) != LUA_TTABLE)
9899 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9900
9901 /* Third argument : lua function. */
9902 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9903
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009904 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009905 if (lua_gettop(L) >= 4)
9906 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9907
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009908 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009909 lua_pushnil(L);
9910 while (lua_next(L, 2) != 0) {
9911 if (lua_type(L, -1) != LUA_TSTRING)
9912 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9913
Thierry Fournierf67442e2020-11-28 20:41:07 +01009914 /* Check if action exists */
9915 trash = get_trash_chunk();
9916 chunk_printf(trash, "lua.%s", name);
9917 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9918 akw = tcp_req_cont_action(trash->area);
9919 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9920 akw = tcp_res_cont_action(trash->area);
9921 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9922 akw = action_http_req_custom(trash->area);
9923 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9924 akw = action_http_res_custom(trash->area);
9925 } else {
9926 akw = NULL;
9927 }
9928 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009929 fcn = akw->private;
9930 if (fcn->function_ref[hlua_state_id] != -1) {
9931 ha_warning("Trying to register action 'lua.%s' more than once. "
9932 "This will become a hard error in version 2.5.\n", name);
9933 }
9934 fcn->function_ref[hlua_state_id] = ref;
9935
9936 /* pop the environment string. */
9937 lua_pop(L, 1);
9938 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009939 }
9940
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009941 /* Check required environment. Only accepted "http" or "tcp". */
9942 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009943 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009944 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009945 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009946 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009947 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009948 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009949
9950 /* Fill fcn. */
9951 fcn->name = strdup(name);
9952 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009953 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009954 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009955
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009956 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009957 fcn->nargs = nargs;
9958
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009959 /* List head */
9960 akl->list.n = akl->list.p = NULL;
9961
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009962 /* action keyword. */
9963 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009964 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009965 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009966 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009967
9968 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9969
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009970 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009971 akl->kw[0].private = fcn;
9972 akl->kw[0].parse = action_register_lua;
9973
9974 /* select the action registering point. */
9975 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9976 tcp_req_cont_keywords_register(akl);
9977 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9978 tcp_res_cont_keywords_register(akl);
9979 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9980 http_req_keywords_register(akl);
9981 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9982 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009983 else {
9984 release_hlua_function(fcn);
9985 if (akl)
9986 ha_free((char **)&(akl->kw[0].kw));
9987 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009988 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009989 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9990 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009991 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009992
9993 /* pop the environment string. */
9994 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009995
9996 /* reset for next loop */
9997 akl = NULL;
9998 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009999 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010000 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010001
10002 alloc_error:
10003 release_hlua_function(fcn);
10004 ha_free(&akl);
10005 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10006 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010007}
10008
10009static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10010 struct act_rule *rule, char **err)
10011{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010012 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010013
Christopher Faulet280f85b2019-07-15 15:02:04 +020010014 if (px->mode == PR_MODE_HTTP) {
10015 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010016 return ACT_RET_PRS_ERR;
10017 }
10018
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010019 /* Memory for the rule. */
10020 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10021 if (!rule->arg.hlua_rule) {
10022 memprintf(err, "out of memory error");
10023 return ACT_RET_PRS_ERR;
10024 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010025
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010026 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010027 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010028
10029 /* TODO: later accept arguments. */
10030 rule->arg.hlua_rule->args = NULL;
10031
10032 /* Add applet pointer in the rule. */
10033 rule->applet.obj_type = OBJ_TYPE_APPLET;
10034 rule->applet.name = fcn->name;
10035 rule->applet.init = hlua_applet_tcp_init;
10036 rule->applet.fct = hlua_applet_tcp_fct;
10037 rule->applet.release = hlua_applet_tcp_release;
10038 rule->applet.timeout = hlua_timeout_applet;
10039
10040 return 0;
10041}
10042
10043/* This function is an LUA binding used for registering
10044 * "sample-conv" functions. It expects a converter name used
10045 * in the haproxy configuration file, and an LUA function.
10046 */
10047__LJMP static int hlua_register_service(lua_State *L)
10048{
10049 struct action_kw_list *akl;
10050 const char *name;
10051 const char *env;
10052 int ref;
10053 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010054 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010055 struct buffer *trash;
10056 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010057
10058 MAY_LJMP(check_args(L, 3, "register_service"));
10059
10060 /* First argument : converter name. */
10061 name = MAY_LJMP(luaL_checkstring(L, 1));
10062
10063 /* Second argument : environment. */
10064 env = MAY_LJMP(luaL_checkstring(L, 2));
10065
10066 /* Third argument : lua function. */
10067 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10068
Thierry Fournierf67442e2020-11-28 20:41:07 +010010069 /* Check for service already registered */
10070 trash = get_trash_chunk();
10071 chunk_printf(trash, "lua.%s", name);
10072 akw = service_find(trash->area);
10073 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010074 fcn = akw->private;
10075 if (fcn->function_ref[hlua_state_id] != -1) {
10076 ha_warning("Trying to register service 'lua.%s' more than once. "
10077 "This will become a hard error in version 2.5.\n", name);
10078 }
10079 fcn->function_ref[hlua_state_id] = ref;
10080 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010081 }
10082
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010083 /* Allocate and fill the sample fetch keyword struct. */
10084 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10085 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010086 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010087 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010088 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010089 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010090
10091 /* Fill fcn. */
10092 len = strlen("<lua.>") + strlen(name) + 1;
10093 fcn->name = calloc(1, len);
10094 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010095 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010096 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010097 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010098
10099 /* List head */
10100 akl->list.n = akl->list.p = NULL;
10101
10102 /* converter keyword. */
10103 len = strlen("lua.") + strlen(name) + 1;
10104 akl->kw[0].kw = calloc(1, len);
10105 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010106 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010107
10108 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10109
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010110 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010111 if (strcmp(env, "tcp") == 0)
10112 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010113 else if (strcmp(env, "http") == 0)
10114 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010115 else {
10116 release_hlua_function(fcn);
10117 if (akl)
10118 ha_free((char **)&(akl->kw[0].kw));
10119 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010120 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010121 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010122 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010123
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010124 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010125 akl->kw[0].private = fcn;
10126
10127 /* End of array. */
10128 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10129
10130 /* Register this new converter */
10131 service_keywords_register(akl);
10132
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010133 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010134
10135 alloc_error:
10136 release_hlua_function(fcn);
10137 ha_free(&akl);
10138 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10139 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010140}
10141
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010142/* This function initialises Lua cli handler. It copies the
10143 * arguments in the Lua stack and create channel IO objects.
10144 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010145static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010146{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010147 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010148 struct hlua *hlua;
10149 struct hlua_function *fcn;
10150 int i;
10151 const char *error;
10152
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010153 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010154 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010155
Willy Tarreaubafbe012017-11-24 17:34:44 +010010156 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010157 if (!hlua) {
10158 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010159 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010160 }
10161 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010162 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010163
10164 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010165 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010166 * applet_http. It is absolutely compatible.
10167 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010168 ctx->task = task_new_here();
10169 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010170 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010171 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010172 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010173 ctx->task->nice = 0;
10174 ctx->task->context = appctx;
10175 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010176
10177 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010178 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010179 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010180 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010181 }
10182
10183 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010184 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010185 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10186 error = lua_tostring(hlua->T, -1);
10187 else
10188 error = "critical error";
10189 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10190 goto error;
10191 }
10192
10193 /* Check stack available size. */
10194 if (!lua_checkstack(hlua->T, 2)) {
10195 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10196 goto error;
10197 }
10198
10199 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010200 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010201
10202 /* Once the arguments parsed, the CLI is like an AppletTCP,
10203 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010204 */
10205 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10206 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10207 goto error;
10208 }
10209 hlua->nargs = 1;
10210
10211 /* push keywords in the stack. */
10212 for (i = 0; *args[i]; i++) {
10213 /* Check stack available size. */
10214 if (!lua_checkstack(hlua->T, 1)) {
10215 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10216 goto error;
10217 }
10218 lua_pushstring(hlua->T, args[i]);
10219 hlua->nargs++;
10220 }
10221
10222 /* We must initialize the execution timeouts. */
10223 hlua->max_time = hlua_timeout_session;
10224
10225 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010226 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010227
10228 /* It's ok */
10229 return 0;
10230
10231 /* It's not ok. */
10232error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010233 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010234 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010235 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010236 return 1;
10237}
10238
10239static int hlua_cli_io_handler_fct(struct appctx *appctx)
10240{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010241 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010242 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010243 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010244 struct hlua_function *fcn;
10245
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010246 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010247 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010248 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010249
10250 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010251 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010252 return 1;
10253
10254 /* Execute the function. */
10255 switch (hlua_ctx_resume(hlua, 1)) {
10256
10257 /* finished. */
10258 case HLUA_E_OK:
10259 return 1;
10260
10261 /* yield. */
10262 case HLUA_E_AGAIN:
10263 /* We want write. */
10264 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010265 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010266 /* Set the timeout. */
10267 if (hlua->wake_time != TICK_ETERNITY)
10268 task_schedule(hlua->task, hlua->wake_time);
10269 return 0;
10270
10271 /* finished with error. */
10272 case HLUA_E_ERRMSG:
10273 /* Display log. */
10274 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10275 fcn->name, lua_tostring(hlua->T, -1));
10276 lua_pop(hlua->T, 1);
10277 return 1;
10278
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010279 case HLUA_E_ETMOUT:
10280 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10281 fcn->name);
10282 return 1;
10283
10284 case HLUA_E_NOMEM:
10285 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10286 fcn->name);
10287 return 1;
10288
10289 case HLUA_E_YIELD: /* unexpected */
10290 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10291 fcn->name);
10292 return 1;
10293
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010294 case HLUA_E_ERR:
10295 /* Display log. */
10296 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10297 fcn->name);
10298 return 1;
10299
10300 default:
10301 return 1;
10302 }
10303
10304 return 1;
10305}
10306
10307static void hlua_cli_io_release_fct(struct appctx *appctx)
10308{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010309 struct hlua_cli_ctx *ctx = appctx->svcctx;
10310
10311 hlua_ctx_destroy(ctx->hlua);
10312 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010313}
10314
10315/* This function is an LUA binding used for registering
10316 * new keywords in the cli. It expects a list of keywords
10317 * which are the "path". It is limited to 5 keywords. A
10318 * description of the command, a function to be executed
10319 * for the parsing and a function for io handlers.
10320 */
10321__LJMP static int hlua_register_cli(lua_State *L)
10322{
10323 struct cli_kw_list *cli_kws;
10324 const char *message;
10325 int ref_io;
10326 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010327 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010328 int index;
10329 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010330 struct buffer *trash;
10331 const char *kw[5];
10332 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010333 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010334
10335 MAY_LJMP(check_args(L, 3, "register_cli"));
10336
10337 /* First argument : an array of maximum 5 keywords. */
10338 if (!lua_istable(L, 1))
10339 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10340
10341 /* Second argument : string with contextual message. */
10342 message = MAY_LJMP(luaL_checkstring(L, 2));
10343
10344 /* Third and fourth argument : lua function. */
10345 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10346
Thierry Fournierf67442e2020-11-28 20:41:07 +010010347 /* Check for CLI service already registered */
10348 trash = get_trash_chunk();
10349 index = 0;
10350 lua_pushnil(L);
10351 memset(kw, 0, sizeof(kw));
10352 while (lua_next(L, 1) != 0) {
10353 if (index >= CLI_PREFIX_KW_NB)
10354 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10355 if (lua_type(L, -1) != LUA_TSTRING)
10356 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10357 kw[index] = lua_tostring(L, -1);
10358 if (index == 0)
10359 chunk_printf(trash, "%s", kw[index]);
10360 else
10361 chunk_appendf(trash, " %s", kw[index]);
10362 index++;
10363 lua_pop(L, 1);
10364 }
10365 cli_kw = cli_find_kw_exact((char **)kw);
10366 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010367 fcn = cli_kw->private;
10368 if (fcn->function_ref[hlua_state_id] != -1) {
10369 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10370 "This will become a hard error in version 2.5.\n", trash->area);
10371 }
10372 fcn->function_ref[hlua_state_id] = ref_io;
10373 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010374 }
10375
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010376 /* Allocate and fill the sample fetch keyword struct. */
10377 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010378 if (!cli_kws) {
10379 errmsg = "Lua out of memory error.";
10380 goto error;
10381 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010382 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010383 if (!fcn) {
10384 errmsg = "Lua out of memory error.";
10385 goto error;
10386 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010387
10388 /* Fill path. */
10389 index = 0;
10390 lua_pushnil(L);
10391 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010392 if (index >= 5) {
10393 errmsg = "1st argument must be a table with a maximum of 5 entries";
10394 goto error;
10395 }
10396 if (lua_type(L, -1) != LUA_TSTRING) {
10397 errmsg = "1st argument must be a table filled with strings";
10398 goto error;
10399 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010400 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010401 if (!cli_kws->kw[0].str_kw[index]) {
10402 errmsg = "Lua out of memory error.";
10403 goto error;
10404 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010405 index++;
10406 lua_pop(L, 1);
10407 }
10408
10409 /* Copy help message. */
10410 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010411 if (!cli_kws->kw[0].usage) {
10412 errmsg = "Lua out of memory error.";
10413 goto error;
10414 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010415
10416 /* Fill fcn io handler. */
10417 len = strlen("<lua.cli>") + 1;
10418 for (i = 0; i < index; i++)
10419 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10420 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010421 if (!fcn->name) {
10422 errmsg = "Lua out of memory error.";
10423 goto error;
10424 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010425 strncat((char *)fcn->name, "<lua.cli", len);
10426 for (i = 0; i < index; i++) {
10427 strncat((char *)fcn->name, ".", len);
10428 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10429 }
10430 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010431 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010432
10433 /* Fill last entries. */
10434 cli_kws->kw[0].private = fcn;
10435 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10436 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10437 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10438
10439 /* Register this new converter */
10440 cli_register_kw(cli_kws);
10441
10442 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010443
10444 error:
10445 release_hlua_function(fcn);
10446 if (cli_kws) {
10447 for (i = 0; i < index; i++)
10448 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10449 ha_free((char **)&(cli_kws->kw[0].usage));
10450 }
10451 ha_free(&cli_kws);
10452 WILL_LJMP(luaL_error(L, errmsg));
10453 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010454}
10455
Christopher Faulet69c581a2021-05-31 08:54:04 +020010456static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10457{
10458 struct hlua_flt_config *conf = fconf->conf;
10459 lua_State *L;
10460 int error, pos, state_id, flt_ref;
10461
10462 state_id = reg_flt_to_stack_id(conf->reg);
10463 L = hlua_states[state_id];
10464 pos = lua_gettop(L);
10465
10466 /* The filter parsing function */
10467 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10468
10469 /* Push the filter class on the stack and resolve all callbacks */
10470 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10471
10472 /* Duplicate the filter class so each filter will have its own copy */
10473 lua_newtable(L);
10474 lua_pushnil(L);
10475
10476 while (lua_next(L, pos+2)) {
10477 lua_pushvalue(L, -2);
10478 lua_insert(L, -2);
10479 lua_settable(L, -4);
10480 }
10481 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10482
10483 /* Remove the original lua filter class from the stack */
10484 lua_pop(L, 1);
10485
10486 /* Push the copy on the stack */
10487 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10488
10489 /* extra args are pushed in a table */
10490 lua_newtable(L);
10491 for (pos = 0; conf->args[pos]; pos++) {
10492 /* Check stack available size. */
10493 if (!lua_checkstack(L, 1)) {
10494 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10495 goto error;
10496 }
10497 lua_pushstring(L, conf->args[pos]);
10498 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10499 }
10500
10501 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10502 switch (error) {
10503 case LUA_OK:
10504 /* replace the filter ref */
10505 conf->ref[state_id] = flt_ref;
10506 break;
10507 case LUA_ERRRUN:
10508 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10509 goto error;
10510 case LUA_ERRMEM:
10511 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10512 goto error;
10513 case LUA_ERRERR:
10514 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10515 goto error;
10516#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10517 case LUA_ERRGCMM:
10518 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10519 goto error;
10520#endif
10521 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010522 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010523 goto error;
10524 }
10525
10526 lua_settop(L, 0);
10527 return 0;
10528
10529 error:
10530 lua_settop(L, 0);
10531 return -1;
10532}
10533
10534static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10535{
10536 struct hlua_flt_config *conf = fconf->conf;
10537 lua_State *L;
10538 int state_id;
10539
10540 if (!conf)
10541 return;
10542
10543 state_id = reg_flt_to_stack_id(conf->reg);
10544 L = hlua_states[state_id];
10545 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10546}
10547
10548static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10549{
10550 struct hlua_flt_config *conf = fconf->conf;
10551 int state_id = reg_flt_to_stack_id(conf->reg);
10552
10553 /* Rely on per-thread init for global scripts */
10554 if (!state_id)
10555 return hlua_filter_init_per_thread(px, fconf);
10556 return 0;
10557}
10558
10559static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10560{
10561
10562 if (fconf->conf) {
10563 struct hlua_flt_config *conf = fconf->conf;
10564 int state_id = reg_flt_to_stack_id(conf->reg);
10565 int pos;
10566
10567 /* Rely on per-thread deinit for global scripts */
10568 if (!state_id)
10569 hlua_filter_deinit_per_thread(px, fconf);
10570
10571 for (pos = 0; conf->args[pos]; pos++)
10572 free(conf->args[pos]);
10573 free(conf->args);
10574 }
10575 ha_free(&fconf->conf);
10576 ha_free((char **)&fconf->id);
10577 ha_free(&fconf->ops);
10578}
10579
10580static int hlua_filter_new(struct stream *s, struct filter *filter)
10581{
10582 struct hlua_flt_config *conf = FLT_CONF(filter);
10583 struct hlua_flt_ctx *flt_ctx = NULL;
10584 int ret = 1;
10585
10586 /* In the execution wrappers linked with a stream, the
10587 * Lua context can be not initialized. This behavior
10588 * permits to save performances because a systematic
10589 * Lua initialization cause 5% performances loss.
10590 */
10591 if (!s->hlua) {
10592 struct hlua *hlua;
10593
10594 hlua = pool_alloc(pool_head_hlua);
10595 if (!hlua) {
10596 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10597 conf->reg->name);
10598 ret = 0;
10599 goto end;
10600 }
10601 HLUA_INIT(hlua);
10602 s->hlua = hlua;
10603 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10604 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10605 conf->reg->name);
10606 ret = 0;
10607 goto end;
10608 }
10609 }
10610
10611 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10612 if (!flt_ctx) {
10613 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10614 conf->reg->name);
10615 ret = 0;
10616 goto end;
10617 }
10618 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10619 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10620 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10621 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10622 conf->reg->name);
10623 ret = 0;
10624 goto end;
10625 }
10626 HLUA_INIT(flt_ctx->hlua[0]);
10627 HLUA_INIT(flt_ctx->hlua[1]);
10628 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10629 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10630 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10631 conf->reg->name);
10632 ret = 0;
10633 goto end;
10634 }
10635
10636 if (!HLUA_IS_RUNNING(s->hlua)) {
10637 /* The following Lua calls can fail. */
10638 if (!SET_SAFE_LJMP(s->hlua)) {
10639 const char *error;
10640
10641 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10642 error = lua_tostring(s->hlua->T, -1);
10643 else
10644 error = "critical error";
10645 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10646 ret = 0;
10647 goto end;
10648 }
10649
10650 /* Check stack size. */
10651 if (!lua_checkstack(s->hlua->T, 1)) {
10652 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010653 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010654 ret = 0;
10655 goto end;
10656 }
10657
10658 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10659 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10660 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10661 conf->reg->name);
10662 RESET_SAFE_LJMP(s->hlua);
10663 ret = 0;
10664 goto end;
10665 }
10666 lua_insert(s->hlua->T, -2);
10667
10668 /* Push the copy on the stack */
10669 s->hlua->nargs = 1;
10670
10671 /* We must initialize the execution timeouts. */
10672 s->hlua->max_time = hlua_timeout_session;
10673
10674 /* At this point the execution is safe. */
10675 RESET_SAFE_LJMP(s->hlua);
10676 }
10677
10678 switch (hlua_ctx_resume(s->hlua, 0)) {
10679 case HLUA_E_OK:
10680 /* Nothing returned or not a table, ignore the filter for current stream */
10681 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10682 ret = 0;
10683 goto end;
10684 }
10685
10686 /* Attached the filter pointer to the ctx */
10687 lua_pushstring(s->hlua->T, "__filter");
10688 lua_pushlightuserdata(s->hlua->T, filter);
10689 lua_settable(s->hlua->T, -3);
10690
10691 /* Save a ref on the filter ctx */
10692 lua_pushvalue(s->hlua->T, 1);
10693 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10694 filter->ctx = flt_ctx;
10695 break;
10696 case HLUA_E_ERRMSG:
10697 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10698 ret = -1;
10699 goto end;
10700 case HLUA_E_ETMOUT:
10701 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10702 ret = 0;
10703 goto end;
10704 case HLUA_E_NOMEM:
10705 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10706 ret = 0;
10707 goto end;
10708 case HLUA_E_AGAIN:
10709 case HLUA_E_YIELD:
10710 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10711 " are not allowed from 'new' function.\n", conf->reg->name);
10712 ret = 0;
10713 goto end;
10714 case HLUA_E_ERR:
10715 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10716 ret = 0;
10717 goto end;
10718 default:
10719 ret = 0;
10720 goto end;
10721 }
10722
10723 end:
10724 if (s->hlua)
10725 lua_settop(s->hlua->T, 0);
10726 if (ret <= 0) {
10727 if (flt_ctx) {
10728 hlua_ctx_destroy(flt_ctx->hlua[0]);
10729 hlua_ctx_destroy(flt_ctx->hlua[1]);
10730 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10731 }
10732 }
10733 return ret;
10734}
10735
10736static void hlua_filter_delete(struct stream *s, struct filter *filter)
10737{
10738 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10739
10740 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10741 hlua_ctx_destroy(flt_ctx->hlua[0]);
10742 hlua_ctx_destroy(flt_ctx->hlua[1]);
10743 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10744 filter->ctx = NULL;
10745}
10746
Christopher Faulet9f55a502020-02-25 15:21:02 +010010747static int hlua_filter_from_payload(struct filter *filter)
10748{
10749 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10750
10751 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10752}
10753
Christopher Fauletc404f112020-02-26 15:03:09 +010010754static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10755 int dir, unsigned int flags)
10756{
10757 struct hlua *flt_hlua;
10758 struct hlua_flt_config *conf = FLT_CONF(filter);
10759 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10760 unsigned int hflags = HLUA_TXN_FLT_CTX;
10761 int ret = 1;
10762
10763 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10764 if (!flt_hlua)
10765 goto end;
10766
10767 if (!HLUA_IS_RUNNING(flt_hlua)) {
10768 int extra_idx = lua_gettop(flt_hlua->T);
10769
10770 /* The following Lua calls can fail. */
10771 if (!SET_SAFE_LJMP(flt_hlua)) {
10772 const char *error;
10773
10774 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10775 error = lua_tostring(flt_hlua->T, -1);
10776 else
10777 error = "critical error";
10778 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10779 goto end;
10780 }
10781
10782 /* Check stack size. */
10783 if (!lua_checkstack(flt_hlua->T, 3)) {
10784 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10785 RESET_SAFE_LJMP(flt_hlua);
10786 goto end;
10787 }
10788
10789 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10790 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10791 RESET_SAFE_LJMP(flt_hlua);
10792 goto end;
10793 }
10794 lua_insert(flt_hlua->T, -2);
10795
10796 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10797 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10798 RESET_SAFE_LJMP(flt_hlua);
10799 goto end;
10800 }
10801 flt_hlua->nargs = 2;
10802
10803 if (flags & HLUA_FLT_CB_ARG_CHN) {
10804 if (dir == SMP_OPT_DIR_REQ)
10805 lua_getfield(flt_hlua->T, -1, "req");
10806 else
10807 lua_getfield(flt_hlua->T, -1, "res");
10808 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10809 lua_pushstring(flt_hlua->T, "__filter");
10810 lua_pushlightuserdata(flt_hlua->T, filter);
10811 lua_settable(flt_hlua->T, -3);
10812 }
10813 flt_hlua->nargs++;
10814 }
10815 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010816 if (dir == SMP_OPT_DIR_REQ)
10817 lua_getfield(flt_hlua->T, -1, "http_req");
10818 else
10819 lua_getfield(flt_hlua->T, -1, "http_res");
10820 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10821 lua_pushstring(flt_hlua->T, "__filter");
10822 lua_pushlightuserdata(flt_hlua->T, filter);
10823 lua_settable(flt_hlua->T, -3);
10824 }
10825 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010826 }
10827
10828 /* Check stack size. */
10829 if (!lua_checkstack(flt_hlua->T, 1)) {
10830 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10831 RESET_SAFE_LJMP(flt_hlua);
10832 goto end;
10833 }
10834
10835 while (extra_idx--) {
10836 lua_pushvalue(flt_hlua->T, 1);
10837 lua_remove(flt_hlua->T, 1);
10838 flt_hlua->nargs++;
10839 }
10840
10841 /* We must initialize the execution timeouts. */
10842 flt_hlua->max_time = hlua_timeout_session;
10843
10844 /* At this point the execution is safe. */
10845 RESET_SAFE_LJMP(flt_hlua);
10846 }
10847
10848 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10849 case HLUA_E_OK:
10850 /* Catch the return value if it required */
10851 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10852 ret = lua_tointeger(flt_hlua->T, -1);
10853 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10854 }
10855
10856 /* Set timeout in the required channel. */
10857 if (flt_hlua->wake_time != TICK_ETERNITY) {
10858 if (dir == SMP_OPT_DIR_REQ)
10859 s->req.analyse_exp = flt_hlua->wake_time;
10860 else
10861 s->res.analyse_exp = flt_hlua->wake_time;
10862 }
10863 break;
10864 case HLUA_E_AGAIN:
10865 /* Set timeout in the required channel. */
10866 if (flt_hlua->wake_time != TICK_ETERNITY) {
10867 if (dir == SMP_OPT_DIR_REQ)
10868 s->req.analyse_exp = flt_hlua->wake_time;
10869 else
10870 s->res.analyse_exp = flt_hlua->wake_time;
10871 }
10872 /* Some actions can be wake up when a "write" event
10873 * is detected on a response channel. This is useful
10874 * only for actions targeted on the requests.
10875 */
10876 if (HLUA_IS_WAKERESWR(flt_hlua))
10877 s->res.flags |= CF_WAKE_WRITE;
10878 if (HLUA_IS_WAKEREQWR(flt_hlua))
10879 s->req.flags |= CF_WAKE_WRITE;
10880 ret = 0;
10881 goto end;
10882 case HLUA_E_ERRMSG:
10883 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10884 ret = -1;
10885 goto end;
10886 case HLUA_E_ETMOUT:
10887 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10888 goto end;
10889 case HLUA_E_NOMEM:
10890 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10891 goto end;
10892 case HLUA_E_YIELD:
10893 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10894 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10895 goto end;
10896 case HLUA_E_ERR:
10897 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10898 goto end;
10899 default:
10900 goto end;
10901 }
10902
10903
10904 end:
10905 return ret;
10906}
10907
10908static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10909{
10910 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10911
10912 flt_ctx->flags = 0;
10913 return hlua_filter_callback(s, filter, "start_analyze",
10914 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10915 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10916}
10917
10918static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10919{
10920 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10921
10922 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10923 return hlua_filter_callback(s, filter, "end_analyze",
10924 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10925 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10926}
10927
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010928static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10929{
10930 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10931
10932 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10933 return hlua_filter_callback(s, filter, "http_headers",
10934 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10935 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10936}
10937
10938static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10939 unsigned int offset, unsigned int len)
10940{
10941 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10942 struct hlua *flt_hlua;
10943 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10944 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10945 int ret;
10946
10947 flt_hlua = flt_ctx->hlua[idx];
10948 flt_ctx->cur_off[idx] = offset;
10949 flt_ctx->cur_len[idx] = len;
10950 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10951 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10952 if (ret != -1) {
10953 ret = flt_ctx->cur_len[idx];
10954 if (lua_gettop(flt_hlua->T) > 0) {
10955 ret = lua_tointeger(flt_hlua->T, -1);
10956 if (ret > flt_ctx->cur_len[idx])
10957 ret = flt_ctx->cur_len[idx];
10958 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10959 }
10960 }
10961 return ret;
10962}
10963
10964static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10965{
10966 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10967
10968 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10969 return hlua_filter_callback(s, filter, "http_end",
10970 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10971 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10972}
10973
Christopher Fauletc404f112020-02-26 15:03:09 +010010974static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10975 unsigned int offset, unsigned int len)
10976{
10977 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10978 struct hlua *flt_hlua;
10979 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10980 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10981 int ret;
10982
10983 flt_hlua = flt_ctx->hlua[idx];
10984 flt_ctx->cur_off[idx] = offset;
10985 flt_ctx->cur_len[idx] = len;
10986 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10987 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10988 if (ret != -1) {
10989 ret = flt_ctx->cur_len[idx];
10990 if (lua_gettop(flt_hlua->T) > 0) {
10991 ret = lua_tointeger(flt_hlua->T, -1);
10992 if (ret > flt_ctx->cur_len[idx])
10993 ret = flt_ctx->cur_len[idx];
10994 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10995 }
10996 }
10997 return ret;
10998}
10999
Christopher Faulet69c581a2021-05-31 08:54:04 +020011000static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11001 struct flt_conf *fconf, char **err, void *private)
11002{
11003 struct hlua_reg_filter *reg_flt = private;
11004 lua_State *L;
11005 struct hlua_flt_config *conf = NULL;
11006 const char *flt_id = NULL;
11007 int state_id, pos, flt_flags = 0;
11008 struct flt_ops *hlua_flt_ops = NULL;
11009
11010 state_id = reg_flt_to_stack_id(reg_flt);
11011 L = hlua_states[state_id];
11012
11013 /* Initialize the filter ops with default callbacks */
11014 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011015 if (!hlua_flt_ops)
11016 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011017 hlua_flt_ops->init = hlua_filter_init;
11018 hlua_flt_ops->deinit = hlua_filter_deinit;
11019 if (state_id) {
11020 /* Set per-thread callback if script is loaded per-thread */
11021 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11022 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11023 }
11024 hlua_flt_ops->attach = hlua_filter_new;
11025 hlua_flt_ops->detach = hlua_filter_delete;
11026
11027 /* Push the filter class on the stack and resolve all callbacks */
11028 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11029
Christopher Fauletc404f112020-02-26 15:03:09 +010011030 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11031 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11032 lua_pop(L, 1);
11033 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11034 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11035 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011036 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11037 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11038 lua_pop(L, 1);
11039 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11040 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11041 lua_pop(L, 1);
11042 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11043 hlua_flt_ops->http_end = hlua_filter_http_end;
11044 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011045 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11046 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11047 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011048
11049 /* Get id and flags of the filter class */
11050 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11051 flt_id = lua_tostring(L, -1);
11052 lua_pop(L, 1);
11053 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11054 flt_flags = lua_tointeger(L, -1);
11055 lua_pop(L, 1);
11056
11057 /* Create the filter config */
11058 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011059 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011060 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011061 conf->reg = reg_flt;
11062
11063 /* duplicate args */
11064 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11065 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011066 if (!conf->args)
11067 goto error;
11068 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011069 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011070 if (!conf->args[pos])
11071 goto error;
11072 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011073 conf->args[pos] = NULL;
11074 *cur_arg += pos + 1;
11075
Christopher Fauletc86bb872021-08-13 08:33:57 +020011076 if (flt_id) {
11077 fconf->id = strdup(flt_id);
11078 if (!fconf->id)
11079 goto error;
11080 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011081 fconf->flags = flt_flags;
11082 fconf->conf = conf;
11083 fconf->ops = hlua_flt_ops;
11084
11085 lua_settop(L, 0);
11086 return 0;
11087
11088 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011089 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011090 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011091 if (conf && conf->args) {
11092 for (pos = 0; conf->args[pos]; pos++)
11093 free(conf->args[pos]);
11094 free(conf->args);
11095 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011096 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011097 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011098 lua_settop(L, 0);
11099 return -1;
11100}
11101
Christopher Fauletc404f112020-02-26 15:03:09 +010011102__LJMP static int hlua_register_data_filter(lua_State *L)
11103{
11104 struct filter *filter;
11105 struct channel *chn;
11106
11107 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11108 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11109 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11110
11111 lua_getfield(L, 1, "__filter");
11112 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11113 filter = lua_touserdata (L, -1);
11114 lua_pop(L, 1);
11115
11116 register_data_filter(chn_strm(chn), chn, filter);
11117 return 1;
11118}
11119
11120__LJMP static int hlua_unregister_data_filter(lua_State *L)
11121{
11122 struct filter *filter;
11123 struct channel *chn;
11124
11125 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11126 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11127 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11128
11129 lua_getfield(L, 1, "__filter");
11130 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11131 filter = lua_touserdata (L, -1);
11132 lua_pop(L, 1);
11133
11134 unregister_data_filter(chn_strm(chn), chn, filter);
11135 return 1;
11136}
11137
Christopher Faulet69c581a2021-05-31 08:54:04 +020011138/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011139 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011140 * parse configuration arguments.
11141 */
11142__LJMP static int hlua_register_filter(lua_State *L)
11143{
11144 struct buffer *trash;
11145 struct flt_kw_list *fkl;
11146 struct flt_kw *fkw;
11147 const char *name;
11148 struct hlua_reg_filter *reg_flt= NULL;
11149 int flt_ref, fun_ref;
11150 int len;
11151
11152 MAY_LJMP(check_args(L, 3, "register_filter"));
11153
11154 /* First argument : filter name. */
11155 name = MAY_LJMP(luaL_checkstring(L, 1));
11156
11157 /* Second argument : The filter class */
11158 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11159
11160 /* Third argument : lua function. */
11161 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11162
11163 trash = get_trash_chunk();
11164 chunk_printf(trash, "lua.%s", name);
11165 fkw = flt_find_kw(trash->area);
11166 if (fkw != NULL) {
11167 reg_flt = fkw->private;
11168 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11169 ha_warning("Trying to register filter 'lua.%s' more than once. "
11170 "This will become a hard error in version 2.5.\n", name);
11171 }
11172 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11173 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11174 return 0;
11175 }
11176
11177 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11178 if (!fkl)
11179 goto alloc_error;
11180 fkl->scope = "HLUA";
11181
11182 reg_flt = new_hlua_reg_filter(name);
11183 if (!reg_flt)
11184 goto alloc_error;
11185
11186 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11187 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11188
11189 /* The filter keyword */
11190 len = strlen("lua.") + strlen(name) + 1;
11191 fkl->kw[0].kw = calloc(1, len);
11192 if (!fkl->kw[0].kw)
11193 goto alloc_error;
11194
11195 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11196
11197 fkl->kw[0].parse = hlua_filter_parse_fct;
11198 fkl->kw[0].private = reg_flt;
11199 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11200
11201 /* Register this new filter */
11202 flt_register_keywords(fkl);
11203
11204 return 0;
11205
11206 alloc_error:
11207 release_hlua_reg_filter(reg_flt);
11208 ha_free(&fkl);
11209 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11210 return 0; /* Never reached */
11211}
11212
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011213static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011214 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011215 char **err, unsigned int *timeout)
11216{
11217 const char *error;
11218
11219 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011220 if (error == PARSE_TIME_OVER) {
11221 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11222 args[1], args[0]);
11223 return -1;
11224 }
11225 else if (error == PARSE_TIME_UNDER) {
11226 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11227 args[1], args[0]);
11228 return -1;
11229 }
11230 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011231 memprintf(err, "%s: invalid timeout", args[0]);
11232 return -1;
11233 }
11234 return 0;
11235}
11236
11237static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011238 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011239 char **err)
11240{
11241 return hlua_read_timeout(args, section_type, curpx, defpx,
11242 file, line, err, &hlua_timeout_session);
11243}
11244
11245static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011246 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011247 char **err)
11248{
11249 return hlua_read_timeout(args, section_type, curpx, defpx,
11250 file, line, err, &hlua_timeout_task);
11251}
11252
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011253static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011254 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011255 char **err)
11256{
11257 return hlua_read_timeout(args, section_type, curpx, defpx,
11258 file, line, err, &hlua_timeout_applet);
11259}
11260
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011261static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011262 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011263 char **err)
11264{
11265 char *error;
11266
11267 hlua_nb_instruction = strtoll(args[1], &error, 10);
11268 if (*error != '\0') {
11269 memprintf(err, "%s: invalid number", args[0]);
11270 return -1;
11271 }
11272 return 0;
11273}
11274
Willy Tarreau32f61e22015-03-18 17:54:59 +010011275static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011276 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011277 char **err)
11278{
11279 char *error;
11280
11281 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011282 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011283 return -1;
11284 }
11285 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11286 if (*error != '\0') {
11287 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11288 return -1;
11289 }
11290 return 0;
11291}
11292
11293
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011294/* This function is called by the main configuration key "lua-load". It loads and
11295 * execute an lua file during the parsing of the HAProxy configuration file. It is
11296 * the main lua entry point.
11297 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011298 * This function runs with the HAProxy keywords API. It returns -1 if an error
11299 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011300 *
11301 * In some error case, LUA set an error message in top of the stack. This function
11302 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011303 *
11304 * This function can fail with an abort() due to an Lua critical error.
11305 * We are in the configuration parsing process of HAProxy, this abort() is
11306 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011307 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011308static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011309{
11310 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011311 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011312
11313 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011314 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011315 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011316 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011317 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011318 return -1;
11319 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011320
11321 /* Push args in the Lua stack, except the first one which is the filename */
11322 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011323 /* Check stack size. */
11324 if (!lua_checkstack(L, 1)) {
11325 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11326 return -1;
11327 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011328 lua_pushstring(L, args[nargs]);
11329 }
11330 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011331
11332 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011333 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011334 switch (error) {
11335 case LUA_OK:
11336 break;
11337 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011338 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011339 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011340 return -1;
11341 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011342 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011343 return -1;
11344 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011345 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011346 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011347 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011348#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011349 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011350 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011351 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011352 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011353#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011354 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011355 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011356 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011357 return -1;
11358 }
11359
11360 return 0;
11361}
11362
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011363static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011364 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011365 char **err)
11366{
11367 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011368 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011369 return -1;
11370 }
11371
Thierry Fournier59f11be2020-11-29 00:37:41 +010011372 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011373 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011374 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011375 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011376}
11377
Thierry Fournier59f11be2020-11-29 00:37:41 +010011378static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011379 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011380 char **err)
11381{
11382 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011383 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011384
11385 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011386 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011387 return -1;
11388 }
11389
11390 if (per_thread_load == NULL) {
11391 /* allocate the first entry large enough to store the final NULL */
11392 per_thread_load = calloc(1, sizeof(*per_thread_load));
11393 if (per_thread_load == NULL) {
11394 memprintf(err, "out of memory error");
11395 return -1;
11396 }
11397 }
11398
11399 /* count used entries */
11400 for (len = 0; per_thread_load[len] != NULL; len++)
11401 ;
11402
11403 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11404 if (per_thread_load == NULL) {
11405 memprintf(err, "out of memory error");
11406 return -1;
11407 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011408 per_thread_load[len + 1] = NULL;
11409
Thierry Fournierae6b5682022-09-19 09:04:16 +020011410 /* count args excepting the first, allocate array and copy args */
11411 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011412 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011413 if (per_thread_load[len] == NULL) {
11414 memprintf(err, "out of memory error");
11415 return -1;
11416 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011417 for (i = 1; *(args[i]) != 0; i++) {
11418 per_thread_load[len][i - 1] = strdup(args[i]);
11419 if (per_thread_load[len][i - 1] == NULL) {
11420 memprintf(err, "out of memory error");
11421 return -1;
11422 }
11423 }
11424 per_thread_load[len][i - 1] = strdup("");
11425 if (per_thread_load[len][i - 1] == NULL) {
11426 memprintf(err, "out of memory error");
11427 return -1;
11428 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011429
11430 /* loading for thread 1 only */
11431 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011432 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011433 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011434}
11435
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011436/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11437 * in the given <ctx>.
11438 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011439static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011440{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011441 lua_getglobal(L, "package"); /* push package variable */
11442 lua_pushstring(L, path); /* push given path */
11443 lua_pushstring(L, ";"); /* push semicolon */
11444 lua_getfield(L, -3, type); /* push old path */
11445 lua_concat(L, 3); /* concatenate to new path */
11446 lua_setfield(L, -2, type); /* store new path */
11447 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011448
11449 return 0;
11450}
11451
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011452static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011453 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011454 char **err)
11455{
11456 char *path;
11457 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011458 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011459 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011460
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011461 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011462 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011463 }
11464
11465 if (!(*args[1])) {
11466 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011467 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011468 }
11469 path = args[1];
11470
11471 if (*args[2]) {
11472 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11473 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011474 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011475 }
11476 type = args[2];
11477 }
11478
Thierry Fournier59f11be2020-11-29 00:37:41 +010011479 p = calloc(1, sizeof(*p));
11480 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011481 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011482 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011483 }
11484 p->path = strdup(path);
11485 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011486 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011487 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011488 }
11489 p->type = strdup(type);
11490 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011491 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011492 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011493 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011494 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011495
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011496 /* Handle the global state and the per-thread state for the first
11497 * thread. The remaining threads will be initialized based on
11498 * prepend_path_list.
11499 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011500 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011501 lua_State *L = hlua_states[i];
11502 const char *error;
11503
11504 if (setjmp(safe_ljmp_env) != 0) {
11505 lua_atpanic(L, hlua_panic_safe);
11506 if (lua_type(L, -1) == LUA_TSTRING)
11507 error = lua_tostring(L, -1);
11508 else
11509 error = "critical error";
11510 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11511 exit(1);
11512 } else {
11513 lua_atpanic(L, hlua_panic_ljmp);
11514 }
11515
11516 hlua_prepend_path(L, type, path);
11517
11518 lua_atpanic(L, hlua_panic_safe);
11519 }
11520
Thierry Fournier59f11be2020-11-29 00:37:41 +010011521 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011522
11523err2:
11524 free(p->type);
11525 free(p->path);
11526err:
11527 free(p);
11528 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011529}
11530
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011531/* configuration keywords declaration */
11532static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011533 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011534 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011535 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011536 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11537 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011538 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011539 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011540 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011541 { 0, NULL, NULL },
11542}};
11543
Willy Tarreau0108d902018-11-25 19:14:37 +010011544INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11545
William Lallemand52139182022-03-30 15:05:42 +020011546#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011547
William Lallemand30fcca12022-03-30 12:03:12 +020011548/*
11549 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11550 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11551 * difference is that the yield in lua and for the CLI is not handled the same
11552 * way.
11553 */
11554__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11555{
11556 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11557 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11558 struct ckch_inst *ckchi = *lua_ckchi;
11559 struct ckch_store *old_ckchs = lua_ckchs[0];
11560 struct ckch_store *new_ckchs = lua_ckchs[1];
11561 struct hlua *hlua;
11562 char *err = NULL;
11563 int y = 1;
11564
11565 hlua = hlua_gethlua(L);
11566
11567 /* get the first ckchi to copy */
11568 if (ckchi == NULL)
11569 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11570
11571 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11572 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11573 struct ckch_inst *new_inst;
11574
11575 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11576 if (y % 10 == 0) {
11577
11578 *lua_ckchi = ckchi;
11579
11580 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11581 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11582 }
11583
11584 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11585 goto error;
11586
11587 /* link the new ckch_inst to the duplicate */
11588 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11589 y++;
11590 }
11591
11592 /* The generation is finished, we can insert everything */
11593 ckch_store_replace(old_ckchs, new_ckchs);
11594
11595 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11596
11597 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11598
11599 return 0;
11600
11601error:
11602 ckch_store_free(new_ckchs);
11603 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11604 WILL_LJMP(luaL_error(L, "%s", err));
11605 free(err);
11606
11607 return 0;
11608}
11609
11610/*
11611 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11612 * from the table in parameter.
11613 *
11614 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11615 * means it does not need to have a transaction since everything is done in the
11616 * same function.
11617 *
11618 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11619 *
11620 */
11621__LJMP static int hlua_ckch_set(lua_State *L)
11622{
11623 struct hlua *hlua;
11624 struct ckch_inst **lua_ckchi;
11625 struct ckch_store **lua_ckchs;
11626 struct ckch_store *old_ckchs = NULL;
11627 struct ckch_store *new_ckchs = NULL;
11628 int errcode = 0;
11629 char *err = NULL;
11630 struct cert_exts *cert_ext = NULL;
11631 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010011632 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020011633 int ret;
11634
11635 if (lua_type(L, -1) != LUA_TTABLE)
11636 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11637
11638 hlua = hlua_gethlua(L);
11639
11640 /* FIXME: this should not return an error but should come back later */
11641 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11642 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11643
11644 ret = lua_getfield(L, -1, "filename");
11645 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011646 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011647 errcode |= ERR_ALERT | ERR_FATAL;
11648 goto end;
11649 }
11650 filename = (char *)lua_tostring(L, -1);
11651
11652
11653 /* look for the filename in the tree */
11654 old_ckchs = ckchs_lookup(filename);
11655 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011656 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011657 errcode |= ERR_ALERT | ERR_FATAL;
11658 goto end;
11659 }
11660 /* TODO: handle extra_files_noext */
11661
11662 new_ckchs = ckchs_dup(old_ckchs);
11663 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011664 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011665 errcode |= ERR_ALERT | ERR_FATAL;
11666 goto end;
11667 }
11668
William Lallemand52ddd992022-11-22 11:51:53 +010011669 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020011670
11671 /* loop on the field in the table, which have the same name as the
11672 * possible extensions of files */
11673 lua_pushnil(L);
11674 while (lua_next(L, 1)) {
11675 int i;
11676 const char *field = lua_tostring(L, -2);
11677 char *payload = (char *)lua_tostring(L, -1);
11678
11679 if (!field || strcmp(field, "filename") == 0) {
11680 lua_pop(L, 1);
11681 continue;
11682 }
11683
11684 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11685 if (strcmp(field, cert_exts[i].ext) == 0) {
11686 cert_ext = &cert_exts[i];
11687 break;
11688 }
11689 }
11690
11691 /* this is the default type, the field is not supported */
11692 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011693 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011694 errcode |= ERR_ALERT | ERR_FATAL;
11695 goto end;
11696 }
11697
11698 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010011699 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011700 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011701 errcode |= ERR_ALERT | ERR_FATAL;
11702 goto end;
11703 }
11704 lua_pop(L, 1);
11705 }
11706
11707 /* store the pointers on the lua stack */
11708 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11709 lua_ckchs[0] = old_ckchs;
11710 lua_ckchs[1] = new_ckchs;
11711 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11712 *lua_ckchi = NULL;
11713
11714 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11715 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11716
11717end:
11718 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11719
11720 if (errcode & ERR_CODE) {
11721 ckch_store_free(new_ckchs);
11722 WILL_LJMP(luaL_error(L, "%s", err));
11723 }
11724 free(err);
11725
11726 return 0;
11727}
11728
William Lallemand52139182022-03-30 15:05:42 +020011729#else
11730
11731__LJMP static int hlua_ckch_set(lua_State *L)
11732{
11733 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11734
11735 return 0;
11736}
11737#endif /* ! USE_OPENSSL */
11738
11739
11740
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011741/* This function can fail with an abort() due to an Lua critical error.
11742 * We are in the initialisation process of HAProxy, this abort() is
11743 * tolerated.
11744 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011745int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011746{
11747 struct hlua_init_function *init;
11748 const char *msg;
11749 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011750 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011751 const char *kind;
11752 const char *trace;
11753 int return_status = 1;
11754#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11755 int nres;
11756#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011757
Willy Tarreaucdb53462020-12-02 12:12:00 +010011758 /* disable memory limit checks if limit is not set */
11759 if (!hlua_global_allocator.limit)
11760 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11761
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011762 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011763 if (setjmp(safe_ljmp_env) != 0) {
11764 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011765 if (lua_type(L, -1) == LUA_TSTRING)
11766 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011767 else
11768 error = "critical error";
11769 fprintf(stderr, "Lua post-init: %s.\n", error);
11770 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011771 } else {
11772 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011773 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011774
Thierry Fournierb8cef172020-11-28 15:37:17 +010011775 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011776
Thierry Fournierc7492592020-11-28 23:57:24 +010011777 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011778 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011779
11780#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011781 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011782#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011783 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011784#endif
11785 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011786 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011787
11788 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011789 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011790 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011791
11792 case LUA_ERRERR:
11793 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011794 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011795 case LUA_ERRRUN:
11796 if (!kind)
11797 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011798 msg = lua_tostring(L, -1);
11799 lua_settop(L, 0); /* Empty the stack. */
11800 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011801 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011802 if (msg)
11803 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11804 else
11805 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11806 return_status = 0;
11807 break;
11808
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011809 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011810 /* Unknown error */
11811 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011812 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011813 case LUA_YIELD:
11814 /* yield is not configured at this step, this state doesn't happen */
11815 if (!kind)
11816 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010011817 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011818 case LUA_ERRMEM:
11819 if (!kind)
11820 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011821 lua_settop(L, 0);
11822 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011823 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011824 ha_alert("Lua init: %s: %s\n", kind, trace);
11825 return_status = 0;
11826 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011827 }
Thierry Fournier670db242020-11-28 10:49:59 +010011828 if (!return_status)
11829 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011830 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011831
11832 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011833 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011834}
11835
Thierry Fournierb8cef172020-11-28 15:37:17 +010011836int hlua_post_init()
11837{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011838 int ret;
11839 int i;
11840 int errors;
11841 char *err = NULL;
11842 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011843 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011844
Willy Tarreaub1310492021-08-30 09:35:18 +020011845#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011846 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011847 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011848 int saved_used_backed = global.ssl_used_backend;
11849 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011850 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011851 global.ssl_used_backend = saved_used_backed;
11852 }
11853#endif
11854
Thierry Fournierc7492592020-11-28 23:57:24 +010011855 /* Perform post init of common thread */
11856 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011857 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011858 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11859 if (ret == 0)
11860 return 0;
11861
11862 /* init remaining lua states and load files */
11863 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11864
11865 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011866 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011867
11868 /* Init lua state */
11869 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11870
11871 /* Load lua files */
11872 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11873 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11874 if (ret != 0) {
11875 ha_alert("Lua init: %s\n", err);
11876 return 0;
11877 }
11878 }
11879 }
11880
11881 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011882 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011883
11884 /* Execute post init for all states */
11885 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11886
11887 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011888 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011889
11890 /* run post init */
11891 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11892 if (ret == 0)
11893 return 0;
11894 }
11895
11896 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011897 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011898
11899 /* control functions registering. Each function must have:
11900 * - only the function_ref[0] set positive and all other to -1
11901 * - only the function_ref[0] set to -1 and all other positive
11902 * This ensure a same reference is not used both in shared
11903 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011904 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011905 * complicated to found for the end user.
11906 */
11907 errors = 0;
11908 list_for_each_entry(fcn, &referenced_functions, l) {
11909 ret = 0;
11910 for (i = 1; i < global.nbthread + 1; i++) {
11911 if (fcn->function_ref[i] == -1)
11912 ret--;
11913 else
11914 ret++;
11915 }
11916 if (abs(ret) != global.nbthread) {
11917 ha_alert("Lua function '%s' is not referenced in all thread. "
11918 "Expect function in all thread or in none thread.\n", fcn->name);
11919 errors++;
11920 continue;
11921 }
11922
11923 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011924 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11925 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011926 "exclusive.\n", fcn->name);
11927 errors++;
11928 }
11929 }
11930
Christopher Faulet69c581a2021-05-31 08:54:04 +020011931 /* Do the same with registered filters */
11932 list_for_each_entry(reg_flt, &referenced_filters, l) {
11933 ret = 0;
11934 for (i = 1; i < global.nbthread + 1; i++) {
11935 if (reg_flt->flt_ref[i] == -1)
11936 ret--;
11937 else
11938 ret++;
11939 }
11940 if (abs(ret) != global.nbthread) {
11941 ha_alert("Lua filter '%s' is not referenced in all thread. "
11942 "Expect function in all thread or in none thread.\n", reg_flt->name);
11943 errors++;
11944 continue;
11945 }
11946
11947 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11948 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11949 "and per-thread Lua context (through lua-load-per-thread). these two context "
11950 "exclusive.\n", fcn->name);
11951 errors++;
11952 }
11953 }
11954
11955
Thierry Fournier59f11be2020-11-29 00:37:41 +010011956 if (errors > 0)
11957 return 0;
11958
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011959 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011960 * -1 in order to have probably a segfault if someone use it
11961 */
11962 hlua_state_id = -1;
11963
11964 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011965}
11966
Willy Tarreau32f61e22015-03-18 17:54:59 +010011967/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11968 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11969 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011970 * allocation. <nsize> is the requested new size. A new allocation is
11971 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011972 * zero. This one verifies that the limits are respected but is optimized
11973 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011974 *
11975 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11976 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11977 * that and will simply allocate zero as if it were the result of malloc(0),
11978 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11979 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011980 */
11981static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11982{
11983 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011984 size_t limit, old, new;
11985
11986 /* a limit of ~0 means unlimited and boot complete, so there's no need
11987 * for accounting anymore.
11988 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011989 if (likely(~zone->limit == 0)) {
11990 if (!nsize)
11991 ha_free(&ptr);
11992 else
11993 ptr = realloc(ptr, nsize);
11994 return ptr;
11995 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011996
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011997 if (!ptr)
11998 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011999
Willy Tarreaucdb53462020-12-02 12:12:00 +010012000 /* enforce strict limits across all threads */
12001 limit = zone->limit;
12002 old = _HA_ATOMIC_LOAD(&zone->allocated);
12003 do {
12004 new = old + nsize - osize;
12005 if (unlikely(nsize && limit && new > limit))
12006 return NULL;
12007 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012008
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012009 if (!nsize)
12010 ha_free(&ptr);
12011 else
12012 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012013
12014 if (unlikely(!ptr && nsize)) // failed
12015 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12016
12017 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012018 return ptr;
12019}
12020
Thierry Fournierecb83c22020-11-28 15:49:44 +010012021/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012022 * We are in the initialisation process of HAProxy, this abort() is
12023 * tolerated.
12024 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012025lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012026{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012027 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012028 int idx;
12029 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012030 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012031 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012032 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012033 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012034 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012035 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012036
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012037 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012038 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012039
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012040 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012041 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012042 *context = NULL;
12043
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012044 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012045 * the Lua function can fail with an abort. We are in the initialisation
12046 * process of HAProxy, this abort() is tolerated.
12047 */
12048
Thierry Fournier3c539322020-11-28 16:05:05 +010012049 /* Call post initialisation function in safe environment. */
12050 if (setjmp(safe_ljmp_env) != 0) {
12051 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012052 if (lua_type(L, -1) == LUA_TSTRING)
12053 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012054 else
12055 error_msg = "critical error";
12056 fprintf(stderr, "Lua init: %s.\n", error_msg);
12057 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012058 } else {
12059 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012060 }
12061
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012062 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012063 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012064#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12065#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12066#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012067 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012068#endif
12069#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012070 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012071#endif
12072#undef HLUA_PREPEND_PATH_TOSTRING
12073#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012074
Thierry Fournier59f11be2020-11-29 00:37:41 +010012075 /* Apply configured prepend path */
12076 list_for_each_entry(pp, &prepend_path_list, l)
12077 hlua_prepend_path(L, pp->type, pp->path);
12078
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012079 /*
12080 *
12081 * Create "core" object.
12082 *
12083 */
12084
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012085 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012087
Thierry Fournierecb83c22020-11-28 15:49:44 +010012088 /* set the thread id */
12089 hlua_class_const_int(L, "thread", thread_num);
12090
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012091 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012092 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012093 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012094
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012095 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012096 hlua_class_function(L, "register_init", hlua_register_init);
12097 hlua_class_function(L, "register_task", hlua_register_task);
12098 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12099 hlua_class_function(L, "register_converters", hlua_register_converters);
12100 hlua_class_function(L, "register_action", hlua_register_action);
12101 hlua_class_function(L, "register_service", hlua_register_service);
12102 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012103 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012104 hlua_class_function(L, "yield", hlua_yield);
12105 hlua_class_function(L, "set_nice", hlua_set_nice);
12106 hlua_class_function(L, "sleep", hlua_sleep);
12107 hlua_class_function(L, "msleep", hlua_msleep);
12108 hlua_class_function(L, "add_acl", hlua_add_acl);
12109 hlua_class_function(L, "del_acl", hlua_del_acl);
12110 hlua_class_function(L, "set_map", hlua_set_map);
12111 hlua_class_function(L, "del_map", hlua_del_map);
12112 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012113 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012114 hlua_class_function(L, "log", hlua_log);
12115 hlua_class_function(L, "Debug", hlua_log_debug);
12116 hlua_class_function(L, "Info", hlua_log_info);
12117 hlua_class_function(L, "Warning", hlua_log_warning);
12118 hlua_class_function(L, "Alert", hlua_log_alert);
12119 hlua_class_function(L, "done", hlua_done);
12120 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012121
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012122 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012123
12124 /*
12125 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012126 * Create "act" object.
12127 *
12128 */
12129
12130 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012131 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012132
12133 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012134 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12135 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12136 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12137 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12138 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12139 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12140 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12141 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012142
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012143 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012144
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012145 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012146
12147 /*
12148 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012149 * Create "Filter" object.
12150 *
12151 */
12152
12153 /* This table entry is the object "filter" base. */
12154 lua_newtable(L);
12155
12156 /* push flags and constants */
12157 hlua_class_const_int(L, "CONTINUE", 1);
12158 hlua_class_const_int(L, "WAIT", 0);
12159 hlua_class_const_int(L, "ERROR", -1);
12160
12161 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12162
Christopher Fauletc404f112020-02-26 15:03:09 +010012163 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12164 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12165 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12166
Christopher Faulet69c581a2021-05-31 08:54:04 +020012167 lua_setglobal(L, "filter");
12168
12169 /*
12170 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012171 * Register class Map
12172 *
12173 */
12174
12175 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012176 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012177
12178 /* register pattern types. */
12179 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012181 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012182 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012183 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012184 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012185
12186 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012187 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012188
12189 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012190 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012191
Ilya Shipitsind4259502020-04-08 01:07:56 +050012192 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012193 lua_pushstring(L, "__index");
12194 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012195
12196 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012197 hlua_class_function(L, "lookup", hlua_map_lookup);
12198 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012199
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012201
Thierry Fournier45e78d72016-02-19 18:34:46 +010012202 /* Register previous table in the registry with reference and named entry.
12203 * The function hlua_register_metatable() pops the stack, so we
12204 * previously create a copy of the table.
12205 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012206 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12207 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012208
12209 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012210 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012211
12212 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012213 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012214
12215 /*
12216 *
William Lallemand30fcca12022-03-30 12:03:12 +020012217 * Register "CertCache" class
12218 *
12219 */
12220
12221 /* Create and fill the metatable. */
12222 lua_newtable(L);
12223 /* Register */
12224 hlua_class_function(L, "set", hlua_ckch_set);
12225 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12226
12227 /*
12228 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012229 * Register class Channel
12230 *
12231 */
12232
12233 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012234 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012235
Ilya Shipitsind4259502020-04-08 01:07:56 +050012236 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012237 lua_pushstring(L, "__index");
12238 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012239
12240 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012241 hlua_class_function(L, "data", hlua_channel_get_data);
12242 hlua_class_function(L, "line", hlua_channel_get_line);
12243 hlua_class_function(L, "set", hlua_channel_set_data);
12244 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012245 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012246 hlua_class_function(L, "prepend", hlua_channel_prepend);
12247 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012248 hlua_class_function(L, "send", hlua_channel_send);
12249 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012250 hlua_class_function(L, "input", hlua_channel_get_in_len);
12251 hlua_class_function(L, "output", hlua_channel_get_out_len);
12252 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012253 hlua_class_function(L, "is_full", hlua_channel_is_full);
12254 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012255
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012256 /* Deprecated API */
12257 hlua_class_function(L, "get", hlua_channel_get);
12258 hlua_class_function(L, "dup", hlua_channel_dup);
12259 hlua_class_function(L, "getline", hlua_channel_getline);
12260 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12261 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12262
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012263 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012264
12265 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012266 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012267
12268 /*
12269 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012270 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012271 *
12272 */
12273
12274 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012275 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012276
Ilya Shipitsind4259502020-04-08 01:07:56 +050012277 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012278 lua_pushstring(L, "__index");
12279 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012280
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012281 /* Browse existing fetches and create the associated
12282 * object method.
12283 */
12284 sf = NULL;
12285 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012286 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12287 * by an underscore.
12288 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012289 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012290 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012291 if (*p == '.' || *p == '-' || *p == '+')
12292 *p = '_';
12293
12294 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012295 lua_pushstring(L, trash.area);
12296 lua_pushlightuserdata(L, sf);
12297 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12298 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012299 }
12300
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012301 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012302
12303 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012304 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012305
12306 /*
12307 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012308 * Register class Converters
12309 *
12310 */
12311
12312 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012313 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012314
12315 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012316 lua_pushstring(L, "__index");
12317 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012318
12319 /* Browse existing converters and create the associated
12320 * object method.
12321 */
12322 sc = NULL;
12323 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012324 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12325 * by an underscore.
12326 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012327 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012328 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012329 if (*p == '.' || *p == '-' || *p == '+')
12330 *p = '_';
12331
12332 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012333 lua_pushstring(L, trash.area);
12334 lua_pushlightuserdata(L, sc);
12335 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12336 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012337 }
12338
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012339 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012340
12341 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012342 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012343
12344 /*
12345 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012346 * Register class HTTP
12347 *
12348 */
12349
12350 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012351 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012352
Ilya Shipitsind4259502020-04-08 01:07:56 +050012353 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012354 lua_pushstring(L, "__index");
12355 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012356
12357 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012358 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12359 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12360 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12361 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12362 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12363 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12364 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12365 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12366 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12367 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012368
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012369 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12370 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12371 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12372 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12373 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12374 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12375 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012376
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012377 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012378
12379 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012380 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012381
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012382 /*
12383 *
12384 * Register class HTTPMessage
12385 *
12386 */
12387
12388 /* Create and fill the metatable. */
12389 lua_newtable(L);
12390
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012391 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012392 lua_pushstring(L, "__index");
12393 lua_newtable(L);
12394
12395 /* Register Lua functions. */
12396 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12397 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12398 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12399 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12400 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12401 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12402 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12403 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12404 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12405 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12406 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12407 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12408 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12409 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12410 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12411 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12412 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12413 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12414
12415 hlua_class_function(L, "body", hlua_http_msg_get_body);
12416 hlua_class_function(L, "set", hlua_http_msg_set_data);
12417 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12418 hlua_class_function(L, "append", hlua_http_msg_append);
12419 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12420 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12421 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12422 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12423
12424 hlua_class_function(L, "send", hlua_http_msg_send);
12425 hlua_class_function(L, "forward", hlua_http_msg_forward);
12426
12427 lua_rawset(L, -3);
12428
12429 /* Register previous table in the registry with reference and named entry. */
12430 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012431
12432 /*
12433 *
12434 * Register class HTTPClient
12435 *
12436 */
12437
12438 /* Create and fill the metatable. */
12439 lua_newtable(L);
12440 lua_pushstring(L, "__index");
12441 lua_newtable(L);
12442 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012443 hlua_class_function(L, "head", hlua_httpclient_head);
12444 hlua_class_function(L, "put", hlua_httpclient_put);
12445 hlua_class_function(L, "post", hlua_httpclient_post);
12446 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012447 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012448 /* Register the garbage collector entry. */
12449 lua_pushstring(L, "__gc");
12450 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12451 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12452
William Lallemand3956c4e2021-09-21 16:25:15 +020012453
12454
12455 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012456 /*
12457 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012458 * Register class AppletTCP
12459 *
12460 */
12461
12462 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012463 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012464
Ilya Shipitsind4259502020-04-08 01:07:56 +050012465 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012466 lua_pushstring(L, "__index");
12467 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012468
12469 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012470 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12471 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12472 hlua_class_function(L, "send", hlua_applet_tcp_send);
12473 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12474 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12475 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12476 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12477 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012478
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012479 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012480
12481 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012482 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012483
12484 /*
12485 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012486 * Register class AppletHTTP
12487 *
12488 */
12489
12490 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012491 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012492
Ilya Shipitsind4259502020-04-08 01:07:56 +050012493 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012494 lua_pushstring(L, "__index");
12495 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012496
12497 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012498 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12499 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12500 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12501 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12502 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12503 hlua_class_function(L, "getline", hlua_applet_http_getline);
12504 hlua_class_function(L, "receive", hlua_applet_http_recv);
12505 hlua_class_function(L, "send", hlua_applet_http_send);
12506 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12507 hlua_class_function(L, "set_status", hlua_applet_http_status);
12508 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012509
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012510 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012511
12512 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012513 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012514
12515 /*
12516 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012517 * Register class TXN
12518 *
12519 */
12520
12521 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012522 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012523
Ilya Shipitsind4259502020-04-08 01:07:56 +050012524 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012525 lua_pushstring(L, "__index");
12526 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012527
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012528 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012529 hlua_class_function(L, "set_priv", hlua_set_priv);
12530 hlua_class_function(L, "get_priv", hlua_get_priv);
12531 hlua_class_function(L, "set_var", hlua_set_var);
12532 hlua_class_function(L, "unset_var", hlua_unset_var);
12533 hlua_class_function(L, "get_var", hlua_get_var);
12534 hlua_class_function(L, "done", hlua_txn_done);
12535 hlua_class_function(L, "reply", hlua_txn_reply_new);
12536 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12537 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12538 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12539 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12540 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12541 hlua_class_function(L, "deflog", hlua_txn_deflog);
12542 hlua_class_function(L, "log", hlua_txn_log);
12543 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12544 hlua_class_function(L, "Info", hlua_txn_log_info);
12545 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12546 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012547
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012548 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012549
12550 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012551 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012552
12553 /*
12554 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012555 * Register class reply
12556 *
12557 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012558 lua_newtable(L);
12559 lua_pushstring(L, "__index");
12560 lua_newtable(L);
12561 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12562 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12563 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12564 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12565 lua_settable(L, -3); /* Sets the __index entry. */
12566 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012567
12568
12569 /*
12570 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012571 * Register class Socket
12572 *
12573 */
12574
12575 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012576 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012577
Ilya Shipitsind4259502020-04-08 01:07:56 +050012578 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012579 lua_pushstring(L, "__index");
12580 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012581
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012582#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012583 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012584#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012585 hlua_class_function(L, "connect", hlua_socket_connect);
12586 hlua_class_function(L, "send", hlua_socket_send);
12587 hlua_class_function(L, "receive", hlua_socket_receive);
12588 hlua_class_function(L, "close", hlua_socket_close);
12589 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12590 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12591 hlua_class_function(L, "setoption", hlua_socket_setoption);
12592 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012593
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012594 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012595
12596 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012597 lua_pushstring(L, "__gc");
12598 lua_pushcclosure(L, hlua_socket_gc, 0);
12599 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012600
12601 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012602 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012603
Thierry Fournieraafc7772020-12-04 11:47:47 +010012604 lua_atpanic(L, hlua_panic_safe);
12605
12606 return L;
12607}
12608
12609void hlua_init(void) {
12610 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012611 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012612#ifdef USE_OPENSSL
12613 struct srv_kw *kw;
12614 int tmp_error;
12615 char *error;
12616 char *args[] = { /* SSL client configuration. */
12617 "ssl",
12618 "verify",
12619 "none",
12620 NULL
12621 };
12622#endif
12623
12624 /* Init post init function list head */
12625 for (i = 0; i < MAX_THREADS + 1; i++)
12626 LIST_INIT(&hlua_init_functions[i]);
12627
12628 /* Init state for common/shared lua parts */
12629 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012630 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012631 hlua_states[0] = hlua_init_state(0);
12632
12633 /* Init state 1 for thread 0. We have at least one thread. */
12634 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012635 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012636 hlua_states[1] = hlua_init_state(1);
12637
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012638 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012639 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012640 if (!socket_proxy) {
12641 fprintf(stderr, "Lua init: %s\n", errmsg);
12642 exit(1);
12643 }
12644 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012645
12646 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012647 socket_tcp = new_server(socket_proxy);
12648 if (!socket_tcp) {
12649 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12650 exit(1);
12651 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012652
12653#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012654 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012655 socket_ssl = new_server(socket_proxy);
12656 if (!socket_ssl) {
12657 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12658 exit(1);
12659 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012660
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012661 socket_ssl->use_ssl = 1;
12662 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012663
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012664 for (i = 0; args[i] != NULL; i++) {
12665 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012666 /*
12667 *
12668 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012669 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012670 * features like client certificates and ssl_verify.
12671 *
12672 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012673 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012674 if (tmp_error != 0) {
12675 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12676 abort(); /* This must be never arrives because the command line
12677 not editable by the user. */
12678 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012679 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012680 }
12681 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012682#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012683
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012684}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012685
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012686static void hlua_deinit()
12687{
Willy Tarreau186f3762020-12-04 11:48:12 +010012688 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012689 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12690
12691 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12692 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012693
12694 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12695 if (hlua_states[thr])
12696 lua_close(hlua_states[thr]);
12697 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012698
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012699 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012700
Willy Tarreau0f143af2021-03-05 10:41:48 +010012701#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012702 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012703#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012704
12705 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012706}
12707
12708REGISTER_POST_DEINIT(hlua_deinit);
12709
Willy Tarreau80713382018-11-26 10:19:54 +010012710static void hlua_register_build_options(void)
12711{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012712 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012713
Willy Tarreaubb57d942016-12-21 19:04:56 +010012714 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12715 hap_register_build_opts(ptr, 1);
12716}
Willy Tarreau80713382018-11-26 10:19:54 +010012717
12718INITCALL0(STG_REGISTER, hlua_register_build_options);