blob: 9b646bc20c5fbc8df29dcbaae7ec0796433be152 [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;
1282 LIST_DELETE(&hlua_hc->by_hlua);
1283 }
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);
1992 sc_ic(sc)->flags |= CF_READ_NULL;
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 Fauleta1ac5fb2021-08-09 10:22:46 +02003245 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003246 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3247 /* Yield waiting for more data, as requested */
3248 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3249 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003250 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003251 }
3252
3253 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003255 return 1;
3256}
3257
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003258/* Copies the first line (including the trailing LF) of input data in the
3259 * channel's buffer. It is possible to set a specific offset (0 by default) and
3260 * a length (all remaining input data starting for the offset by default). If
3261 * there is not enough input data and more data can be received, the function
3262 * yields. If a length is explicitly specified, no more data are
3263 * copied. Otherwise, if no LF is found and more data can be received, this
3264 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003265 *
3266 * From an action, All input data are considered. For a filter, the offset and
3267 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003268 */
3269__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003270{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003271 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003272 struct filter *filter;
3273 size_t l, input, output;
3274 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003275
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003276 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003277 output = co_data(chn);
3278 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003279
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003280 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3281 if (filter && !hlua_filter_from_payload(filter))
3282 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003283
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003284 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003285 if (lua_gettop(L) > 1) {
3286 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3287 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003288 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003289 offset += output;
3290 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003291 lua_pushfstring(L, "offset out of range.");
3292 WILL_LJMP(lua_error(L));
3293 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003294 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295
3296 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003297 if (lua_gettop(L) == 3) {
3298 len = MAY_LJMP(luaL_checkinteger(L, 3));
3299 if (!len)
3300 goto dup;
3301 if (len == -1)
3302 len = global.tune.bufsize;
3303 if (len < 0) {
3304 lua_pushfstring(L, "length out of range.");
3305 WILL_LJMP(lua_error(L));
3306 }
3307 }
3308
3309 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003310 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003311 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003312 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003313 len = l+1;
3314 goto dup;
3315 }
3316 }
3317
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003318 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003319 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3320 /* Yield waiting for more data */
3321 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3322 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003323 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003324 }
3325
3326 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003327 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003328 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003329}
3330
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003331/* [ DEPRECATED ]
3332 *
3333 * Duplicate all input data foud in the channel's buffer. The data are not
3334 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003335 *
3336 * From an action, All input data are considered. For a filter, the offset and
3337 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003338 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003339__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003341 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003342 struct filter *filter;
3343 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003344
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003346 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003347 if (IS_HTX_STRM(chn_strm(chn))) {
3348 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3349 WILL_LJMP(lua_error(L));
3350 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003351
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003352 offset = co_data(chn);
3353 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003355 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3356 if (filter && !hlua_filter_from_payload(filter))
3357 WILL_LJMP(lua_error(L));
3358
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003359 if (!ci_data(chn) && channel_input_closed(chn)) {
3360 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003361 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003362 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003363
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003364 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003365 return 1;
3366}
3367
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368/* [ DEPRECATED ]
3369 *
3370 * Get all input data foud in the channel's buffer. The data are removed from
3371 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3372 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003373 *
3374 * From an action, All input data are considered. For a filter, the offset and
3375 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003376 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003377__LJMP static int hlua_channel_get(lua_State *L)
3378{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003379 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003380 struct filter *filter;
3381 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003382 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003383
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003384 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003385 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3386 if (IS_HTX_STRM(chn_strm(chn))) {
3387 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3388 WILL_LJMP(lua_error(L));
3389 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003390
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003391 offset = co_data(chn);
3392 len = ci_data(chn);
3393
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003394 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3395 if (filter && !hlua_filter_from_payload(filter))
3396 WILL_LJMP(lua_error(L));
3397
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003398 if (!ci_data(chn) && channel_input_closed(chn)) {
3399 lua_pushnil(L);
3400 return 1;
3401 }
3402
3403 ret = _hlua_channel_dup(chn, L, offset, len);
3404 _hlua_channel_delete(chn, offset, ret);
3405 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003406}
3407
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003408/* This functions consumes and returns one line. If the channel is closed,
3409 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003410 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003412 *
3413 * From an action, All input data are considered. For a filter, the offset and
3414 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003415 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003416__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003417{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003418 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003419 struct filter *filter;
3420 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003421 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003422
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003423 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003424
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003425 offset = co_data(chn);
3426 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003427
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003428 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3429 if (filter && !hlua_filter_from_payload(filter))
3430 WILL_LJMP(lua_error(L));
3431
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003432 if (!ci_data(chn) && channel_input_closed(chn)) {
3433 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003434 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003435 }
3436
3437 for (l = 0; l < len; l++) {
3438 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3439 len = l+1;
3440 goto dup;
3441 }
3442 }
3443
3444 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3445 /* Yield waiting for more data */
3446 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3447 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003448
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003449 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003450 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003451 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003452 return 1;
3453}
3454
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003455/* [ DEPRECATED ]
3456 *
3457 * Check arguments for the function "hlua_channel_getline_yield".
3458 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003459__LJMP static int hlua_channel_getline(lua_State *L)
3460{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003461 struct channel *chn;
3462
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003463 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003464 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3465 if (IS_HTX_STRM(chn_strm(chn))) {
3466 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3467 WILL_LJMP(lua_error(L));
3468 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003469 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3470}
3471
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003472/* Retrieves a given amount of input data at the given offset. By default all
3473 * available input data are returned. The offset may be negactive to start from
3474 * the end of input data. The length may be -1 to set it to the maximum buffer
3475 * size.
3476 */
3477__LJMP static int hlua_channel_get_data(lua_State *L)
3478{
3479 struct channel *chn;
3480
3481 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3482 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3483 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3484 if (IS_HTX_STRM(chn_strm(chn))) {
3485 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3486 WILL_LJMP(lua_error(L));
3487 }
3488 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3489}
3490
3491/* Retrieves a given amount of input data at the given offset. By default all
3492 * available input data are returned. The offset may be negactive to start from
3493 * the end of input data. The length may be -1 to set it to the maximum buffer
3494 * size.
3495 */
3496__LJMP static int hlua_channel_get_line(lua_State *L)
3497{
3498 struct channel *chn;
3499
3500 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3501 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3502 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3503 if (IS_HTX_STRM(chn_strm(chn))) {
3504 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3505 WILL_LJMP(lua_error(L));
3506 }
3507 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3508}
3509
3510/* Appends a string into the input side of channel. It returns the length of the
3511 * written string, or -1 if the channel is closed or if the buffer size is too
3512 * little for the data. 0 may be returned if nothing is copied. This function
3513 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003514 *
3515 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003516 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003517__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003518{
Christopher Faulet23976d92021-08-06 09:59:49 +02003519 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003520 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003521 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003522 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003523 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003524
3525 MAY_LJMP(check_args(L, 2, "append"));
3526 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003527 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003528 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003529 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003530 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003531 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003532
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003533 offset = co_data(chn);
3534 len = ci_data(chn);
3535
3536 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3537 if (filter && !hlua_filter_from_payload(filter))
3538 WILL_LJMP(lua_error(L));
3539
3540 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3541 if (ret > 0 && filter) {
3542 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3543
3544 flt_update_offsets(filter, chn, ret);
3545 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3546 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003547 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003548 return 1;
3549}
3550
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003551/* Prepends a string into the input side of channel. It returns the length of the
3552 * written string, or -1 if the channel is closed or if the buffer size is too
3553 * little for the data. 0 may be returned if nothing is copied. This function
3554 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003555 *
3556 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003557 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003558__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003559{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003560 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003561 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003562 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003563 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003564 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003567 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003568 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3569 if (IS_HTX_STRM(chn_strm(chn))) {
3570 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3571 WILL_LJMP(lua_error(L));
3572 }
3573
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 offset = co_data(chn);
3575 len = ci_data(chn);
3576
3577 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3578 if (filter && !hlua_filter_from_payload(filter))
3579 WILL_LJMP(lua_error(L));
3580
3581 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3582 if (ret > 0 && filter) {
3583 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3584
3585 flt_update_offsets(filter, chn, ret);
3586 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3587 }
3588
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003589 lua_pushinteger(L, ret);
3590 return 1;
3591}
3592
3593/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003594 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003595 * returns the length of the written string, or -1 if the channel is closed or
3596 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 *
3598 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599 */
3600__LJMP static int hlua_channel_insert_data(lua_State *L)
3601{
3602 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003606 int ret, offset;
3607
3608 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3609 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3610 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3611 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003612
3613 output = co_data(chn);
3614 input = ci_data(chn);
3615
3616 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3617 if (filter && !hlua_filter_from_payload(filter))
3618 WILL_LJMP(lua_error(L));
3619
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003620 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003621 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003622 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003624 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003626 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003627 lua_pushfstring(L, "offset out of range.");
3628 WILL_LJMP(lua_error(L));
3629 }
3630 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003631 if (IS_HTX_STRM(chn_strm(chn))) {
3632 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3633 WILL_LJMP(lua_error(L));
3634 }
3635
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003636 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3637 if (ret > 0 && filter) {
3638 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003640 flt_update_offsets(filter, chn, ret);
3641 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003642 }
3643
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 lua_pushinteger(L, ret);
3645 return 1;
3646}
3647/* Replaces a given amount of input data at the given offset by a string
3648 * content. By default all remaining data are removed (offset = 0 and len =
3649 * -1). It returns the length of the written string, or -1 if the channel is
3650 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003651 *
3652 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003653 */
3654__LJMP static int hlua_channel_set_data(lua_State *L)
3655{
3656 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003658 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003659 size_t sz, input, output;
3660 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003661
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003662 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3663 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3664 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3665 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003667 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003668 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003669 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003670 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003671
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003672 output = co_data(chn);
3673 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003674
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003675 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3676 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003677 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003678
3679 offset = output;
3680 if (lua_gettop(L) > 2) {
3681 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3682 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003683 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003684 offset += output;
3685 if (offset < output || offset > input + output) {
3686 lua_pushfstring(L, "offset out of range.");
3687 WILL_LJMP(lua_error(L));
3688 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003689 }
3690
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003691 len = output + input - offset;
3692 if (lua_gettop(L) == 4) {
3693 len = MAY_LJMP(luaL_checkinteger(L, 4));
3694 if (!len)
3695 goto set;
3696 if (len == -1)
3697 len = output + input - offset;
3698 if (len < 0 || offset + len > output + input) {
3699 lua_pushfstring(L, "length out of range.");
3700 WILL_LJMP(lua_error(L));
3701 }
3702 }
3703
3704 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003705 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003707 lua_pushinteger(L, -1);
3708 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003709 _hlua_channel_delete(chn, offset, len);
3710 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3711 if (filter) {
3712 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3713
3714 len -= (ret > 0 ? ret : 0);
3715 flt_update_offsets(filter, chn, -len);
3716 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3717 }
3718
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003719 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003720 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003721 return 1;
3722}
3723
3724/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003725 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003726 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003727 *
3728 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003729 */
3730__LJMP static int hlua_channel_del_data(lua_State *L)
3731{
3732 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003733 struct filter *filter;
3734 size_t input, output;
3735 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003736
3737 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3738 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3739 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003740
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003741 if (IS_HTX_STRM(chn_strm(chn))) {
3742 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3743 WILL_LJMP(lua_error(L));
3744 }
3745
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003746 output = co_data(chn);
3747 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003748
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3750 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003751 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003752
3753 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003754 if (lua_gettop(L) > 1) {
3755 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003756 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003757 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 offset += output;
3759 if (offset < output || offset > input + output) {
3760 lua_pushfstring(L, "offset out of range.");
3761 WILL_LJMP(lua_error(L));
3762 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003763 }
3764
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003765 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003766 if (lua_gettop(L) == 3) {
3767 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003768 if (!len)
3769 goto end;
3770 if (len == -1)
3771 len = output + input - offset;
3772 if (len < 0 || offset + len > output + input) {
3773 lua_pushfstring(L, "length out of range.");
3774 WILL_LJMP(lua_error(L));
3775 }
3776 }
3777
3778 _hlua_channel_delete(chn, offset, len);
3779 if (filter) {
3780 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3781
3782 flt_update_offsets(filter, chn, -len);
3783 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3784 }
3785
3786 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003787 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003788 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003789}
3790
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003791/* Append data in the output side of the buffer. This data is immediately
3792 * sent. The function returns the amount of data written. If the buffer
3793 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003794 * if the channel is closed.
3795 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003796__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003797{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003798 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003799 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003800 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003801 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003803 struct hlua *hlua;
3804
3805 /* Get hlua struct, or NULL if we execute from main lua state */
3806 hlua = hlua_gethlua(L);
3807 if (!hlua) {
3808 lua_pushnil(L);
3809 return 1;
3810 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003811
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003812 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3813 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3814 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003815
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003816 offset = co_data(chn);
3817 len = ci_data(chn);
3818
3819 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3820 if (filter && !hlua_filter_from_payload(filter))
3821 WILL_LJMP(lua_error(L));
3822
3823
Willy Tarreau47860ed2015-03-10 14:07:50 +01003824 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003825 lua_pushinteger(L, -1);
3826 return 1;
3827 }
3828
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003829 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003830 if (len > sz -l) {
3831 if (filter) {
3832 lua_pushinteger(L, -1);
3833 return 1;
3834 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003835 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003836 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003837
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003839 if (ret == -1) {
3840 lua_pop(L, 1);
3841 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003842 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003843 }
3844 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003845 if (filter) {
3846 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3847
3848
3849 flt_update_offsets(filter, chn, ret);
3850 FLT_OFF(filter, chn) += ret;
3851 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3852 }
3853 else
3854 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003855
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003856 l += ret;
3857 lua_pop(L, 1);
3858 lua_pushinteger(L, l);
3859 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003860
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861 if (l < sz) {
3862 /* Yield only if the channel's output is not empty.
3863 * Otherwise it means we cannot add more data. */
3864 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003865 return 1;
3866
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003867 /* If we are waiting for space in the response buffer, we
3868 * must set the flag WAKERESWR. This flag required the task
3869 * wake up if any activity is detected on the response buffer.
3870 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003871 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003872 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003873 else
3874 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003875 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003876 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003877
3878 return 1;
3879}
3880
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003881/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003882 * yield the LUA process, and resume it without checking the
3883 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003884 *
3885 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003886 */
3887__LJMP static int hlua_channel_send(lua_State *L)
3888{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003889 struct channel *chn;
3890
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003891 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003892 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3893 if (IS_HTX_STRM(chn_strm(chn))) {
3894 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3895 WILL_LJMP(lua_error(L));
3896 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003897 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003898 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003899}
3900
3901/* This function forward and amount of butes. The data pass from
3902 * the input side of the buffer to the output side, and can be
3903 * forwarded. This function never fails.
3904 *
3905 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003906 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003908__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003909{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003910 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003911 struct filter *filter;
3912 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003913 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003914 struct hlua *hlua;
3915
3916 /* Get hlua struct, or NULL if we execute from main lua state */
3917 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003918 if (!hlua) {
3919 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003920 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003921 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003922
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003923 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003924 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003925 l = MAY_LJMP(luaL_checkinteger(L, -1));
3926
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927 offset = co_data(chn);
3928 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003929
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003930 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3931 if (filter && !hlua_filter_from_payload(filter))
3932 WILL_LJMP(lua_error(L));
3933
3934 max = fwd - l;
3935 if (max > len)
3936 max = len;
3937
3938 if (filter) {
3939 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3940
3941 FLT_OFF(filter, chn) += max;
3942 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3943 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3944 }
3945 else
3946 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003947
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003948 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003949 lua_pop(L, 1);
3950 lua_pushinteger(L, l);
3951
3952 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003953 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003954 /* The the input channel or the output channel are closed, we
3955 * must return the amount of data forwarded.
3956 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003957 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003958 return 1;
3959
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003960 /* If we are waiting for space data in the response buffer, we
3961 * must set the flag WAKERESWR. This flag required the task
3962 * wake up if any activity is detected on the response buffer.
3963 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003964 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003965 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003966 else
3967 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003968
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003969 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003970 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003971 }
3972
3973 return 1;
3974}
3975
3976/* Just check the input and prepare the stack for the previous
3977 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003978 *
3979 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003980 */
3981__LJMP static int hlua_channel_forward(lua_State *L)
3982{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003983 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003984
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003985 MAY_LJMP(check_args(L, 2, "forward"));
3986 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3987 if (IS_HTX_STRM(chn_strm(chn))) {
3988 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3989 WILL_LJMP(lua_error(L));
3990 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003991 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003992 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003993}
3994
3995/* Just returns the number of bytes available in the input
3996 * side of the buffer. This function never fails.
3997 */
3998__LJMP static int hlua_channel_get_in_len(lua_State *L)
3999{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004000 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004001 struct filter *filter;
4002 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004003
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004004 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004005 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004006
4007 output = co_data(chn);
4008 input = ci_data(chn);
4009 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4010 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4011 lua_pushinteger(L, input);
4012 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004013 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004014
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004015 lua_pushinteger(L, htx->data - co_data(chn));
4016 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004017 return 1;
4018}
4019
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004020/* Returns true if the channel is full. */
4021__LJMP static int hlua_channel_is_full(lua_State *L)
4022{
4023 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004024
4025 MAY_LJMP(check_args(L, 1, "is_full"));
4026 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004027 /* ignore the reserve, we are not on a producer side (ie in an
4028 * applet).
4029 */
4030 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004031 return 1;
4032}
4033
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004034/* Returns true if the channel may still receive data. */
4035__LJMP static int hlua_channel_may_recv(lua_State *L)
4036{
4037 struct channel *chn;
4038
4039 MAY_LJMP(check_args(L, 1, "may_recv"));
4040 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4041 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4042 return 1;
4043}
4044
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004045/* Returns true if the channel is the response channel. */
4046__LJMP static int hlua_channel_is_resp(lua_State *L)
4047{
4048 struct channel *chn;
4049
4050 MAY_LJMP(check_args(L, 1, "is_resp"));
4051 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4052
4053 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4054 return 1;
4055}
4056
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004057/* Just returns the number of bytes available in the output
4058 * side of the buffer. This function never fails.
4059 */
4060__LJMP static int hlua_channel_get_out_len(lua_State *L)
4061{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004062 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004063 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004064
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004065 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004066 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004067
4068 output = co_data(chn);
4069 input = ci_data(chn);
4070 hlua_channel_filter(L, 1, chn, &output, &input);
4071
4072 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004073 return 1;
4074}
4075
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004076/*
4077 *
4078 *
4079 * Class Fetches
4080 *
4081 *
4082 */
4083
4084/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004085 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004086 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004087__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004088{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004089 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004090}
4091
4092/* This function creates and push in the stack a fetch object according
4093 * with a current TXN.
4094 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004095static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004096{
Willy Tarreau7073c472015-04-06 11:15:40 +02004097 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004098
4099 /* Check stack size. */
4100 if (!lua_checkstack(L, 3))
4101 return 0;
4102
4103 /* Create the object: obj[0] = userdata.
4104 * Note that the base of the Fetches object is the
4105 * transaction object.
4106 */
4107 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004108 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004109 lua_rawseti(L, -2, 0);
4110
Willy Tarreau7073c472015-04-06 11:15:40 +02004111 hsmp->s = txn->s;
4112 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004113 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004114 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004115
4116 /* Pop a class sesison metatable and affect it to the userdata. */
4117 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4118 lua_setmetatable(L, -2);
4119
4120 return 1;
4121}
4122
4123/* This function is an LUA binding. It is called with each sample-fetch.
4124 * It uses closure argument to store the associated sample-fetch. It
4125 * returns only one argument or throws an error. An error is thrown
4126 * only if an error is encountered during the argument parsing. If
4127 * the "sample-fetch" function fails, nil is returned.
4128 */
4129__LJMP static int hlua_run_sample_fetch(lua_State *L)
4130{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004131 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004132 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004133 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004134 int i;
4135 struct sample smp;
4136
4137 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004138 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004140 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004141 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004142
Thierry FOURNIERca988662015-12-20 18:43:03 +01004143 /* Check execution authorization. */
4144 if (f->use & SMP_USE_HTTP_ANY &&
4145 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4146 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4147 "is not available in Lua services", f->kw);
4148 WILL_LJMP(lua_error(L));
4149 }
4150
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004151 /* Get extra arguments. */
4152 for (i = 0; i < lua_gettop(L) - 1; i++) {
4153 if (i >= ARGM_NBARGS)
4154 break;
4155 hlua_lua2arg(L, i + 2, &args[i]);
4156 }
4157 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004158 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004159
4160 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004161 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004162
4163 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004164 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004165 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004166 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004167 }
4168
4169 /* Initialise the sample. */
4170 memset(&smp, 0, sizeof(smp));
4171
4172 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004173 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004174 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004175 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004176 lua_pushstring(L, "");
4177 else
4178 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004179 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004180 }
4181
4182 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004183 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004184 hlua_smp2lua_str(L, &smp);
4185 else
4186 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004187
4188 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004189 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004190 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004191
4192 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004193 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004194 WILL_LJMP(lua_error(L));
4195 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004196}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004197
4198/*
4199 *
4200 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004201 * Class Converters
4202 *
4203 *
4204 */
4205
4206/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004207 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004209__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004211 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004212}
4213
4214/* This function creates and push in the stack a Converters object
4215 * according with a current TXN.
4216 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004217static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004218{
Willy Tarreau7073c472015-04-06 11:15:40 +02004219 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004220
4221 /* Check stack size. */
4222 if (!lua_checkstack(L, 3))
4223 return 0;
4224
4225 /* Create the object: obj[0] = userdata.
4226 * Note that the base of the Converters object is the
4227 * same than the TXN object.
4228 */
4229 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004230 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004231 lua_rawseti(L, -2, 0);
4232
Willy Tarreau7073c472015-04-06 11:15:40 +02004233 hsmp->s = txn->s;
4234 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004235 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004236 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004237
Willy Tarreau87b09662015-04-03 00:22:06 +02004238 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004239 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4240 lua_setmetatable(L, -2);
4241
4242 return 1;
4243}
4244
4245/* This function is an LUA binding. It is called with each converter.
4246 * It uses closure argument to store the associated converter. It
4247 * returns only one argument or throws an error. An error is thrown
4248 * only if an error is encountered during the argument parsing. If
4249 * the converter function function fails, nil is returned.
4250 */
4251__LJMP static int hlua_run_sample_conv(lua_State *L)
4252{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004253 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004254 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004255 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004256 int i;
4257 struct sample smp;
4258
4259 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004260 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004261
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004262 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004263 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004264
4265 /* Get extra arguments. */
4266 for (i = 0; i < lua_gettop(L) - 2; i++) {
4267 if (i >= ARGM_NBARGS)
4268 break;
4269 hlua_lua2arg(L, i + 3, &args[i]);
4270 }
4271 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004272 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004273
4274 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004275 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004276
4277 /* Run the special args checker. */
4278 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4279 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004280 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004281 }
4282
4283 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004284 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004285 if (!hlua_lua2smp(L, 2, &smp)) {
4286 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004287 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004288 }
4289
Willy Tarreau1777ea62016-03-10 16:15:46 +01004290 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4291
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004292 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004293 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004294 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004295 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004296 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004297 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004298 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4299 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004300 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004301 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004302 }
4303
4304 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004305 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004306 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004307 lua_pushstring(L, "");
4308 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004309 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004310 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004311 }
4312
4313 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004314 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004315 hlua_smp2lua_str(L, &smp);
4316 else
4317 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004318 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004319 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004320 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004321
4322 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004323 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004324 WILL_LJMP(lua_error(L));
4325 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004326}
4327
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004328/*
4329 *
4330 *
4331 * Class AppletTCP
4332 *
4333 *
4334 */
4335
4336/* Returns a struct hlua_txn if the stack entry "ud" is
4337 * a class stream, otherwise it throws an error.
4338 */
4339__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4340{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004341 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004342}
4343
4344/* This function creates and push in the stack an Applet object
4345 * according with a current TXN.
4346 */
4347static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4348{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004349 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004350 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004351 struct proxy *p;
4352
4353 ALREADY_CHECKED(s);
4354 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004355
4356 /* Check stack size. */
4357 if (!lua_checkstack(L, 3))
4358 return 0;
4359
4360 /* Create the object: obj[0] = userdata.
4361 * Note that the base of the Converters object is the
4362 * same than the TXN object.
4363 */
4364 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004365 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004366 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 luactx->appctx = ctx;
4368 luactx->htxn.s = s;
4369 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004370
4371 /* Create the "f" field that contains a list of fetches. */
4372 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004373 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004374 return 0;
4375 lua_settable(L, -3);
4376
4377 /* Create the "sf" field that contains a list of stringsafe fetches. */
4378 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004379 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004380 return 0;
4381 lua_settable(L, -3);
4382
4383 /* Create the "c" field that contains a list of converters. */
4384 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004385 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004386 return 0;
4387 lua_settable(L, -3);
4388
4389 /* Create the "sc" field that contains a list of stringsafe converters. */
4390 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004391 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004392 return 0;
4393 lua_settable(L, -3);
4394
4395 /* Pop a class stream metatable and affect it to the table. */
4396 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4397 lua_setmetatable(L, -2);
4398
4399 return 1;
4400}
4401
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004402__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4403{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004404 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004405 struct stream *s;
4406 const char *name;
4407 size_t len;
4408 struct sample smp;
4409
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004410 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4411 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004412
4413 /* It is useles to retrieve the stream, but this function
4414 * runs only in a stream context.
4415 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004416 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004417 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004418 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004419
4420 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004421 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004422 hlua_lua2smp(L, 3, &smp);
4423
4424 /* Store the sample in a variable. */
4425 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004426
4427 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4428 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4429 else
4430 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4431
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004432 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433}
4434
4435__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4436{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004437 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438 struct stream *s;
4439 const char *name;
4440 size_t len;
4441 struct sample smp;
4442
4443 MAY_LJMP(check_args(L, 2, "unset_var"));
4444
4445 /* It is useles to retrieve the stream, but this function
4446 * runs only in a stream context.
4447 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004448 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004449 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004450 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004451
4452 /* Unset the variable. */
4453 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004454 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4455 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004456}
4457
4458__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4459{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004460 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004461 struct stream *s;
4462 const char *name;
4463 size_t len;
4464 struct sample smp;
4465
4466 MAY_LJMP(check_args(L, 2, "get_var"));
4467
4468 /* It is useles to retrieve the stream, but this function
4469 * runs only in a stream context.
4470 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004471 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004472 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004473 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004474
4475 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004476 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004477 lua_pushnil(L);
4478 return 1;
4479 }
4480
4481 return hlua_smp2lua(L, &smp);
4482}
4483
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004484__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4485{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4487 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004488 struct hlua *hlua;
4489
4490 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004491 if (!s->hlua)
4492 return 0;
4493 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004494
4495 MAY_LJMP(check_args(L, 2, "set_priv"));
4496
4497 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004498 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004499
4500 /* Get and store new value. */
4501 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4502 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4503
4504 return 0;
4505}
4506
4507__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4508{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004509 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4510 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004511 struct hlua *hlua;
4512
4513 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004514 if (!s->hlua) {
4515 lua_pushnil(L);
4516 return 1;
4517 }
4518 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004519
4520 /* Push configuration index in the stack. */
4521 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4522
4523 return 1;
4524}
4525
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004526/* If expected data not yet available, it returns a yield. This function
4527 * consumes the data in the buffer. It returns a string containing the
4528 * data. This string can be empty.
4529 */
4530__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4531{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004532 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004533 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004534 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004535 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004536 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004537 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004538 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004539
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004540 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004541 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004542
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004543 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004545 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004546 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004547 }
4548
4549 /* End of data: commit the total strings and return. */
4550 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004551 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004552 return 1;
4553 }
4554
4555 /* Ensure that the block 2 length is usable. */
4556 if (ret == 1)
4557 len2 = 0;
4558
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004559 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004560 luaL_addlstring(&luactx->b, blk1, len1);
4561 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004562
4563 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004564 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004565 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 return 1;
4567}
4568
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004569/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004570__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4571{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004572 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004573
4574 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004575 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576
4577 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4578}
4579
4580/* If expected data not yet available, it returns a yield. This function
4581 * consumes the data in the buffer. It returns a string containing the
4582 * data. This string can be empty.
4583 */
4584__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4585{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004586 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004587 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004588 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004590 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004591 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004592 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004593 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004594
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004595 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004596 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004597
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004598 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004599 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004600 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004601 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602 }
4603
4604 /* End of data: commit the total strings and return. */
4605 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004606 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 return 1;
4608 }
4609
4610 /* Ensure that the block 2 length is usable. */
4611 if (ret == 1)
4612 len2 = 0;
4613
4614 if (len == -1) {
4615
4616 /* If len == -1, catenate all the data avalaile and
4617 * yield because we want to get all the data until
4618 * the end of data stream.
4619 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004620 luaL_addlstring(&luactx->b, blk1, len1);
4621 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004622 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004623 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004624 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004625
4626 } else {
4627
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004628 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004629 if (len1 > len)
4630 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004631 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004632 len -= len1;
4633
4634 /* Copy the second block. */
4635 if (len2 > len)
4636 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004637 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004638 len -= len2;
4639
4640 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004641 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004642
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004643 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004644 if (len > 0) {
4645 lua_pushinteger(L, len);
4646 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004647 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004648 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004649 }
4650
4651 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004652 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004653 return 1;
4654 }
4655
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004656 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004657 hlua_pusherror(L, "Lua: internal error");
4658 WILL_LJMP(lua_error(L));
4659 return 0;
4660}
4661
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004662/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004663__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4664{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004665 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004666 int len = -1;
4667
4668 if (lua_gettop(L) > 2)
4669 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4670 if (lua_gettop(L) >= 2) {
4671 len = MAY_LJMP(luaL_checkinteger(L, 2));
4672 lua_pop(L, 1);
4673 }
4674
4675 /* Confirm or set the required length */
4676 lua_pushinteger(L, len);
4677
4678 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004679 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004680
4681 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4682}
4683
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004684/* Append data in the output side of the buffer. This data is immediately
4685 * sent. The function returns the amount of data written. If the buffer
4686 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004687 * if the channel is closed.
4688 */
4689__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4690{
4691 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004692 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004693 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4694 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004695 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004696 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004697 int max;
4698
4699 /* Get the max amount of data which can write as input in the channel. */
4700 max = channel_recv_max(chn);
4701 if (max > (len - l))
4702 max = len - l;
4703
4704 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004705 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004706
4707 /* update counters. */
4708 l += max;
4709 lua_pop(L, 1);
4710 lua_pushinteger(L, l);
4711
4712 /* If some data is not send, declares the situation to the
4713 * applet, and returns a yield.
4714 */
4715 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004716 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004717 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004718 }
4719
4720 return 1;
4721}
4722
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004723/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004724 * yield the LUA process, and resume it without checking the
4725 * input arguments.
4726 */
4727__LJMP static int hlua_applet_tcp_send(lua_State *L)
4728{
4729 MAY_LJMP(check_args(L, 2, "send"));
4730 lua_pushinteger(L, 0);
4731
4732 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4733}
4734
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004735/*
4736 *
4737 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004738 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004739 *
4740 *
4741 */
4742
4743/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004744 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004745 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004746__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004748 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004749}
4750
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004751/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004752 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004753 * It relies on the caller to have already reserved the room in ctx->svcctx
4754 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004755 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004756static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004757{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004758 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004759 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004760 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004761 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004762 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004763 struct htx *htx;
4764 struct htx_blk *blk;
4765 struct htx_sl *sl;
4766 struct ist path;
4767 unsigned long long len = 0;
4768 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004769 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004770
4771 /* Check stack size. */
4772 if (!lua_checkstack(L, 3))
4773 return 0;
4774
4775 /* Create the object: obj[0] = userdata.
4776 * Note that the base of the Converters object is the
4777 * same than the TXN object.
4778 */
4779 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004780 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004781 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004782 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004783 http_ctx->status = 200; /* Default status code returned. */
4784 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004785 luactx->htxn.s = s;
4786 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004788 /* Create the "f" field that contains a list of fetches. */
4789 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004790 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004791 return 0;
4792 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004793
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004794 /* Create the "sf" field that contains a list of stringsafe fetches. */
4795 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004796 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004797 return 0;
4798 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004799
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004800 /* Create the "c" field that contains a list of converters. */
4801 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004803 return 0;
4804 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004805
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004806 /* Create the "sc" field that contains a list of stringsafe converters. */
4807 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004808 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004809 return 0;
4810 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004811
Christopher Fauleta2097962019-07-15 16:25:33 +02004812 htx = htxbuf(&s->req.buf);
4813 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004814 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004815 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004816
Christopher Fauleta2097962019-07-15 16:25:33 +02004817 /* Stores the request method. */
4818 lua_pushstring(L, "method");
4819 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4820 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004821
Christopher Fauleta2097962019-07-15 16:25:33 +02004822 /* Stores the http version. */
4823 lua_pushstring(L, "version");
4824 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4825 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004826
Christopher Fauleta2097962019-07-15 16:25:33 +02004827 /* creates an array of headers. hlua_http_get_headers() crates and push
4828 * the array on the top of the stack.
4829 */
4830 lua_pushstring(L, "headers");
4831 htxn.s = s;
4832 htxn.p = px;
4833 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004834 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004835 return 0;
4836 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004837
Amaury Denoyellec453f952021-07-06 11:40:12 +02004838 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4839 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004840 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004841 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004842
Christopher Fauleta2097962019-07-15 16:25:33 +02004843 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004844 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004845 q = p;
4846 while (q < end && *q != '?')
4847 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004848
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004849 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004850 lua_pushstring(L, "path");
4851 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004852 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004853
Christopher Fauleta2097962019-07-15 16:25:33 +02004854 /* Stores the query string. */
4855 lua_pushstring(L, "qs");
4856 if (*q == '?')
4857 q++;
4858 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004859 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004860 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004861
Christopher Fauleta2097962019-07-15 16:25:33 +02004862 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4863 struct htx_blk *blk = htx_get_blk(htx, pos);
4864 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004865
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004866 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004867 break;
4868 if (type == HTX_BLK_DATA)
4869 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004870 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004871 if (htx->extra != ULLONG_MAX)
4872 len += htx->extra;
4873
4874 /* Stores the request path. */
4875 lua_pushstring(L, "length");
4876 lua_pushinteger(L, len);
4877 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004878
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004879 /* Create an empty array of HTTP request headers. */
4880 lua_pushstring(L, "response");
4881 lua_newtable(L);
4882 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004883
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004884 /* Pop a class stream metatable and affect it to the table. */
4885 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4886 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004887
4888 return 1;
4889}
4890
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004891__LJMP static int hlua_applet_http_set_var(lua_State *L)
4892{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004893 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004894 struct stream *s;
4895 const char *name;
4896 size_t len;
4897 struct sample smp;
4898
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004899 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4900 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004901
4902 /* It is useles to retrieve the stream, but this function
4903 * runs only in a stream context.
4904 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004905 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004906 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004907 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004908
4909 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004910 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004911 hlua_lua2smp(L, 3, &smp);
4912
4913 /* Store the sample in a variable. */
4914 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004915
4916 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4917 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4918 else
4919 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4920
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004921 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922}
4923
4924__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4925{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004926 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927 struct stream *s;
4928 const char *name;
4929 size_t len;
4930 struct sample smp;
4931
4932 MAY_LJMP(check_args(L, 2, "unset_var"));
4933
4934 /* It is useles to retrieve the stream, but this function
4935 * runs only in a stream context.
4936 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004937 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004938 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004939 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004940
4941 /* Unset the variable. */
4942 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004943 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4944 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004945}
4946
4947__LJMP static int hlua_applet_http_get_var(lua_State *L)
4948{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004949 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004950 struct stream *s;
4951 const char *name;
4952 size_t len;
4953 struct sample smp;
4954
4955 MAY_LJMP(check_args(L, 2, "get_var"));
4956
4957 /* It is useles to retrieve the stream, but this function
4958 * runs only in a stream context.
4959 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004960 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004961 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004962 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004963
4964 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004965 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004966 lua_pushnil(L);
4967 return 1;
4968 }
4969
4970 return hlua_smp2lua(L, &smp);
4971}
4972
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004973__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4974{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4976 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004977 struct hlua *hlua;
4978
4979 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004980 if (!s->hlua)
4981 return 0;
4982 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004983
4984 MAY_LJMP(check_args(L, 2, "set_priv"));
4985
4986 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004987 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004988
4989 /* Get and store new value. */
4990 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4991 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4992
4993 return 0;
4994}
4995
4996__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4997{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004998 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4999 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005000 struct hlua *hlua;
5001
5002 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005003 if (!s->hlua) {
5004 lua_pushnil(L);
5005 return 1;
5006 }
5007 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005008
5009 /* Push configuration index in the stack. */
5010 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5011
5012 return 1;
5013}
5014
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005015/* If expected data not yet available, it returns a yield. This function
5016 * consumes the data in the buffer. It returns a string containing the
5017 * data. This string can be empty.
5018 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005019__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005020{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005021 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005022 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005023 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005024 struct htx *htx;
5025 struct htx_blk *blk;
5026 size_t count;
5027 int stop = 0;
5028
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005029 htx = htx_from_buf(&req->buf);
5030 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005031 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005032
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005033 while (count && !stop && blk) {
5034 enum htx_blk_type type = htx_get_blk_type(blk);
5035 uint32_t sz = htx_get_blksz(blk);
5036 struct ist v;
5037 uint32_t vlen;
5038 char *nl;
5039
5040 vlen = sz;
5041 if (vlen > count) {
5042 if (type != HTX_BLK_DATA)
5043 break;
5044 vlen = count;
5045 }
5046
5047 switch (type) {
5048 case HTX_BLK_UNUSED:
5049 break;
5050
5051 case HTX_BLK_DATA:
5052 v = htx_get_blk_value(htx, blk);
5053 v.len = vlen;
5054 nl = istchr(v, '\n');
5055 if (nl != NULL) {
5056 stop = 1;
5057 vlen = nl - v.ptr + 1;
5058 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005059 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005060 break;
5061
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005062 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005063 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005064 stop = 1;
5065 break;
5066
5067 default:
5068 break;
5069 }
5070
Willy Tarreau84240042022-02-28 16:51:23 +01005071 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 count -= vlen;
5073 if (sz == vlen)
5074 blk = htx_remove_blk(htx, blk);
5075 else {
5076 htx_cut_data_blk(htx, blk, vlen);
5077 break;
5078 }
5079 }
5080
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005081 /* The message was fully consumed and no more data are expected
5082 * (EOM flag set).
5083 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005084 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005085 stop = 1;
5086
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005087 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005088 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005089 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005090 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005091 }
5092
5093 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005094 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005095 return 1;
5096}
5097
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005098
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005099/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005100__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005101{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005102 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005103
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005104 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005105 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005106
Christopher Fauleta2097962019-07-15 16:25:33 +02005107 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005108}
5109
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005110/* If expected data not yet available, it returns a yield. This function
5111 * consumes the data in the buffer. It returns a string containing the
5112 * data. This string can be empty.
5113 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005114__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005115{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005116 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005117 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005118 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005119 struct htx *htx;
5120 struct htx_blk *blk;
5121 size_t count;
5122 int len;
5123
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005124 htx = htx_from_buf(&req->buf);
5125 len = MAY_LJMP(luaL_checkinteger(L, 2));
5126 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005127 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005128 while (count && len && blk) {
5129 enum htx_blk_type type = htx_get_blk_type(blk);
5130 uint32_t sz = htx_get_blksz(blk);
5131 struct ist v;
5132 uint32_t vlen;
5133
5134 vlen = sz;
5135 if (len > 0 && vlen > len)
5136 vlen = len;
5137 if (vlen > count) {
5138 if (type != HTX_BLK_DATA)
5139 break;
5140 vlen = count;
5141 }
5142
5143 switch (type) {
5144 case HTX_BLK_UNUSED:
5145 break;
5146
5147 case HTX_BLK_DATA:
5148 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005149 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005150 break;
5151
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005152 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005153 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005154 len = 0;
5155 break;
5156
5157 default:
5158 break;
5159 }
5160
Willy Tarreau84240042022-02-28 16:51:23 +01005161 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005162 count -= vlen;
5163 if (len > 0)
5164 len -= vlen;
5165 if (sz == vlen)
5166 blk = htx_remove_blk(htx, blk);
5167 else {
5168 htx_cut_data_blk(htx, blk, vlen);
5169 break;
5170 }
5171 }
5172
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005173 /* The message was fully consumed and no more data are expected
5174 * (EOM flag set).
5175 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005176 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005177 len = 0;
5178
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005179 htx_to_buf(htx, &req->buf);
5180
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005181 /* If we are no other data available, yield waiting for new data. */
5182 if (len) {
5183 if (len > 0) {
5184 lua_pushinteger(L, len);
5185 lua_replace(L, 2);
5186 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005187 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005188 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005189 }
5190
5191 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005192 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005193 return 1;
5194}
5195
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005196/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005197__LJMP static int hlua_applet_http_recv(lua_State *L)
5198{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005199 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005200 int len = -1;
5201
5202 /* Check arguments. */
5203 if (lua_gettop(L) > 2)
5204 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5205 if (lua_gettop(L) >= 2) {
5206 len = MAY_LJMP(luaL_checkinteger(L, 2));
5207 lua_pop(L, 1);
5208 }
5209
Christopher Fauleta2097962019-07-15 16:25:33 +02005210 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005211
Christopher Fauleta2097962019-07-15 16:25:33 +02005212 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005213 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005214
Christopher Fauleta2097962019-07-15 16:25:33 +02005215 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005216}
5217
5218/* Append data in the output side of the buffer. This data is immediately
5219 * sent. The function returns the amount of data written. If the buffer
5220 * cannot contain the data, the function yields. The function returns -1
5221 * if the channel is closed.
5222 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005223__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005224{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005225 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005226 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005227 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005228 struct htx *htx = htx_from_buf(&res->buf);
5229 const char *data;
5230 size_t len;
5231 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5232 int max;
5233
Christopher Faulet9060fc02019-07-03 11:39:30 +02005234 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005235 if (!max)
5236 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005237
5238 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5239
5240 /* Get the max amount of data which can write as input in the channel. */
5241 if (max > (len - l))
5242 max = len - l;
5243
5244 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005245 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005246 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005247
5248 /* update counters. */
5249 l += max;
5250 lua_pop(L, 1);
5251 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005252
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005253 /* If some data is not send, declares the situation to the
5254 * applet, and returns a yield.
5255 */
5256 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005257 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005258 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005259 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005260 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005261 }
5262
Christopher Fauleta2097962019-07-15 16:25:33 +02005263 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005264 return 1;
5265}
5266
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005267/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268 * yield the LUA process, and resume it without checking the
5269 * input arguments.
5270 */
5271__LJMP static int hlua_applet_http_send(lua_State *L)
5272{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005273 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005274 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005275
5276 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005277 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005278 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5279 WILL_LJMP(lua_error(L));
5280 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005281
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005282 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005283 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005284
Christopher Fauleta2097962019-07-15 16:25:33 +02005285 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005286}
5287
5288__LJMP static int hlua_applet_http_addheader(lua_State *L)
5289{
5290 const char *name;
5291 int ret;
5292
5293 MAY_LJMP(hlua_checkapplet_http(L, 1));
5294 name = MAY_LJMP(luaL_checkstring(L, 2));
5295 MAY_LJMP(luaL_checkstring(L, 3));
5296
5297 /* Push in the stack the "response" entry. */
5298 ret = lua_getfield(L, 1, "response");
5299 if (ret != LUA_TTABLE) {
5300 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5301 "is expected as an array. %s found", lua_typename(L, ret));
5302 WILL_LJMP(lua_error(L));
5303 }
5304
5305 /* check if the header is already registered if it is not
5306 * the case, register it.
5307 */
5308 ret = lua_getfield(L, -1, name);
5309 if (ret == LUA_TNIL) {
5310
5311 /* Entry not found. */
5312 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5313
5314 /* Insert the new header name in the array in the top of the stack.
5315 * It left the new array in the top of the stack.
5316 */
5317 lua_newtable(L);
5318 lua_pushvalue(L, 2);
5319 lua_pushvalue(L, -2);
5320 lua_settable(L, -4);
5321
5322 } else if (ret != LUA_TTABLE) {
5323
5324 /* corruption error. */
5325 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5326 "is expected as an array. %s found", name, lua_typename(L, ret));
5327 WILL_LJMP(lua_error(L));
5328 }
5329
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005330 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005331 * the header value as new entry.
5332 */
5333 lua_pushvalue(L, 3);
5334 ret = lua_rawlen(L, -2);
5335 lua_rawseti(L, -2, ret + 1);
5336 lua_pushboolean(L, 1);
5337 return 1;
5338}
5339
5340__LJMP static int hlua_applet_http_status(lua_State *L)
5341{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005342 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005343 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005344 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005345 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005346
5347 if (status < 100 || status > 599) {
5348 lua_pushboolean(L, 0);
5349 return 1;
5350 }
5351
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005352 http_ctx->status = status;
5353 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005354 lua_pushboolean(L, 1);
5355 return 1;
5356}
5357
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005358
Christopher Fauleta2097962019-07-15 16:25:33 +02005359__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005361 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005362 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005363 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005364 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005365 struct htx *htx;
5366 struct htx_sl *sl;
5367 struct h1m h1m;
5368 const char *status, *reason;
5369 const char *name, *value;
5370 size_t nlen, vlen;
5371 unsigned int flags;
5372
5373 /* Send the message at once. */
5374 htx = htx_from_buf(&res->buf);
5375 h1m_init_res(&h1m);
5376
5377 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005378 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5379 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005381 reason = http_get_reason(http_ctx->status);
5382 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005383 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5384 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5385 }
5386 else {
5387 flags = HTX_SL_F_IS_RESP;
5388 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5389 }
5390 if (!sl) {
5391 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005392 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005393 WILL_LJMP(lua_error(L));
5394 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005395 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005396
5397 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005398 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5399 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005400 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005401 WILL_LJMP(lua_error(L));
5402 }
5403
5404 /* Browse the list of headers. */
5405 lua_pushnil(L);
5406 while(lua_next(L, -2) != 0) {
5407 /* We expect a string as -2. */
5408 if (lua_type(L, -2) != LUA_TSTRING) {
5409 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005410 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005411 lua_typename(L, lua_type(L, -2)));
5412 WILL_LJMP(lua_error(L));
5413 }
5414 name = lua_tolstring(L, -2, &nlen);
5415
5416 /* We expect an array as -1. */
5417 if (lua_type(L, -1) != LUA_TTABLE) {
5418 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 +02005419 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005420 name,
5421 lua_typename(L, lua_type(L, -1)));
5422 WILL_LJMP(lua_error(L));
5423 }
5424
5425 /* Browse the table who is on the top of the stack. */
5426 lua_pushnil(L);
5427 while(lua_next(L, -2) != 0) {
5428 int id;
5429
5430 /* We expect a number as -2. */
5431 if (lua_type(L, -2) != LUA_TNUMBER) {
5432 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 +02005433 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005434 name,
5435 lua_typename(L, lua_type(L, -2)));
5436 WILL_LJMP(lua_error(L));
5437 }
5438 id = lua_tointeger(L, -2);
5439
5440 /* We expect a string as -2. */
5441 if (lua_type(L, -1) != LUA_TSTRING) {
5442 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 +02005443 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444 name, id,
5445 lua_typename(L, lua_type(L, -1)));
5446 WILL_LJMP(lua_error(L));
5447 }
5448 value = lua_tolstring(L, -1, &vlen);
5449
5450 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005451 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5452 int ret;
5453
5454 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5455 if (ret < 0) {
5456 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5457 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5458 name);
5459 WILL_LJMP(lua_error(L));
5460 }
5461 else if (ret == 0)
5462 goto next; /* Skip it */
5463 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005464 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5465 struct ist v = ist2(value, vlen);
5466 int ret;
5467
5468 ret = h1_parse_cont_len_header(&h1m, &v);
5469 if (ret < 0) {
5470 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005471 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005472 name);
5473 WILL_LJMP(lua_error(L));
5474 }
5475 else if (ret == 0)
5476 goto next; /* Skip it */
5477 }
5478
5479 /* Add a new header */
5480 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5481 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005482 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483 name);
5484 WILL_LJMP(lua_error(L));
5485 }
5486 next:
5487 /* Remove the array from the stack, and get next element with a remaining string. */
5488 lua_pop(L, 1);
5489 }
5490
5491 /* Remove the array from the stack, and get next element with a remaining string. */
5492 lua_pop(L, 1);
5493 }
5494
5495 if (h1m.flags & H1_MF_CHNK)
5496 h1m.flags &= ~H1_MF_CLEN;
5497 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5498 h1m.flags |= H1_MF_XFER_LEN;
5499
5500 /* Uset HTX start-line flags */
5501 if (h1m.flags & H1_MF_XFER_ENC)
5502 flags |= HTX_SL_F_XFER_ENC;
5503 if (h1m.flags & H1_MF_XFER_LEN) {
5504 flags |= HTX_SL_F_XFER_LEN;
5505 if (h1m.flags & H1_MF_CHNK)
5506 flags |= HTX_SL_F_CHNK;
5507 else if (h1m.flags & H1_MF_CLEN)
5508 flags |= HTX_SL_F_CLEN;
5509 if (h1m.body_len == 0)
5510 flags |= HTX_SL_F_BODYLESS;
5511 }
5512 sl->flags |= flags;
5513
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005514 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005515 * and the status code implies the presence of a message body, we must
5516 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005517 * for the keepalive compliance. If the applet announces a transfer-encoding
5518 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005519 */
5520 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005521 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005522 /* Add a new header */
5523 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5524 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5525 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005526 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005527 WILL_LJMP(lua_error(L));
5528 }
5529 }
5530
5531 /* Finalize headers. */
5532 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5533 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005534 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005535 WILL_LJMP(lua_error(L));
5536 }
5537
5538 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5539 b_reset(&res->buf);
5540 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5541 WILL_LJMP(lua_error(L));
5542 }
5543
5544 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005545 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005546
5547 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005548 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549 return 0;
5550
5551}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005552/* We will build the status line and the headers of the HTTP response.
5553 * We will try send at once if its not possible, we give back the hand
5554 * waiting for more room.
5555 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005556__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005557{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005558 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005559 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005560 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005561
5562 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005563 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005564 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005565 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005566 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005567}
5568
5569
Christopher Fauleta2097962019-07-15 16:25:33 +02005570__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005571{
Christopher Fauleta2097962019-07-15 16:25:33 +02005572 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005573}
5574
Christopher Fauleta2097962019-07-15 16:25:33 +02005575/*
5576 *
5577 *
5578 * Class HTTP
5579 *
5580 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005581 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005582
5583/* Returns a struct hlua_txn if the stack entry "ud" is
5584 * a class stream, otherwise it throws an error.
5585 */
5586__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005587{
Christopher Fauleta2097962019-07-15 16:25:33 +02005588 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5589}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005590
Christopher Fauleta2097962019-07-15 16:25:33 +02005591/* This function creates and push in the stack a HTTP object
5592 * according with a current TXN.
5593 */
5594static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5595{
5596 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005597
Christopher Fauleta2097962019-07-15 16:25:33 +02005598 /* Check stack size. */
5599 if (!lua_checkstack(L, 3))
5600 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005601
Christopher Fauleta2097962019-07-15 16:25:33 +02005602 /* Create the object: obj[0] = userdata.
5603 * Note that the base of the Converters object is the
5604 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005605 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005606 lua_newtable(L);
5607 htxn = lua_newuserdata(L, sizeof(*htxn));
5608 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005609
5610 htxn->s = txn->s;
5611 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005612 htxn->dir = txn->dir;
5613 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005614
5615 /* Pop a class stream metatable and affect it to the table. */
5616 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5617 lua_setmetatable(L, -2);
5618
5619 return 1;
5620}
5621
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005622/* This function creates and returns an array containing the status-line
5623 * elements. This function does not fails.
5624 */
5625__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5626{
5627 /* Create the table. */
5628 lua_newtable(L);
5629
5630 if (sl->flags & HTX_SL_F_IS_RESP) {
5631 lua_pushstring(L, "version");
5632 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5633 lua_settable(L, -3);
5634 lua_pushstring(L, "code");
5635 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5636 lua_settable(L, -3);
5637 lua_pushstring(L, "reason");
5638 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5639 lua_settable(L, -3);
5640 }
5641 else {
5642 lua_pushstring(L, "method");
5643 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5644 lua_settable(L, -3);
5645 lua_pushstring(L, "uri");
5646 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5647 lua_settable(L, -3);
5648 lua_pushstring(L, "version");
5649 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5650 lua_settable(L, -3);
5651 }
5652 return 1;
5653}
5654
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005655/* This function creates ans returns an array of HTTP headers.
5656 * This function does not fails. It is used as wrapper with the
5657 * 2 following functions.
5658 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005659__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005660{
Christopher Fauleta2097962019-07-15 16:25:33 +02005661 struct htx *htx;
5662 int32_t pos;
5663
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005664 /* Create the table. */
5665 lua_newtable(L);
5666
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005667
Christopher Fauleta2097962019-07-15 16:25:33 +02005668 htx = htxbuf(&msg->chn->buf);
5669 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5670 struct htx_blk *blk = htx_get_blk(htx, pos);
5671 enum htx_blk_type type = htx_get_blk_type(blk);
5672 struct ist n, v;
5673 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005674
Christopher Fauleta2097962019-07-15 16:25:33 +02005675 if (type == HTX_BLK_HDR) {
5676 n = htx_get_blk_name(htx,blk);
5677 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005678 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005679 else if (type == HTX_BLK_EOH)
5680 break;
5681 else
5682 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005683
Christopher Fauleta2097962019-07-15 16:25:33 +02005684 /* Check for existing entry:
5685 * assume that the table is on the top of the stack, and
5686 * push the key in the stack, the function lua_gettable()
5687 * perform the lookup.
5688 */
5689 lua_pushlstring(L, n.ptr, n.len);
5690 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005691
Christopher Fauleta2097962019-07-15 16:25:33 +02005692 switch (lua_type(L, -1)) {
5693 case LUA_TNIL:
5694 /* Table not found, create it. */
5695 lua_pop(L, 1); /* remove the nil value. */
5696 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5697 lua_newtable(L); /* create and push empty table. */
5698 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5699 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5700 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005701 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005702
Christopher Fauleta2097962019-07-15 16:25:33 +02005703 case LUA_TTABLE:
5704 /* Entry found: push the value in the table. */
5705 len = lua_rawlen(L, -1);
5706 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5707 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5708 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5709 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005710
Christopher Fauleta2097962019-07-15 16:25:33 +02005711 default:
5712 /* Other cases are errors. */
5713 hlua_pusherror(L, "internal error during the parsing of headers.");
5714 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005715 }
5716 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005717 return 1;
5718}
5719
5720__LJMP static int hlua_http_req_get_headers(lua_State *L)
5721{
5722 struct hlua_txn *htxn;
5723
5724 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5725 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5726
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005727 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005728 WILL_LJMP(lua_error(L));
5729
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005730 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005731}
5732
5733__LJMP static int hlua_http_res_get_headers(lua_State *L)
5734{
5735 struct hlua_txn *htxn;
5736
5737 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5738 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5739
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005740 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005741 WILL_LJMP(lua_error(L));
5742
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005743 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005744}
5745
5746/* This function replace full header, or just a value in
5747 * the request or in the response. It is a wrapper fir the
5748 * 4 following functions.
5749 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005750__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005751{
5752 size_t name_len;
5753 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5754 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5755 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005756 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005757 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005758
Dragan Dosen26743032019-04-30 15:54:36 +02005759 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005760 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5761
Christopher Fauleta2097962019-07-15 16:25:33 +02005762 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005763 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005764 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005765 return 0;
5766}
5767
5768__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5769{
5770 struct hlua_txn *htxn;
5771
5772 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5773 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5774
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005775 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005776 WILL_LJMP(lua_error(L));
5777
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005778 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005779}
5780
5781__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5782{
5783 struct hlua_txn *htxn;
5784
5785 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5786 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5787
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005788 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005789 WILL_LJMP(lua_error(L));
5790
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005791 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005792}
5793
5794__LJMP static int hlua_http_req_rep_val(lua_State *L)
5795{
5796 struct hlua_txn *htxn;
5797
5798 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5799 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5800
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005801 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005802 WILL_LJMP(lua_error(L));
5803
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005804 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005805}
5806
5807__LJMP static int hlua_http_res_rep_val(lua_State *L)
5808{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005809 struct hlua_txn *htxn;
5810
5811 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5812 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5813
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005814 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005815 WILL_LJMP(lua_error(L));
5816
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005817 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005818}
5819
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005820/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005821 * It is a wrapper for the 2 following functions.
5822 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005823__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005824{
5825 size_t len;
5826 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005827 struct htx *htx = htxbuf(&msg->chn->buf);
5828 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005829
Christopher Fauleta2097962019-07-15 16:25:33 +02005830 ctx.blk = NULL;
5831 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5832 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005833 return 0;
5834}
5835
5836__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5837{
5838 struct hlua_txn *htxn;
5839
5840 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5841 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5842
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005843 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005844 WILL_LJMP(lua_error(L));
5845
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005846 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005847}
5848
5849__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5850{
5851 struct hlua_txn *htxn;
5852
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005853 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005854 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5855
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005856 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005857 WILL_LJMP(lua_error(L));
5858
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005859 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005860}
5861
5862/* This function adds an header. It is a wrapper used by
5863 * the 2 following functions.
5864 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005865__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005866{
5867 size_t name_len;
5868 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5869 size_t value_len;
5870 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005871 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005872
Christopher Fauleta2097962019-07-15 16:25:33 +02005873 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5874 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005875 return 0;
5876}
5877
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005878__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5879{
5880 struct hlua_txn *htxn;
5881
5882 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5883 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5884
5885 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5886 WILL_LJMP(lua_error(L));
5887
5888 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5889}
5890
5891__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5892{
5893 struct hlua_txn *htxn;
5894
5895 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5896 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5897
5898 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5899 WILL_LJMP(lua_error(L));
5900
5901 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5902}
5903
5904static int hlua_http_req_set_hdr(lua_State *L)
5905{
5906 struct hlua_txn *htxn;
5907
5908 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5909 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5910
5911 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5912 WILL_LJMP(lua_error(L));
5913
5914 hlua_http_del_hdr(L, &htxn->s->txn->req);
5915 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5916}
5917
5918static int hlua_http_res_set_hdr(lua_State *L)
5919{
5920 struct hlua_txn *htxn;
5921
5922 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5923 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5924
5925 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5926 WILL_LJMP(lua_error(L));
5927
5928 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5929 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5930}
5931
5932/* This function set the method. */
5933static int hlua_http_req_set_meth(lua_State *L)
5934{
5935 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5936 size_t name_len;
5937 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5938
5939 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5940 WILL_LJMP(lua_error(L));
5941
5942 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5943 return 1;
5944}
5945
5946/* This function set the method. */
5947static int hlua_http_req_set_path(lua_State *L)
5948{
5949 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5950 size_t name_len;
5951 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5952
5953 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5954 WILL_LJMP(lua_error(L));
5955
5956 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5957 return 1;
5958}
5959
5960/* This function set the query-string. */
5961static int hlua_http_req_set_query(lua_State *L)
5962{
5963 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5964 size_t name_len;
5965 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5966
5967 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5968 WILL_LJMP(lua_error(L));
5969
5970 /* Check length. */
5971 if (name_len > trash.size - 1) {
5972 lua_pushboolean(L, 0);
5973 return 1;
5974 }
5975
5976 /* Add the mark question as prefix. */
5977 chunk_reset(&trash);
5978 trash.area[trash.data++] = '?';
5979 memcpy(trash.area + trash.data, name, name_len);
5980 trash.data += name_len;
5981
5982 lua_pushboolean(L,
5983 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5984 return 1;
5985}
5986
5987/* This function set the uri. */
5988static int hlua_http_req_set_uri(lua_State *L)
5989{
5990 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5991 size_t name_len;
5992 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5993
5994 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5995 WILL_LJMP(lua_error(L));
5996
5997 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5998 return 1;
5999}
6000
6001/* This function set the response code & optionally reason. */
6002static int hlua_http_res_set_status(lua_State *L)
6003{
6004 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6005 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6006 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6007 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6008
6009 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6010 WILL_LJMP(lua_error(L));
6011
6012 http_res_set_status(code, reason, htxn->s);
6013 return 0;
6014}
6015
6016/*
6017 *
6018 *
6019 * Class HTTPMessage
6020 *
6021 *
6022 */
6023
6024/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6025 * otherwise it throws an error.
6026 */
6027__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6028{
6029 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6030}
6031
6032/* Creates and pushes on the stack a HTTP object according with a current TXN.
6033 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006034static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006035{
6036 /* Check stack size. */
6037 if (!lua_checkstack(L, 3))
6038 return 0;
6039
6040 lua_newtable(L);
6041 lua_pushlightuserdata(L, msg);
6042 lua_rawseti(L, -2, 0);
6043
6044 /* Create the "channel" field that contains the request channel object. */
6045 lua_pushstring(L, "channel");
6046 if (!hlua_channel_new(L, msg->chn))
6047 return 0;
6048 lua_rawset(L, -3);
6049
6050 /* Pop a class stream metatable and affect it to the table. */
6051 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6052 lua_setmetatable(L, -2);
6053
6054 return 1;
6055}
6056
6057/* Helper function returning a filter attached to the HTTP message at the
6058 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006059 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006060 * filled with output and input length respectively.
6061 */
6062static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6063{
6064 struct channel *chn = msg->chn;
6065 struct htx *htx = htxbuf(&chn->buf);
6066 struct filter *filter = NULL;
6067
6068 *offset = co_data(msg->chn);
6069 *len = htx->data - co_data(msg->chn);
6070
6071 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6072 filter = lua_touserdata (L, -1);
6073 if (msg->msg_state >= HTTP_MSG_DATA) {
6074 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6075
6076 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6077 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6078 }
6079 }
6080
6081 lua_pop(L, 1);
6082 return filter;
6083}
6084
6085/* Returns true if the channel attached to the HTTP message is the response
6086 * channel.
6087 */
6088__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6089{
6090 struct http_msg *msg;
6091
6092 MAY_LJMP(check_args(L, 1, "is_resp"));
6093 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6094
6095 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6096 return 1;
6097}
6098
6099/* Returns an array containing the elements status-line of the HTTP message. It relies
6100 * on hlua_http_get_stline().
6101 */
6102__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6103{
6104 struct http_msg *msg;
6105 struct htx *htx;
6106 struct htx_sl *sl;
6107
6108 MAY_LJMP(check_args(L, 1, "get_stline"));
6109 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6110
6111 if (msg->msg_state > HTTP_MSG_BODY)
6112 WILL_LJMP(lua_error(L));
6113
6114 htx = htxbuf(&msg->chn->buf);
6115 sl = http_get_stline(htx);
6116 if (!sl)
6117 return 0;
6118 return hlua_http_get_stline(L, sl);
6119}
6120
6121/* Returns an array containing all headers of the HTTP message. it relies on
6122 * hlua_http_get_headers().
6123 */
6124__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6125{
6126 struct http_msg *msg;
6127
6128 MAY_LJMP(check_args(L, 1, "get_headers"));
6129 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6130
6131 if (msg->msg_state > HTTP_MSG_BODY)
6132 WILL_LJMP(lua_error(L));
6133
6134 return hlua_http_get_headers(L, msg);
6135}
6136
6137/* Deletes all occurrences of an header in the HTTP message matching on its
6138 * name. It relies on hlua_http_del_hdr().
6139 */
6140__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6141{
6142 struct http_msg *msg;
6143
6144 MAY_LJMP(check_args(L, 2, "del_header"));
6145 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6146
6147 if (msg->msg_state > HTTP_MSG_BODY)
6148 WILL_LJMP(lua_error(L));
6149
6150 return hlua_http_del_hdr(L, msg);
6151}
6152
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006153/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006154 * message given its name against a regex and replaces it if it matches. It
6155 * relies on hlua_http_rep_hdr().
6156 */
6157__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6158{
6159 struct http_msg *msg;
6160
6161 MAY_LJMP(check_args(L, 4, "rep_header"));
6162 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6163
6164 if (msg->msg_state > HTTP_MSG_BODY)
6165 WILL_LJMP(lua_error(L));
6166
6167 return hlua_http_rep_hdr(L, msg, 1);
6168}
6169
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006170/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006171 * message given its name against a regex and replaces it if it matches. It
6172 * relies on hlua_http_rep_hdr().
6173 */
6174__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6175{
6176 struct http_msg *msg;
6177
6178 MAY_LJMP(check_args(L, 4, "rep_value"));
6179 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6180
6181 if (msg->msg_state > HTTP_MSG_BODY)
6182 WILL_LJMP(lua_error(L));
6183
6184 return hlua_http_rep_hdr(L, msg, 0);
6185}
6186
6187/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6188__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6189{
6190 struct http_msg *msg;
6191
6192 MAY_LJMP(check_args(L, 3, "add_header"));
6193 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6194
6195 if (msg->msg_state > HTTP_MSG_BODY)
6196 WILL_LJMP(lua_error(L));
6197
6198 return hlua_http_add_hdr(L, msg);
6199}
6200
6201/* Add an header in the HTTP message removing existing headers with the same
6202 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6203 */
6204__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6205{
6206 struct http_msg *msg;
6207
6208 MAY_LJMP(check_args(L, 3, "set_header"));
6209 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6210
6211 if (msg->msg_state > HTTP_MSG_BODY)
6212 WILL_LJMP(lua_error(L));
6213
6214 hlua_http_del_hdr(L, msg);
6215 return hlua_http_add_hdr(L, msg);
6216}
6217
6218/* Rewrites the request method. It relies on http_req_replace_stline(). */
6219__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6220{
6221 struct stream *s;
6222 struct http_msg *msg;
6223 const char *name;
6224 size_t name_len;
6225
6226 MAY_LJMP(check_args(L, 2, "set_method"));
6227 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6228 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6229
6230 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6231 WILL_LJMP(lua_error(L));
6232
6233 s = chn_strm(msg->chn);
6234 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6235 return 1;
6236}
6237
6238/* Rewrites the request path. It relies on http_req_replace_stline(). */
6239__LJMP static int hlua_http_msg_set_path(lua_State *L)
6240{
6241 struct stream *s;
6242 struct http_msg *msg;
6243 const char *name;
6244 size_t name_len;
6245
6246 MAY_LJMP(check_args(L, 2, "set_path"));
6247 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6248 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6249
6250 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6251 WILL_LJMP(lua_error(L));
6252
6253 s = chn_strm(msg->chn);
6254 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6255 return 1;
6256}
6257
6258/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6259__LJMP static int hlua_http_msg_set_query(lua_State *L)
6260{
6261 struct stream *s;
6262 struct http_msg *msg;
6263 const char *name;
6264 size_t name_len;
6265
6266 MAY_LJMP(check_args(L, 2, "set_query"));
6267 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6268 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6269
6270 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6271 WILL_LJMP(lua_error(L));
6272
6273 /* Check length. */
6274 if (name_len > trash.size - 1) {
6275 lua_pushboolean(L, 0);
6276 return 1;
6277 }
6278
6279 /* Add the mark question as prefix. */
6280 chunk_reset(&trash);
6281 trash.area[trash.data++] = '?';
6282 memcpy(trash.area + trash.data, name, name_len);
6283 trash.data += name_len;
6284
6285 s = chn_strm(msg->chn);
6286 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6287 return 1;
6288}
6289
6290/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6291__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6292{
6293 struct stream *s;
6294 struct http_msg *msg;
6295 const char *name;
6296 size_t name_len;
6297
6298 MAY_LJMP(check_args(L, 2, "set_uri"));
6299 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6300 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6301
6302 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6303 WILL_LJMP(lua_error(L));
6304
6305 s = chn_strm(msg->chn);
6306 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6307 return 1;
6308}
6309
6310/* Rewrites the response status code. It relies on http_res_set_status(). */
6311__LJMP static int hlua_http_msg_set_status(lua_State *L)
6312{
6313 struct http_msg *msg;
6314 unsigned int code;
6315 const char *reason;
6316 size_t reason_len;
6317
6318 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6319 code = MAY_LJMP(luaL_checkinteger(L, 2));
6320 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6321
6322 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6323 WILL_LJMP(lua_error(L));
6324
6325 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6326 return 1;
6327}
6328
6329/* Returns true if the HTTP message is full. */
6330__LJMP static int hlua_http_msg_is_full(lua_State *L)
6331{
6332 struct http_msg *msg;
6333
6334 MAY_LJMP(check_args(L, 1, "is_full"));
6335 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6336 lua_pushboolean(L, channel_full(msg->chn, 0));
6337 return 1;
6338}
6339
6340/* Returns true if the HTTP message may still receive data. */
6341__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6342{
6343 struct http_msg *msg;
6344 struct htx *htx;
6345
6346 MAY_LJMP(check_args(L, 1, "may_recv"));
6347 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6348 htx = htxbuf(&msg->chn->buf);
6349 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6350 return 1;
6351}
6352
6353/* Returns true if the HTTP message EOM was received */
6354__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6355{
6356 struct http_msg *msg;
6357 struct htx *htx;
6358
6359 MAY_LJMP(check_args(L, 1, "may_recv"));
6360 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6361 htx = htxbuf(&msg->chn->buf);
6362 lua_pushboolean(L, !htx_expect_more(htx));
6363 return 1;
6364}
6365
6366/* Returns the number of bytes available in the input side of the HTTP
6367 * message. This function never fails.
6368 */
6369__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6370{
6371 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006372 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006373
6374 MAY_LJMP(check_args(L, 1, "input"));
6375 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006376 hlua_http_msg_filter(L, 1, msg, &output, &input);
6377 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006378 return 1;
6379}
6380
6381/* Returns the number of bytes available in the output side of the HTTP
6382 * message. This function never fails.
6383 */
6384__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6385{
6386 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006387 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006388
6389 MAY_LJMP(check_args(L, 1, "output"));
6390 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006391 hlua_http_msg_filter(L, 1, msg, &output, &input);
6392 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006393 return 1;
6394}
6395
6396/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6397 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006398 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006399 * block. This function is called during the payload filtering, so the headers
6400 * are already scheduled for output (from the filter point of view).
6401 */
6402static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6403{
6404 struct htx *htx = htxbuf(&msg->chn->buf);
6405 struct htx_blk *blk;
6406 struct htx_ret htxret;
6407 luaL_Buffer b;
6408 int ret = 0;
6409
6410 luaL_buffinit(L, &b);
6411 htxret = htx_find_offset(htx, offset);
6412 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6413 enum htx_blk_type type = htx_get_blk_type(blk);
6414 struct ist v;
6415
6416 switch (type) {
6417 case HTX_BLK_UNUSED:
6418 break;
6419
6420 case HTX_BLK_DATA:
6421 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006422 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006423 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006424
6425 luaL_addlstring(&b, v.ptr, v.len);
6426 ret += v.len;
6427 break;
6428
6429 default:
vishnu0af4bd72021-10-24 06:46:24 +05306430 if (!ret)
6431 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006432 goto end;
6433 }
6434 offset = 0;
6435 }
6436
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006437end:
vishnu0af4bd72021-10-24 06:46:24 +05306438 if (!ret && (htx->flags & HTX_FL_EOM))
6439 goto no_data;
6440 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006441 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306442
6443 no_data:
6444 /* Remove the empty string and push nil on the stack */
6445 lua_pop(L, 1);
6446 lua_pushnil(L);
6447 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006448}
6449
6450/* Copies the string <str> to the HTTP message <msg> at the offset
6451 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006452 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006453 * the filter context.
6454 */
6455static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6456{
6457 struct htx *htx = htx_from_buf(&msg->chn->buf);
6458 struct htx_ret htxret;
6459 int /*max, */ret = 0;
6460
6461 /* Nothing to do, just return */
6462 if (unlikely(istlen(str) == 0))
6463 goto end;
6464
6465 if (istlen(str) > htx_free_data_space(htx)) {
6466 ret = -1;
6467 goto end;
6468 }
6469
6470 htxret = htx_find_offset(htx, offset);
6471 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6472 if (!htx_add_last_data(htx, str))
6473 goto end;
6474 }
6475 else {
6476 struct ist v = htx_get_blk_value(htx, htxret.blk);
6477 v.ptr += htxret.ret;
6478 v.len = 0;
6479 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6480 goto end;
6481 }
6482 ret = str.len;
6483 if (ret) {
6484 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6485 flt_update_offsets(filter, msg->chn, ret);
6486 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6487 }
6488
6489 end:
6490 htx_to_buf(htx, &msg->chn->buf);
6491 return ret;
6492}
6493
6494/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6495 * position <offset>. It stops on the first non-DATA HTX block. This function is
6496 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006497 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006498 * update the filter context.
6499 */
6500static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6501{
6502 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6503 struct htx *htx = htx_from_buf(&msg->chn->buf);
6504 struct htx_blk *blk;
6505 struct htx_ret htxret;
6506 size_t ret = 0;
6507
6508 /* Be sure <len> is always the amount of DATA to remove */
6509 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006510 /* When htx tail type == HTX_BLK_DATA, no need to take care
6511 * of special blocks like HTX_BLK_EOT.
6512 * We simply truncate after offset
6513 * (truncate targeted blk and discard the following ones)
6514 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006515 htx_truncate(htx, offset);
6516 ret = len;
6517 goto end;
6518 }
6519
6520 htxret = htx_find_offset(htx, offset);
6521 blk = htxret.blk;
6522 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006523 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006524 struct ist v;
6525
6526 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6527 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006528
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006529 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006530 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006531
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006532 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006533 /* trimming data in blk: discard everything after the offset
6534 * (replace 'v' with 'IST_NULL')
6535 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006536 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006537 if (blk && v.len < len) {
6538 /* In this case, caller wants to keep removing data,
6539 * but we need to spare current blk
6540 * because it was already trimmed
6541 */
6542 blk = htx_get_next_blk(htx, blk);
6543 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006544 len -= v.len;
6545 ret += v.len;
6546 }
6547
6548
6549 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006550 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006551 enum htx_blk_type type = htx_get_blk_type(blk);
6552 uint32_t sz = htx_get_blksz(blk);
6553
6554 switch (type) {
6555 case HTX_BLK_UNUSED:
6556 break;
6557
6558 case HTX_BLK_DATA:
6559 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006560 /* don't discard whole blk, only part of it
6561 * (from the beginning)
6562 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006563 htx_cut_data_blk(htx, blk, len);
6564 ret += len;
6565 goto end;
6566 }
6567 break;
6568
6569 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006570 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006571 goto end;
6572 }
6573
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006574 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006575 len -= sz;
6576 ret += sz;
6577 blk = htx_remove_blk(htx, blk);
6578 }
6579
6580end:
6581 flt_update_offsets(filter, msg->chn, -ret);
6582 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6583 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6584 * to loose the EOM flag if the message is empty.
6585 */
6586}
6587
6588/* Copies input data found in an HTTP message. Unlike the channel function used
6589 * to duplicate raw data, this one can only be called inside a filter, from
6590 * http_payload callback. So it cannot yield. An exception is returned if it is
6591 * called from another callback. If nothing was copied, a nil value is pushed on
6592 * the stack.
6593 */
6594__LJMP static int hlua_http_msg_get_body(lua_State *L)
6595{
6596 struct http_msg *msg;
6597 struct filter *filter;
6598 size_t output, input;
6599 int offset, len;
6600
6601 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6602 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6603 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6604
6605 if (msg->msg_state < HTTP_MSG_DATA)
6606 WILL_LJMP(lua_error(L));
6607
6608 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6609 if (!filter || !hlua_filter_from_payload(filter))
6610 WILL_LJMP(lua_error(L));
6611
6612 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6613 lua_pushnil(L);
6614 return 1;
6615 }
6616
6617 offset = output;
6618 if (lua_gettop(L) > 1) {
6619 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6620 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006621 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006622 offset += output;
6623 if (offset < output || offset > input + output) {
6624 lua_pushfstring(L, "offset out of range.");
6625 WILL_LJMP(lua_error(L));
6626 }
6627 }
6628 len = output + input - offset;
6629 if (lua_gettop(L) == 3) {
6630 len = MAY_LJMP(luaL_checkinteger(L, 3));
6631 if (!len)
6632 goto dup;
6633 if (len == -1)
6634 len = global.tune.bufsize;
6635 if (len < 0) {
6636 lua_pushfstring(L, "length out of range.");
6637 WILL_LJMP(lua_error(L));
6638 }
6639 }
6640
6641 dup:
6642 _hlua_http_msg_dup(msg, L, offset, len);
6643 return 1;
6644}
6645
6646/* Appends a string to the HTTP message, after all existing DATA blocks but
6647 * before the trailers, if any. It returns the amount of data written or -1 if
6648 * nothing was copied. Unlike the channel function used to append data, this one
6649 * can only be called inside a filter, from http_payload callback. So it cannot
6650 * yield. An exception is returned if it is called from another callback.
6651 */
6652__LJMP static int hlua_http_msg_append(lua_State *L)
6653{
6654 struct http_msg *msg;
6655 struct filter *filter;
6656 const char *str;
6657 size_t offset, len, sz;
6658 int ret;
6659
6660 MAY_LJMP(check_args(L, 2, "append"));
6661 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6662
6663 if (msg->msg_state < HTTP_MSG_DATA)
6664 WILL_LJMP(lua_error(L));
6665
6666 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6667 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6668 if (!filter || !hlua_filter_from_payload(filter))
6669 WILL_LJMP(lua_error(L));
6670
6671 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6672 lua_pushinteger(L, ret);
6673 return 1;
6674}
6675
6676/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6677 * returns the amount of data written or -1 if nothing was copied. Unlike the
6678 * channel function used to prepend data, this one can only be called inside a
6679 * filter, from http_payload callback. So it cannot yield. An exception is
6680 * returned if it is called from another callback.
6681 */
6682__LJMP static int hlua_http_msg_prepend(lua_State *L)
6683{
6684 struct http_msg *msg;
6685 struct filter *filter;
6686 const char *str;
6687 size_t offset, len, sz;
6688 int ret;
6689
6690 MAY_LJMP(check_args(L, 2, "prepend"));
6691 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006692
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006693 if (msg->msg_state < HTTP_MSG_DATA)
6694 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006695
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006696 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6697 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6698 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006699 WILL_LJMP(lua_error(L));
6700
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006701 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6702 lua_pushinteger(L, ret);
6703 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006704}
6705
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706/* Inserts a string to the HTTP message at a given offset. By default the string
6707 * is appended at the end of DATA blocks. It returns the amount of data written
6708 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6709 * this one can only be called inside a filter, from http_payload callback. So
6710 * it cannot yield. An exception is returned if it is called from another
6711 * callback.
6712 */
6713__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006714{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 struct http_msg *msg;
6716 struct filter *filter;
6717 const char *str;
6718 size_t input, output, sz;
6719 int offset;
6720 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006721
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006722 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6723 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006724 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006725
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006726 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006727 WILL_LJMP(lua_error(L));
6728
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006729 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006730 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731 if (!filter || !hlua_filter_from_payload(filter))
6732 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006733
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006734 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006735 if (lua_gettop(L) > 2) {
6736 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6737 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006738 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006739 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006740 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006741 lua_pushfstring(L, "offset out of range.");
6742 WILL_LJMP(lua_error(L));
6743 }
6744 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006745
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6747 lua_pushinteger(L, ret);
6748 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006749}
6750
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006751/* Removes a given amount of data from the HTTP message at a given offset. By
6752 * default all DATA blocks are removed. It returns the amount of data
6753 * removed. Unlike the channel function used to remove data, this one can only
6754 * be called inside a filter, from http_payload callback. So it cannot yield. An
6755 * exception is returned if it is called from another callback.
6756 */
6757__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006758{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006759 struct http_msg *msg;
6760 struct filter *filter;
6761 size_t input, output;
6762 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006763
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006764 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006765 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006766 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006767
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006768 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006769 WILL_LJMP(lua_error(L));
6770
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006771 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 if (!filter || !hlua_filter_from_payload(filter))
6773 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006774
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006775 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006776 if (lua_gettop(L) > 1) {
6777 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006778 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006779 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006780 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006781 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006782 lua_pushfstring(L, "offset out of range.");
6783 WILL_LJMP(lua_error(L));
6784 }
6785 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006786
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006788 if (lua_gettop(L) == 3) {
6789 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006790 if (!len)
6791 goto end;
6792 if (len == -1)
6793 len = output + input - offset;
6794 if (len < 0 || offset + len > output + input) {
6795 lua_pushfstring(L, "length out of range.");
6796 WILL_LJMP(lua_error(L));
6797 }
6798 }
6799
6800 _hlua_http_msg_delete(msg, filter, offset, len);
6801
6802 end:
6803 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006804 return 1;
6805}
6806
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006807/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006808 * all remaining data are removed, accordingly to the filter context. It returns
6809 * the amount of data written or -1 if nothing was copied. Unlike the channel
6810 * function used to replace data, this one can only be called inside a filter,
6811 * from http_payload callback. So it cannot yield. An exception is returned if
6812 * it is called from another callback.
6813 */
6814__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006815{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006816 struct http_msg *msg;
6817 struct filter *filter;
6818 struct htx *htx;
6819 const char *str;
6820 size_t input, output, sz;
6821 int offset, len;
6822 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006823
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006824 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6825 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6826 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6827
6828 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006829 WILL_LJMP(lua_error(L));
6830
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006831 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6832 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6833 if (!filter || !hlua_filter_from_payload(filter))
6834 WILL_LJMP(lua_error(L));
6835
6836 offset = output;
6837 if (lua_gettop(L) > 2) {
6838 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6839 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006840 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006841 offset += output;
6842 if (offset < output || offset > input + output) {
6843 lua_pushfstring(L, "offset out of range.");
6844 WILL_LJMP(lua_error(L));
6845 }
6846 }
6847
6848 len = output + input - offset;
6849 if (lua_gettop(L) == 4) {
6850 len = MAY_LJMP(luaL_checkinteger(L, 4));
6851 if (!len)
6852 goto set;
6853 if (len == -1)
6854 len = output + input - offset;
6855 if (len < 0 || offset + len > output + input) {
6856 lua_pushfstring(L, "length out of range.");
6857 WILL_LJMP(lua_error(L));
6858 }
6859 }
6860
6861 set:
6862 /* Be sure we can copied the string once input data will be removed. */
6863 htx = htx_from_buf(&msg->chn->buf);
6864 if (sz > htx_free_data_space(htx) + len)
6865 lua_pushinteger(L, -1);
6866 else {
6867 _hlua_http_msg_delete(msg, filter, offset, len);
6868 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6869 lua_pushinteger(L, ret);
6870 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006871 return 1;
6872}
6873
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006874/* Prepends data into an HTTP message and forward it, from the filter point of
6875 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6876 * the channel function used to send data, this one can only be called inside a
6877 * filter, from http_payload callback. So it cannot yield. An exception is
6878 * returned if it is called from another callback.
6879 */
6880__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006881{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006882 struct http_msg *msg;
6883 struct filter *filter;
6884 struct htx *htx;
6885 const char *str;
6886 size_t offset, len, sz;
6887 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006888
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006889 MAY_LJMP(check_args(L, 2, "send"));
6890 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6891
6892 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006893 WILL_LJMP(lua_error(L));
6894
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006895 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6896 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6897 if (!filter || !hlua_filter_from_payload(filter))
6898 WILL_LJMP(lua_error(L));
6899
6900 /* Return an error if the channel's output is closed */
6901 if (unlikely(channel_output_closed(msg->chn))) {
6902 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006903 return 1;
6904 }
6905
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006906 htx = htx_from_buf(&msg->chn->buf);
6907 if (sz > htx_free_data_space(htx)) {
6908 lua_pushinteger(L, -1);
6909 return 1;
6910 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006911
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006912 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6913 if (ret > 0) {
6914 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6915
6916 FLT_OFF(filter, msg->chn) += ret;
6917 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6918 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6919 }
6920
6921 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006922 return 1;
6923}
6924
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006925/* Forwards a given amount of bytes. It return -1 if the channel's output is
6926 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6927 * channel function used to forward data, this one can only be called inside a
6928 * filter, from http_payload callback. So it cannot yield. An exception is
6929 * returned if it is called from another callback. All other functions deal with
6930 * DATA block, this one not.
6931*/
6932__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006933{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006934 struct http_msg *msg;
6935 struct filter *filter;
6936 size_t offset, len;
6937 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006938
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006939 MAY_LJMP(check_args(L, 2, "forward"));
6940 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6941
6942 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006943 WILL_LJMP(lua_error(L));
6944
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006945 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6946 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6947 if (!filter || !hlua_filter_from_payload(filter))
6948 WILL_LJMP(lua_error(L));
6949
6950 /* Nothing to do, just return */
6951 if (!fwd)
6952 goto end;
6953
6954 /* Return an error if the channel's output is closed */
6955 if (unlikely(channel_output_closed(msg->chn))) {
6956 ret = -1;
6957 goto end;
6958 }
6959
6960 ret = fwd;
6961 if (ret > len)
6962 ret = len;
6963
6964 if (ret) {
6965 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6966
6967 FLT_OFF(filter, msg->chn) += ret;
6968 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6969 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6970 }
6971
6972 end:
6973 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006974 return 1;
6975}
6976
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006977/* Set EOM flag on the HTX message.
6978 *
6979 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6980 * really know how to do without this feature.
6981 */
6982__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006983{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006984 struct http_msg *msg;
6985 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006986
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006987 MAY_LJMP(check_args(L, 1, "set_eom"));
6988 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6989 htx = htxbuf(&msg->chn->buf);
6990 htx->flags |= HTX_FL_EOM;
6991 return 0;
6992}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006993
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006994/* Unset EOM flag on the HTX message.
6995 *
6996 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6997 * really know how to do without this feature.
6998 */
6999__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7000{
7001 struct http_msg *msg;
7002 struct htx *htx;
7003
7004 MAY_LJMP(check_args(L, 1, "set_eom"));
7005 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7006 htx = htxbuf(&msg->chn->buf);
7007 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007008 return 0;
7009}
7010
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007011/*
7012 *
7013 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007014 * Class HTTPClient
7015 *
7016 *
7017 */
7018__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7019{
7020 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7021}
7022
William Lallemandf77f1de2021-09-28 19:10:38 +02007023
7024/* stops the httpclient and ask it to kill itself */
7025__LJMP static int hlua_httpclient_gc(lua_State *L)
7026{
7027 struct hlua_httpclient *hlua_hc;
7028
7029 MAY_LJMP(check_args(L, 1, "__gc"));
7030
7031 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7032
William Lallemandbb581422022-10-20 10:57:28 +02007033 if (hlua_hc->hc)
7034 httpclient_stop_and_destroy(hlua_hc->hc);
7035
7036 LIST_DELETE(&hlua_hc->by_hlua);
William Lallemandf77f1de2021-09-28 19:10:38 +02007037
7038 hlua_hc->hc = NULL;
7039
7040
7041 return 0;
7042}
7043
7044
William Lallemand3956c4e2021-09-21 16:25:15 +02007045__LJMP static int hlua_httpclient_new(lua_State *L)
7046{
7047 struct hlua_httpclient *hlua_hc;
7048 struct hlua *hlua;
7049
7050 /* Get hlua struct, or NULL if we execute from main lua state */
7051 hlua = hlua_gethlua(L);
7052 if (!hlua)
7053 return 0;
7054
7055 /* Check stack size. */
7056 if (!lua_checkstack(L, 3)) {
7057 hlua_pusherror(L, "httpclient: full stack");
7058 goto err;
7059 }
7060 /* Create the object: obj[0] = userdata. */
7061 lua_newtable(L);
7062 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7063 lua_rawseti(L, -2, 0);
7064 memset(hlua_hc, 0, sizeof(*hlua_hc));
7065
7066 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7067 if (!hlua_hc->hc)
7068 goto err;
7069
William Lallemandbb581422022-10-20 10:57:28 +02007070 LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
7071
William Lallemand3956c4e2021-09-21 16:25:15 +02007072 /* Pop a class stream metatable and affect it to the userdata. */
7073 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7074 lua_setmetatable(L, -2);
7075
7076 return 1;
7077
7078 err:
7079 WILL_LJMP(lua_error(L));
7080 return 0;
7081}
7082
7083
7084/*
7085 * Callback of the httpclient, this callback wakes the lua task up, once the
7086 * httpclient receives some data
7087 *
7088 */
7089
William Lallemandbd5739e2021-10-28 15:41:38 +02007090static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007091{
7092 struct hlua *hlua = hc->caller;
7093
7094 if (!hlua || !hlua->task)
7095 return;
7096
7097 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7098}
7099
7100/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007101 * Fill the lua stack with headers from the httpclient response
7102 * This works the same way as the hlua_http_get_headers() function
7103 */
7104__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7105{
7106 struct http_hdr *hdr;
7107
7108 lua_newtable(L);
7109
William Lallemandef574b22021-10-05 16:19:31 +02007110 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007111 struct ist n, v;
7112 int len;
7113
7114 n = hdr->n;
7115 v = hdr->v;
7116
7117 /* Check for existing entry:
7118 * assume that the table is on the top of the stack, and
7119 * push the key in the stack, the function lua_gettable()
7120 * perform the lookup.
7121 */
7122
7123 lua_pushlstring(L, n.ptr, n.len);
7124 lua_gettable(L, -2);
7125
7126 switch (lua_type(L, -1)) {
7127 case LUA_TNIL:
7128 /* Table not found, create it. */
7129 lua_pop(L, 1); /* remove the nil value. */
7130 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7131 lua_newtable(L); /* create and push empty table. */
7132 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7133 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7134 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7135 break;
7136
7137 case LUA_TTABLE:
7138 /* Entry found: push the value in the table. */
7139 len = lua_rawlen(L, -1);
7140 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7141 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7142 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7143 break;
7144
7145 default:
7146 /* Other cases are errors. */
7147 hlua_pusherror(L, "internal error during the parsing of headers.");
7148 WILL_LJMP(lua_error(L));
7149 }
7150 }
7151 return 1;
7152}
7153
7154/*
William Lallemand746e6f32021-10-06 10:57:44 +02007155 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7156 *
7157 * Caller must free the result
7158 */
7159struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7160{
7161 struct http_hdr hdrs[global.tune.max_http_hdr];
7162 struct http_hdr *result = NULL;
7163 uint32_t hdr_num = 0;
7164
7165 lua_pushnil(L);
7166 while (lua_next(L, -2) != 0) {
7167 struct ist name, value;
7168 const char *n, *v;
7169 size_t nlen, vlen;
7170
7171 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7172 /* Skip element if the key is not a string or if the value is not a table */
7173 goto next_hdr;
7174 }
7175
7176 n = lua_tolstring(L, -2, &nlen);
7177 name = ist2(n, nlen);
7178
7179 /* Loop on header's values */
7180 lua_pushnil(L);
7181 while (lua_next(L, -2)) {
7182 if (!lua_isstring(L, -1)) {
7183 /* Skip the value if it is not a string */
7184 goto next_value;
7185 }
7186
7187 v = lua_tolstring(L, -1, &vlen);
7188 value = ist2(v, vlen);
7189 name = ist2(n, nlen);
7190
7191 hdrs[hdr_num].n = istdup(name);
7192 hdrs[hdr_num].v = istdup(value);
7193
7194 hdr_num++;
7195
7196 next_value:
7197 lua_pop(L, 1);
7198 }
7199
7200 next_hdr:
7201 lua_pop(L, 1);
7202
7203 }
7204
7205 if (hdr_num) {
7206 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007207 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007208 if (!result)
7209 goto skip_headers;
7210 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7211
7212 result[hdr_num].n = IST_NULL;
7213 result[hdr_num].v = IST_NULL;
7214 }
7215
7216skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007217
7218 return result;
7219}
7220
7221
William Lallemandbd5739e2021-10-28 15:41:38 +02007222/*
7223 * For each yield, checks if there is some data in the httpclient and push them
7224 * in the lua buffer, once the httpclient finished its job, push the result on
7225 * the stack
7226 */
7227__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7228{
7229 struct buffer *tr;
7230 int res;
7231 struct hlua *hlua = hlua_gethlua(L);
7232 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7233
7234
7235 tr = get_trash_chunk();
7236
7237 res = httpclient_res_xfer(hlua_hc->hc, tr);
7238 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7239
7240 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7241
7242 luaL_pushresult(&hlua_hc->b);
7243 lua_settable(L, -3);
7244
7245 lua_pushstring(L, "status");
7246 lua_pushinteger(L, hlua_hc->hc->res.status);
7247 lua_settable(L, -3);
7248
7249
7250 lua_pushstring(L, "reason");
7251 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7252 lua_settable(L, -3);
7253
7254 lua_pushstring(L, "headers");
7255 hlua_httpclient_get_headers(L, hlua_hc);
7256 lua_settable(L, -3);
7257
7258 return 1;
7259 }
7260
7261 if (httpclient_data(hlua_hc->hc))
7262 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7263
7264 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7265
7266 return 0;
7267}
7268
7269/*
7270 * Call this when trying to stream a body during a request
7271 */
7272__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7273{
7274 struct hlua *hlua;
7275 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7276 const char *body_str = NULL;
7277 int ret;
7278 int end = 0;
7279 size_t buf_len;
7280 size_t to_send = 0;
7281
7282 hlua = hlua_gethlua(L);
7283
7284 if (!hlua || !hlua->task)
7285 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7286 "'frontend', 'backend' or 'task'"));
7287
7288 ret = lua_getfield(L, -1, "body");
7289 if (ret != LUA_TSTRING)
7290 goto rcv;
7291
7292 body_str = lua_tolstring(L, -1, &buf_len);
7293 lua_pop(L, 1);
7294
Christopher Fauletfc591292022-01-12 14:46:03 +01007295 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007296
7297 if ((hlua_hc->sent + to_send) >= buf_len)
7298 end = 1;
7299
7300 /* the end flag is always set since we are using the whole remaining size */
7301 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7302
7303 if (buf_len > hlua_hc->sent) {
7304 /* still need to process the buffer */
7305 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7306 } else {
7307 goto rcv;
7308 /* we sent the whole request buffer we can recv */
7309 }
7310 return 0;
7311
7312rcv:
7313
7314 /* we return a "res" object */
7315 lua_newtable(L);
7316
William Lallemandbd5739e2021-10-28 15:41:38 +02007317 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007318 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007319
William Lallemand933fe392021-11-04 09:45:58 +01007320 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007321 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7322
7323 return 1;
7324}
William Lallemand746e6f32021-10-06 10:57:44 +02007325
William Lallemand3956c4e2021-09-21 16:25:15 +02007326/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007327 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007328 */
7329
William Lallemanddc2cc902021-10-26 11:43:26 +02007330__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007331{
7332 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007333 struct http_hdr *hdrs = NULL;
7334 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007335 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007336 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007337 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007338 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007339 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007340
7341 hlua = hlua_gethlua(L);
7342
7343 if (!hlua || !hlua->task)
7344 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7345 "'frontend', 'backend' or 'task'"));
7346
William Lallemand746e6f32021-10-06 10:57:44 +02007347 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7348 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7349
William Lallemand4f4f2b72022-02-17 20:00:23 +01007350 hlua_hc = hlua_checkhttpclient(L, 1);
7351
William Lallemand7177a952022-03-03 15:33:12 +01007352 lua_pushnil(L); /* first key */
7353 while (lua_next(L, 2)) {
7354 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7355 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7356 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007357
William Lallemand7177a952022-03-03 15:33:12 +01007358 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7359 if (lua_type(L, -1) != LUA_TSTRING)
7360 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7361 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007362
William Lallemand7177a952022-03-03 15:33:12 +01007363 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7364 if (lua_type(L, -1) != LUA_TNUMBER)
7365 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7366 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007367
William Lallemand7177a952022-03-03 15:33:12 +01007368 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7369 if (lua_type(L, -1) != LUA_TTABLE)
7370 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7371 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007372
William Lallemand7177a952022-03-03 15:33:12 +01007373 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7374 if (lua_type(L, -1) != LUA_TSTRING)
7375 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7376 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007377
William Lallemand7177a952022-03-03 15:33:12 +01007378 } else {
7379 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7380 }
7381 /* removes 'value'; keeps 'key' for next iteration */
7382 lua_pop(L, 1);
7383 }
William Lallemanddec25c32021-10-25 19:48:37 +02007384
William Lallemand746e6f32021-10-06 10:57:44 +02007385 if (!url_str) {
7386 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7387 return 0;
7388 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007389
William Lallemand10a37362022-03-02 16:18:26 +01007390 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007391
7392 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007393 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007394
7395 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007396 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7397 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7398 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007399 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007400
William Lallemandbd5739e2021-10-28 15:41:38 +02007401 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007402 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007403 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7404 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007405
William Lallemandbd5739e2021-10-28 15:41:38 +02007406 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007407
William Lallemand746e6f32021-10-06 10:57:44 +02007408 /* free the temporary headers array */
7409 hdrs_i = hdrs;
7410 while (hdrs_i && isttest(hdrs_i->n)) {
7411 istfree(&hdrs_i->n);
7412 istfree(&hdrs_i->v);
7413 hdrs_i++;
7414 }
7415 ha_free(&hdrs);
7416
7417
William Lallemand6137a9e2021-10-26 15:01:53 +02007418 if (ret != ERR_NONE) {
7419 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7420 return 0;
7421 }
7422
William Lallemandc2d3db42022-04-26 11:46:13 +02007423 if (!httpclient_start(hlua_hc->hc))
7424 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007425
William Lallemandbd5739e2021-10-28 15:41:38 +02007426 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007427
William Lallemand3956c4e2021-09-21 16:25:15 +02007428 return 0;
7429}
7430
7431/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007432 * Sends an HTTP HEAD request and wait for a response
7433 *
7434 * httpclient:head(url, headers, payload)
7435 */
7436__LJMP static int hlua_httpclient_head(lua_State *L)
7437{
7438 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7439}
7440
7441/*
7442 * Send an HTTP GET request and wait for a response
7443 *
7444 * httpclient:get(url, headers, payload)
7445 */
7446__LJMP static int hlua_httpclient_get(lua_State *L)
7447{
7448 return hlua_httpclient_send(L, HTTP_METH_GET);
7449
7450}
7451
7452/*
7453 * Sends an HTTP PUT request and wait for a response
7454 *
7455 * httpclient:put(url, headers, payload)
7456 */
7457__LJMP static int hlua_httpclient_put(lua_State *L)
7458{
7459 return hlua_httpclient_send(L, HTTP_METH_PUT);
7460}
7461
7462/*
7463 * Send an HTTP POST request and wait for a response
7464 *
7465 * httpclient:post(url, headers, payload)
7466 */
7467__LJMP static int hlua_httpclient_post(lua_State *L)
7468{
7469 return hlua_httpclient_send(L, HTTP_METH_POST);
7470}
7471
7472
7473/*
7474 * Sends an HTTP DELETE request and wait for a response
7475 *
7476 * httpclient:delete(url, headers, payload)
7477 */
7478__LJMP static int hlua_httpclient_delete(lua_State *L)
7479{
7480 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7481}
7482
7483/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007484 *
7485 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007486 * Class TXN
7487 *
7488 *
7489 */
7490
7491/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007492 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007493 */
7494__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7495{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007496 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007497}
7498
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007499__LJMP static int hlua_set_var(lua_State *L)
7500{
7501 struct hlua_txn *htxn;
7502 const char *name;
7503 size_t len;
7504 struct sample smp;
7505
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007506 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7507 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007508
7509 /* It is useles to retrieve the stream, but this function
7510 * runs only in a stream context.
7511 */
7512 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7513 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7514
7515 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007516 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007517 hlua_lua2smp(L, 3, &smp);
7518
7519 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007520 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007521
7522 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7523 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7524 else
7525 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7526
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007527 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007528}
7529
Christopher Faulet85d79c92016-11-09 16:54:56 +01007530__LJMP static int hlua_unset_var(lua_State *L)
7531{
7532 struct hlua_txn *htxn;
7533 const char *name;
7534 size_t len;
7535 struct sample smp;
7536
7537 MAY_LJMP(check_args(L, 2, "unset_var"));
7538
7539 /* It is useles to retrieve the stream, but this function
7540 * runs only in a stream context.
7541 */
7542 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7543 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7544
7545 /* Unset the variable. */
7546 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007547 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7548 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007549}
7550
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007551__LJMP static int hlua_get_var(lua_State *L)
7552{
7553 struct hlua_txn *htxn;
7554 const char *name;
7555 size_t len;
7556 struct sample smp;
7557
7558 MAY_LJMP(check_args(L, 2, "get_var"));
7559
7560 /* It is useles to retrieve the stream, but this function
7561 * runs only in a stream context.
7562 */
7563 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7564 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7565
Willy Tarreau7560dd42016-03-10 16:28:58 +01007566 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007567 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007568 lua_pushnil(L);
7569 return 1;
7570 }
7571
7572 return hlua_smp2lua(L, &smp);
7573}
7574
Willy Tarreau59551662015-03-10 14:23:13 +01007575__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007576{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007577 struct hlua *hlua;
7578
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007579 MAY_LJMP(check_args(L, 2, "set_priv"));
7580
Willy Tarreau87b09662015-04-03 00:22:06 +02007581 /* It is useles to retrieve the stream, but this function
7582 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007583 */
7584 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007585
7586 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007587 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007588 if (!hlua)
7589 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007590
7591 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007592 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007593
7594 /* Get and store new value. */
7595 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7596 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7597
7598 return 0;
7599}
7600
Willy Tarreau59551662015-03-10 14:23:13 +01007601__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007602{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007603 struct hlua *hlua;
7604
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007605 MAY_LJMP(check_args(L, 1, "get_priv"));
7606
Willy Tarreau87b09662015-04-03 00:22:06 +02007607 /* It is useles to retrieve the stream, but this function
7608 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007609 */
7610 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007611
7612 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007613 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007614 if (!hlua) {
7615 lua_pushnil(L);
7616 return 1;
7617 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007618
7619 /* Push configuration index in the stack. */
7620 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7621
7622 return 1;
7623}
7624
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007625/* Create stack entry containing a class TXN. This function
7626 * return 0 if the stack does not contains free slots,
7627 * otherwise it returns 1.
7628 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007629static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007630{
Willy Tarreaude491382015-04-06 11:04:28 +02007631 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007632
7633 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007634 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007635 return 0;
7636
7637 /* NOTE: The allocation never fails. The failure
7638 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007639 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007640 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007641 /* Create the object: obj[0] = userdata. */
7642 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007643 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007644 lua_rawseti(L, -2, 0);
7645
Willy Tarreaude491382015-04-06 11:04:28 +02007646 htxn->s = s;
7647 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007648 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007649 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007650
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007651 /* Create the "f" field that contains a list of fetches. */
7652 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007653 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007654 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007655 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007656
7657 /* Create the "sf" field that contains a list of stringsafe fetches. */
7658 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007659 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007660 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007661 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007662
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007663 /* Create the "c" field that contains a list of converters. */
7664 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007665 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007666 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007667 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007668
7669 /* Create the "sc" field that contains a list of stringsafe converters. */
7670 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007671 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007672 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007673 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007674
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007675 /* Create the "req" field that contains the request channel object. */
7676 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007677 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007678 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007679 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007680
7681 /* Create the "res" field that contains the response channel object. */
7682 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007683 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007684 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007685 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007686
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007687 /* Creates the HTTP object is the current proxy allows http. */
7688 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007689 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007690 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007691 return 0;
7692 }
7693 else
7694 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007695 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007696
Christopher Faulet78c35472020-02-26 17:14:08 +01007697 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7698 /* HTTPMessage object are created when a lua TXN is created from
7699 * a filter context only
7700 */
7701
7702 /* Creates the HTTP-Request object is the current proxy allows http. */
7703 lua_pushstring(L, "http_req");
7704 if (p->mode == PR_MODE_HTTP) {
7705 if (!hlua_http_msg_new(L, &s->txn->req))
7706 return 0;
7707 }
7708 else
7709 lua_pushnil(L);
7710 lua_rawset(L, -3);
7711
7712 /* Creates the HTTP-Response object is the current proxy allows http. */
7713 lua_pushstring(L, "http_res");
7714 if (p->mode == PR_MODE_HTTP) {
7715 if (!hlua_http_msg_new(L, &s->txn->rsp))
7716 return 0;
7717 }
7718 else
7719 lua_pushnil(L);
7720 lua_rawset(L, -3);
7721 }
7722
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007723 /* Pop a class sesison metatable and affect it to the userdata. */
7724 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7725 lua_setmetatable(L, -2);
7726
7727 return 1;
7728}
7729
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007730__LJMP static int hlua_txn_deflog(lua_State *L)
7731{
7732 const char *msg;
7733 struct hlua_txn *htxn;
7734
7735 MAY_LJMP(check_args(L, 2, "deflog"));
7736 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7737 msg = MAY_LJMP(luaL_checkstring(L, 2));
7738
7739 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7740 return 0;
7741}
7742
7743__LJMP static int hlua_txn_log(lua_State *L)
7744{
7745 int level;
7746 const char *msg;
7747 struct hlua_txn *htxn;
7748
7749 MAY_LJMP(check_args(L, 3, "log"));
7750 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7751 level = MAY_LJMP(luaL_checkinteger(L, 2));
7752 msg = MAY_LJMP(luaL_checkstring(L, 3));
7753
7754 if (level < 0 || level >= NB_LOG_LEVELS)
7755 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7756
7757 hlua_sendlog(htxn->s->be, level, msg);
7758 return 0;
7759}
7760
7761__LJMP static int hlua_txn_log_debug(lua_State *L)
7762{
7763 const char *msg;
7764 struct hlua_txn *htxn;
7765
7766 MAY_LJMP(check_args(L, 2, "Debug"));
7767 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7768 msg = MAY_LJMP(luaL_checkstring(L, 2));
7769 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7770 return 0;
7771}
7772
7773__LJMP static int hlua_txn_log_info(lua_State *L)
7774{
7775 const char *msg;
7776 struct hlua_txn *htxn;
7777
7778 MAY_LJMP(check_args(L, 2, "Info"));
7779 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7780 msg = MAY_LJMP(luaL_checkstring(L, 2));
7781 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7782 return 0;
7783}
7784
7785__LJMP static int hlua_txn_log_warning(lua_State *L)
7786{
7787 const char *msg;
7788 struct hlua_txn *htxn;
7789
7790 MAY_LJMP(check_args(L, 2, "Warning"));
7791 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7792 msg = MAY_LJMP(luaL_checkstring(L, 2));
7793 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7794 return 0;
7795}
7796
7797__LJMP static int hlua_txn_log_alert(lua_State *L)
7798{
7799 const char *msg;
7800 struct hlua_txn *htxn;
7801
7802 MAY_LJMP(check_args(L, 2, "Alert"));
7803 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7804 msg = MAY_LJMP(luaL_checkstring(L, 2));
7805 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7806 return 0;
7807}
7808
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007809__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7810{
7811 struct hlua_txn *htxn;
7812 int ll;
7813
7814 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7815 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7816 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7817
7818 if (ll < 0 || ll > 7)
7819 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7820
7821 htxn->s->logs.level = ll;
7822 return 0;
7823}
7824
7825__LJMP static int hlua_txn_set_tos(lua_State *L)
7826{
7827 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007828 int tos;
7829
7830 MAY_LJMP(check_args(L, 2, "set_tos"));
7831 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7832 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7833
Willy Tarreau1a18b542018-12-11 16:37:42 +01007834 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007835 return 0;
7836}
7837
7838__LJMP static int hlua_txn_set_mark(lua_State *L)
7839{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007840 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007841 int mark;
7842
7843 MAY_LJMP(check_args(L, 2, "set_mark"));
7844 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7845 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7846
Lukas Tribus579e3e32019-08-11 18:03:45 +02007847 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007848 return 0;
7849}
7850
Patrick Hemmer268a7072018-05-11 12:52:31 -04007851__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7852{
7853 struct hlua_txn *htxn;
7854
7855 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7856 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7857 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7858 return 0;
7859}
7860
7861__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7862{
7863 struct hlua_txn *htxn;
7864
7865 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7866 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7867 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7868 return 0;
7869}
7870
Christopher Faulet700d9e82020-01-31 12:21:52 +01007871/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007872 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007873 * message and terminate the transaction. It returns 1 on success and 0 on
7874 * error. The Reply must be on top of the stack.
7875 */
7876__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7877{
7878 struct htx *htx;
7879 struct htx_sl *sl;
7880 struct h1m h1m;
7881 const char *status, *reason, *body;
7882 size_t status_len, reason_len, body_len;
7883 int ret, code, flags;
7884
7885 code = 200;
7886 status = "200";
7887 status_len = 3;
7888 ret = lua_getfield(L, -1, "status");
7889 if (ret == LUA_TNUMBER) {
7890 code = lua_tointeger(L, -1);
7891 status = lua_tolstring(L, -1, &status_len);
7892 }
7893 lua_pop(L, 1);
7894
7895 reason = http_get_reason(code);
7896 reason_len = strlen(reason);
7897 ret = lua_getfield(L, -1, "reason");
7898 if (ret == LUA_TSTRING)
7899 reason = lua_tolstring(L, -1, &reason_len);
7900 lua_pop(L, 1);
7901
7902 body = NULL;
7903 body_len = 0;
7904 ret = lua_getfield(L, -1, "body");
7905 if (ret == LUA_TSTRING)
7906 body = lua_tolstring(L, -1, &body_len);
7907 lua_pop(L, 1);
7908
7909 /* Prepare the response before inserting the headers */
7910 h1m_init_res(&h1m);
7911 htx = htx_from_buf(&s->res.buf);
7912 channel_htx_truncate(&s->res, htx);
7913 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7914 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7915 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7916 ist2(status, status_len), ist2(reason, reason_len));
7917 }
7918 else {
7919 flags = HTX_SL_F_IS_RESP;
7920 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7921 ist2(status, status_len), ist2(reason, reason_len));
7922 }
7923 if (!sl)
7924 goto fail;
7925 sl->info.res.status = code;
7926
7927 /* Push in the stack the "headers" entry. */
7928 ret = lua_getfield(L, -1, "headers");
7929 if (ret != LUA_TTABLE)
7930 goto skip_headers;
7931
7932 lua_pushnil(L);
7933 while (lua_next(L, -2) != 0) {
7934 struct ist name, value;
7935 const char *n, *v;
7936 size_t nlen, vlen;
7937
7938 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7939 /* Skip element if the key is not a string or if the value is not a table */
7940 goto next_hdr;
7941 }
7942
7943 n = lua_tolstring(L, -2, &nlen);
7944 name = ist2(n, nlen);
7945 if (isteqi(name, ist("content-length"))) {
7946 /* Always skip content-length header. It will be added
7947 * later with the correct len
7948 */
7949 goto next_hdr;
7950 }
7951
7952 /* Loop on header's values */
7953 lua_pushnil(L);
7954 while (lua_next(L, -2)) {
7955 if (!lua_isstring(L, -1)) {
7956 /* Skip the value if it is not a string */
7957 goto next_value;
7958 }
7959
7960 v = lua_tolstring(L, -1, &vlen);
7961 value = ist2(v, vlen);
7962
7963 if (isteqi(name, ist("transfer-encoding")))
7964 h1_parse_xfer_enc_header(&h1m, value);
7965 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7966 goto fail;
7967
7968 next_value:
7969 lua_pop(L, 1);
7970 }
7971
7972 next_hdr:
7973 lua_pop(L, 1);
7974 }
7975 skip_headers:
7976 lua_pop(L, 1);
7977
7978 /* Update h1m flags: CLEN is set if CHNK is not present */
7979 if (!(h1m.flags & H1_MF_CHNK)) {
7980 const char *clen = ultoa(body_len);
7981
7982 h1m.flags |= H1_MF_CLEN;
7983 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7984 goto fail;
7985 }
7986 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7987 h1m.flags |= H1_MF_XFER_LEN;
7988
7989 /* Update HTX start-line flags */
7990 if (h1m.flags & H1_MF_XFER_ENC)
7991 flags |= HTX_SL_F_XFER_ENC;
7992 if (h1m.flags & H1_MF_XFER_LEN) {
7993 flags |= HTX_SL_F_XFER_LEN;
7994 if (h1m.flags & H1_MF_CHNK)
7995 flags |= HTX_SL_F_CHNK;
7996 else if (h1m.flags & H1_MF_CLEN)
7997 flags |= HTX_SL_F_CLEN;
7998 if (h1m.body_len == 0)
7999 flags |= HTX_SL_F_BODYLESS;
8000 }
8001 sl->flags |= flags;
8002
8003
8004 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008005 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008006 goto fail;
8007
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008008 htx->flags |= HTX_FL_EOM;
8009
Christopher Faulet700d9e82020-01-31 12:21:52 +01008010 /* Now, forward the response and terminate the transaction */
8011 s->txn->status = code;
8012 htx_to_buf(htx, &s->res.buf);
8013 if (!http_forward_proxy_resp(s, 1))
8014 goto fail;
8015
8016 return 1;
8017
8018 fail:
8019 channel_htx_truncate(&s->res, htx);
8020 return 0;
8021}
8022
8023/* Terminate a transaction if called from a lua action. For TCP streams,
8024 * processing is just aborted. Nothing is returned to the client and all
8025 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8026 * is forwarded to the client before terminating the transaction. On success,
8027 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8028 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8029 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008030 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008031__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008032{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008033 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008034 struct stream *s;
8035 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008036
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008037 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008038
Christopher Faulet700d9e82020-01-31 12:21:52 +01008039 /* If the flags NOTERM is set, we cannot terminate the session, so we
8040 * just end the execution of the current lua code. */
8041 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008042 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008043
Christopher Faulet700d9e82020-01-31 12:21:52 +01008044 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008045 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008046 struct channel *req = &s->req;
8047 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008048
Christopher Faulet700d9e82020-01-31 12:21:52 +01008049 channel_auto_read(req);
8050 channel_abort(req);
8051 channel_auto_close(req);
8052 channel_erase(req);
8053
8054 res->wex = tick_add_ifset(now_ms, res->wto);
8055 channel_auto_read(res);
8056 channel_auto_close(res);
8057 channel_shutr_now(res);
8058
8059 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8060 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008061 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008062
Christopher Faulet700d9e82020-01-31 12:21:52 +01008063 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8064 /* No reply or invalid reply */
8065 s->txn->status = 0;
8066 http_reply_and_close(s, 0, NULL);
8067 }
8068 else {
8069 /* Remove extra args to have the reply on top of the stack */
8070 if (lua_gettop(L) > 2)
8071 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008072
Christopher Faulet700d9e82020-01-31 12:21:52 +01008073 if (!hlua_txn_forward_reply(L, s)) {
8074 if (!(s->flags & SF_ERR_MASK))
8075 s->flags |= SF_ERR_PRXCOND;
8076 lua_pushinteger(L, ACT_RET_ERR);
8077 WILL_LJMP(hlua_done(L));
8078 return 0; /* Never reached */
8079 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008080 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008081
Christopher Faulet700d9e82020-01-31 12:21:52 +01008082 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8083 if (htxn->dir == SMP_OPT_DIR_REQ) {
8084 /* let's log the request time */
8085 s->logs.tv_request = now;
8086 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008087 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008088 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008089
Christopher Faulet700d9e82020-01-31 12:21:52 +01008090 done:
8091 if (!(s->flags & SF_ERR_MASK))
8092 s->flags |= SF_ERR_LOCAL;
8093 if (!(s->flags & SF_FINST_MASK))
8094 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008095
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008096 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8097 lua_pushinteger(L, -1);
8098 else
8099 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008100 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008101 return 0;
8102}
8103
Christopher Faulet700d9e82020-01-31 12:21:52 +01008104/*
8105 *
8106 *
8107 * Class REPLY
8108 *
8109 *
8110 */
8111
8112/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8113 * free slots, the function fails and returns 0;
8114 */
8115static int hlua_txn_reply_new(lua_State *L)
8116{
8117 struct hlua_txn *htxn;
8118 const char *reason, *body = NULL;
8119 int ret, status;
8120
8121 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008122 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008123 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8124 WILL_LJMP(lua_error(L));
8125 }
8126
8127 /* Default value */
8128 status = 200;
8129 reason = http_get_reason(status);
8130
8131 if (lua_istable(L, 2)) {
8132 /* load status and reason from the table argument at index 2 */
8133 ret = lua_getfield(L, 2, "status");
8134 if (ret == LUA_TNIL)
8135 goto reason;
8136 else if (ret != LUA_TNUMBER) {
8137 /* invalid status: ignore the reason */
8138 goto body;
8139 }
8140 status = lua_tointeger(L, -1);
8141
8142 reason:
8143 lua_pop(L, 1); /* restore the stack: remove status */
8144 ret = lua_getfield(L, 2, "reason");
8145 if (ret == LUA_TSTRING)
8146 reason = lua_tostring(L, -1);
8147
8148 body:
8149 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8150 ret = lua_getfield(L, 2, "body");
8151 if (ret == LUA_TSTRING)
8152 body = lua_tostring(L, -1);
8153 lua_pop(L, 1); /* restore the stack: remove body */
8154 }
8155
8156 /* Create the Reply table */
8157 lua_newtable(L);
8158
8159 /* Add status element */
8160 lua_pushstring(L, "status");
8161 lua_pushinteger(L, status);
8162 lua_settable(L, -3);
8163
8164 /* Add reason element */
8165 reason = http_get_reason(status);
8166 lua_pushstring(L, "reason");
8167 lua_pushstring(L, reason);
8168 lua_settable(L, -3);
8169
8170 /* Add body element, nil if undefined */
8171 lua_pushstring(L, "body");
8172 if (body)
8173 lua_pushstring(L, body);
8174 else
8175 lua_pushnil(L);
8176 lua_settable(L, -3);
8177
8178 /* Add headers element */
8179 lua_pushstring(L, "headers");
8180 lua_newtable(L);
8181
8182 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8183 if (lua_istable(L, 2)) {
8184 /* load headers from the table argument at index 2. If it is a table, copy it. */
8185 ret = lua_getfield(L, 2, "headers");
8186 if (ret == LUA_TTABLE) {
8187 /* stack: [ ... <headers:table>, <table> ] */
8188 lua_pushnil(L);
8189 while (lua_next(L, -2) != 0) {
8190 /* stack: [ ... <headers:table>, <table>, k, v] */
8191 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8192 /* invalid value type, skip it */
8193 lua_pop(L, 1);
8194 continue;
8195 }
8196
8197
8198 /* Duplicate the key and swap it with the value. */
8199 lua_pushvalue(L, -2);
8200 lua_insert(L, -2);
8201 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8202
8203 lua_newtable(L);
8204 lua_insert(L, -2);
8205 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8206
8207 if (lua_isstring(L, -1)) {
8208 /* push the value in the inner table */
8209 lua_rawseti(L, -2, 1);
8210 }
8211 else { /* table */
8212 lua_pushnil(L);
8213 while (lua_next(L, -2) != 0) {
8214 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8215 if (!lua_isstring(L, -1)) {
8216 /* invalid value type, skip it*/
8217 lua_pop(L, 1);
8218 continue;
8219 }
8220 /* push the value in the inner table */
8221 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8222 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8223 }
8224 lua_pop(L, 1);
8225 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8226 }
8227
8228 /* push (k,v) on the stack in the headers table:
8229 * stack: [ ... <headers:table>, <table>, k, k, v ]
8230 */
8231 lua_settable(L, -5);
8232 /* stack: [ ... <headers:table>, <table>, k ] */
8233 }
8234 }
8235 lua_pop(L, 1);
8236 }
8237 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8238 lua_settable(L, -3);
8239 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8240
8241 /* Pop a class sesison metatable and affect it to the userdata. */
8242 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8243 lua_setmetatable(L, -2);
8244 return 1;
8245}
8246
8247/* Set the reply status code, and optionally the reason. If no reason is
8248 * provided, the default one corresponding to the status code is used.
8249 */
8250__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8251{
8252 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8253 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8254
8255 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008256 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008257
8258 if (status < 100 || status > 599) {
8259 lua_pushboolean(L, 0);
8260 return 1;
8261 }
8262 if (!reason)
8263 reason = http_get_reason(status);
8264
8265 lua_pushinteger(L, status);
8266 lua_setfield(L, 1, "status");
8267
8268 lua_pushstring(L, reason);
8269 lua_setfield(L, 1, "reason");
8270
8271 lua_pushboolean(L, 1);
8272 return 1;
8273}
8274
8275/* Add a header into the reply object. Each header name is associated to an
8276 * array of values in the "headers" table. If the header name is not found, a
8277 * new entry is created.
8278 */
8279__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8280{
8281 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8282 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8283 int ret;
8284
8285 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008286 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008287
8288 /* Push in the stack the "headers" entry. */
8289 ret = lua_getfield(L, 1, "headers");
8290 if (ret != LUA_TTABLE) {
8291 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8292 WILL_LJMP(lua_error(L));
8293 }
8294
8295 /* check if the header is already registered. If not, register it. */
8296 ret = lua_getfield(L, -1, name);
8297 if (ret == LUA_TNIL) {
8298 /* Entry not found. */
8299 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8300
8301 /* Insert the new header name in the array in the top of the stack.
8302 * It left the new array in the top of the stack.
8303 */
8304 lua_newtable(L);
8305 lua_pushstring(L, name);
8306 lua_pushvalue(L, -2);
8307 lua_settable(L, -4);
8308 }
8309 else if (ret != LUA_TTABLE) {
8310 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8311 WILL_LJMP(lua_error(L));
8312 }
8313
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008314 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008315 * the header value as new entry.
8316 */
8317 lua_pushstring(L, value);
8318 ret = lua_rawlen(L, -2);
8319 lua_rawseti(L, -2, ret + 1);
8320
8321 lua_pushboolean(L, 1);
8322 return 1;
8323}
8324
8325/* Remove all occurrences of a given header name. */
8326__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8327{
8328 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8329 int ret;
8330
8331 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008332 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008333
8334 /* Push in the stack the "headers" entry. */
8335 ret = lua_getfield(L, 1, "headers");
8336 if (ret != LUA_TTABLE) {
8337 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8338 WILL_LJMP(lua_error(L));
8339 }
8340
8341 lua_pushstring(L, name);
8342 lua_pushnil(L);
8343 lua_settable(L, -3);
8344
8345 lua_pushboolean(L, 1);
8346 return 1;
8347}
8348
8349/* Set the reply's body. Overwrite any existing entry. */
8350__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8351{
8352 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8353
8354 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008355 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008356
8357 lua_pushstring(L, payload);
8358 lua_setfield(L, 1, "body");
8359
8360 lua_pushboolean(L, 1);
8361 return 1;
8362}
8363
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008364__LJMP static int hlua_log(lua_State *L)
8365{
8366 int level;
8367 const char *msg;
8368
8369 MAY_LJMP(check_args(L, 2, "log"));
8370 level = MAY_LJMP(luaL_checkinteger(L, 1));
8371 msg = MAY_LJMP(luaL_checkstring(L, 2));
8372
8373 if (level < 0 || level >= NB_LOG_LEVELS)
8374 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8375
8376 hlua_sendlog(NULL, level, msg);
8377 return 0;
8378}
8379
8380__LJMP static int hlua_log_debug(lua_State *L)
8381{
8382 const char *msg;
8383
8384 MAY_LJMP(check_args(L, 1, "debug"));
8385 msg = MAY_LJMP(luaL_checkstring(L, 1));
8386 hlua_sendlog(NULL, LOG_DEBUG, msg);
8387 return 0;
8388}
8389
8390__LJMP static int hlua_log_info(lua_State *L)
8391{
8392 const char *msg;
8393
8394 MAY_LJMP(check_args(L, 1, "info"));
8395 msg = MAY_LJMP(luaL_checkstring(L, 1));
8396 hlua_sendlog(NULL, LOG_INFO, msg);
8397 return 0;
8398}
8399
8400__LJMP static int hlua_log_warning(lua_State *L)
8401{
8402 const char *msg;
8403
8404 MAY_LJMP(check_args(L, 1, "warning"));
8405 msg = MAY_LJMP(luaL_checkstring(L, 1));
8406 hlua_sendlog(NULL, LOG_WARNING, msg);
8407 return 0;
8408}
8409
8410__LJMP static int hlua_log_alert(lua_State *L)
8411{
8412 const char *msg;
8413
8414 MAY_LJMP(check_args(L, 1, "alert"));
8415 msg = MAY_LJMP(luaL_checkstring(L, 1));
8416 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008417 return 0;
8418}
8419
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008420__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008421{
8422 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008423 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008424 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008425 return 0;
8426}
8427
8428__LJMP static int hlua_sleep(lua_State *L)
8429{
8430 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008431 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008432
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008433 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008434
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008435 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008436 wakeup_ms = tick_add(now_ms, delay);
8437 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008438
Willy Tarreau9635e032018-10-16 17:52:55 +02008439 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008440 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008441}
8442
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008443__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008444{
8445 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008446 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008447
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008448 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008449
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008450 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008451 wakeup_ms = tick_add(now_ms, delay);
8452 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008453
Willy Tarreau9635e032018-10-16 17:52:55 +02008454 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008455 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008456}
8457
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008458/* This functionis an LUA binding. it permits to give back
8459 * the hand at the HAProxy scheduler. It is used when the
8460 * LUA processing consumes a lot of time.
8461 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008462__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008463{
8464 return 0;
8465}
8466
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008467__LJMP static int hlua_yield(lua_State *L)
8468{
Willy Tarreau9635e032018-10-16 17:52:55 +02008469 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008470 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008471}
8472
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008473/* This function change the nice of the currently executed
8474 * task. It is used set low or high priority at the current
8475 * task.
8476 */
Willy Tarreau59551662015-03-10 14:23:13 +01008477__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008478{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008479 struct hlua *hlua;
8480 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008481
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008482 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008483 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008484
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008485 /* Get hlua struct, or NULL if we execute from main lua state */
8486 hlua = hlua_gethlua(L);
8487
8488 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008489 if (!hlua || !hlua->task)
8490 return 0;
8491
8492 if (nice < -1024)
8493 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008494 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008495 nice = 1024;
8496
8497 hlua->task->nice = nice;
8498 return 0;
8499}
8500
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008501/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008502 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8503 * return an E_AGAIN signal, the emmiter of this signal must set a
8504 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008505 *
8506 * Task wrapper are longjmp safe because the only one Lua code
8507 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008508 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008509struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008510{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008511 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008512 enum hlua_exec status;
8513
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008514 if (task->tid < 0)
8515 task->tid = tid;
8516
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008517 /* If it is the first call to the task, we must initialize the
8518 * execution timeouts.
8519 */
8520 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008521 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008522
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008523 /* Execute the Lua code. */
8524 status = hlua_ctx_resume(hlua, 1);
8525
8526 switch (status) {
8527 /* finished or yield */
8528 case HLUA_E_OK:
8529 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008530 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008531 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008532 break;
8533
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008534 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008535 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008536 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008537 break;
8538
8539 /* finished with error. */
8540 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008541 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008542 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008543 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008544 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008545 break;
8546
8547 case HLUA_E_ERR:
8548 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008549 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008550 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008551 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008552 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008553 break;
8554 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008555 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008556}
8557
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008558/* This function is an LUA binding that register LUA function to be
8559 * executed after the HAProxy configuration parsing and before the
8560 * HAProxy scheduler starts. This function expect only one LUA
8561 * argument that is a function. This function returns nothing, but
8562 * throws if an error is encountered.
8563 */
8564__LJMP static int hlua_register_init(lua_State *L)
8565{
8566 struct hlua_init_function *init;
8567 int ref;
8568
8569 MAY_LJMP(check_args(L, 1, "register_init"));
8570
8571 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8572
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008573 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008574 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008575 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008576
8577 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008578 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008579 return 0;
8580}
8581
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008582/* This functio is an LUA binding. It permits to register a task
8583 * executed in parallel of the main HAroxy activity. The task is
8584 * created and it is set in the HAProxy scheduler. It can be called
8585 * from the "init" section, "post init" or during the runtime.
8586 *
8587 * Lua prototype:
8588 *
8589 * <none> core.register_task(<function>)
8590 */
8591static int hlua_register_task(lua_State *L)
8592{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008593 struct hlua *hlua = NULL;
8594 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008595 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008596 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008597
8598 MAY_LJMP(check_args(L, 1, "register_task"));
8599
8600 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8601
Thierry Fournier75fc0292020-11-28 13:18:56 +01008602 /* Get the reference state. If the reference is NULL, L is the master
8603 * state, otherwise hlua->T is.
8604 */
8605 hlua = hlua_gethlua(L);
8606 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008607 /* we are in runtime processing */
8608 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008609 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008610 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008611 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008612
Willy Tarreaubafbe012017-11-24 17:34:44 +01008613 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008614 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008615 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008616 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008617
Thierry Fournier59f11be2020-11-29 00:37:41 +01008618 /* We are in the common lua state, execute the task anywhere,
8619 * otherwise, inherit the current thread identifier
8620 */
8621 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008622 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008623 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008624 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008625 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008626 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008627
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008628 task->context = hlua;
8629 task->process = hlua_process_task;
8630
Thierry Fournier021d9862020-11-28 23:42:03 +01008631 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008632 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008633
8634 /* Restore the function in the stack. */
8635 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8636 hlua->nargs = 0;
8637
8638 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008639 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008640
8641 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008642
8643 alloc_error:
8644 task_destroy(task);
8645 hlua_ctx_destroy(hlua);
8646 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8647 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008648}
8649
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008650/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8651 * doesn't allow "yield" functions because the HAProxy engine cannot
8652 * resume converters.
8653 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008654static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008655{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008656 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008657 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008658 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008659
Willy Tarreaube508f12016-03-10 11:47:01 +01008660 if (!stream)
8661 return 0;
8662
Willy Tarreau87b09662015-04-03 00:22:06 +02008663 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008664 * Lua context can be not initialized. This behavior
8665 * permits to save performances because a systematic
8666 * Lua initialization cause 5% performances loss.
8667 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008668 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008669 struct hlua *hlua;
8670
8671 hlua = pool_alloc(pool_head_hlua);
8672 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008673 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8674 return 0;
8675 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008676 HLUA_INIT(hlua);
8677 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008678 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008679 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8680 return 0;
8681 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008682 }
8683
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008684 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008685 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008686
8687 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008688 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008689 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8690 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008691 else
8692 error = "critical error";
8693 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008694 return 0;
8695 }
8696
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008697 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008698 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008699 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008700 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008701 return 0;
8702 }
8703
8704 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008705 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008706
8707 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008708 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008709 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008710 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008711 return 0;
8712 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008713 hlua_smp2lua(stream->hlua->T, smp);
8714 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008715
8716 /* push keywords in the stack. */
8717 if (arg_p) {
8718 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008719 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008720 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008721 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008722 return 0;
8723 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008724 hlua_arg2lua(stream->hlua->T, arg_p);
8725 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008726 }
8727 }
8728
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008729 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008730 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008731
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008732 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008733 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008734 }
8735
8736 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008737 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008738 /* finished. */
8739 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008740 /* If the stack is empty, the function fails. */
8741 if (lua_gettop(stream->hlua->T) <= 0)
8742 return 0;
8743
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008744 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008745 hlua_lua2smp(stream->hlua->T, -1, smp);
8746 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008747 return 1;
8748
8749 /* yield. */
8750 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008751 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008752 return 0;
8753
8754 /* finished with error. */
8755 case HLUA_E_ERRMSG:
8756 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008757 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008758 fcn->name, lua_tostring(stream->hlua->T, -1));
8759 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008760 return 0;
8761
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008762 case HLUA_E_ETMOUT:
8763 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8764 return 0;
8765
8766 case HLUA_E_NOMEM:
8767 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8768 return 0;
8769
8770 case HLUA_E_YIELD:
8771 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8772 return 0;
8773
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008774 case HLUA_E_ERR:
8775 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008776 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008777 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008778
8779 default:
8780 return 0;
8781 }
8782}
8783
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008784/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8785 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008786 * resume sample-fetches. This function will be called by the sample
8787 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008788 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008789static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8790 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008791{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008792 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008793 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008794 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008795 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008796
Willy Tarreaube508f12016-03-10 11:47:01 +01008797 if (!stream)
8798 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008799
Willy Tarreau87b09662015-04-03 00:22:06 +02008800 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008801 * Lua context can be not initialized. This behavior
8802 * permits to save performances because a systematic
8803 * Lua initialization cause 5% performances loss.
8804 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008805 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008806 struct hlua *hlua;
8807
8808 hlua = pool_alloc(pool_head_hlua);
8809 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008810 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8811 return 0;
8812 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008813 hlua->T = NULL;
8814 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008815 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008816 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8817 return 0;
8818 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008819 }
8820
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008821 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008822 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008823
8824 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008825 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008826 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8827 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008828 else
8829 error = "critical error";
8830 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008831 return 0;
8832 }
8833
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008834 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008835 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008836 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008837 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008838 return 0;
8839 }
8840
8841 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008842 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008843
8844 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008845 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008846 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008847 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008848 return 0;
8849 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008850 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008851
8852 /* push keywords in the stack. */
8853 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8854 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008855 if (!lua_checkstack(stream->hlua->T, 1)) {
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 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008860 hlua_arg2lua(stream->hlua->T, arg_p);
8861 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008862 }
8863
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008864 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008865 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008866
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008867 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008868 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008869 }
8870
8871 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008872 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008873 /* finished. */
8874 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008875 /* If the stack is empty, the function fails. */
8876 if (lua_gettop(stream->hlua->T) <= 0)
8877 return 0;
8878
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008879 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008880 hlua_lua2smp(stream->hlua->T, -1, smp);
8881 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008882
8883 /* Set the end of execution flag. */
8884 smp->flags &= ~SMP_F_MAY_CHANGE;
8885 return 1;
8886
8887 /* yield. */
8888 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008889 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008890 return 0;
8891
8892 /* finished with error. */
8893 case HLUA_E_ERRMSG:
8894 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008895 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008896 fcn->name, lua_tostring(stream->hlua->T, -1));
8897 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008898 return 0;
8899
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008900 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008901 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8902 return 0;
8903
8904 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008905 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8906 return 0;
8907
8908 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008909 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8910 return 0;
8911
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008912 case HLUA_E_ERR:
8913 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008914 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008915 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008916
8917 default:
8918 return 0;
8919 }
8920}
8921
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008922/* This function is an LUA binding used for registering
8923 * "sample-conv" functions. It expects a converter name used
8924 * in the haproxy configuration file, and an LUA function.
8925 */
8926__LJMP static int hlua_register_converters(lua_State *L)
8927{
8928 struct sample_conv_kw_list *sck;
8929 const char *name;
8930 int ref;
8931 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008932 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008933 struct sample_conv *sc;
8934 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008935
8936 MAY_LJMP(check_args(L, 2, "register_converters"));
8937
8938 /* First argument : converter name. */
8939 name = MAY_LJMP(luaL_checkstring(L, 1));
8940
8941 /* Second argument : lua function. */
8942 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8943
Thierry Fournierf67442e2020-11-28 20:41:07 +01008944 /* Check if the converter is already registered */
8945 trash = get_trash_chunk();
8946 chunk_printf(trash, "lua.%s", name);
8947 sc = find_sample_conv(trash->area, trash->data);
8948 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008949 fcn = sc->private;
8950 if (fcn->function_ref[hlua_state_id] != -1) {
8951 ha_warning("Trying to register converter 'lua.%s' more than once. "
8952 "This will become a hard error in version 2.5.\n", name);
8953 }
8954 fcn->function_ref[hlua_state_id] = ref;
8955 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008956 }
8957
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008958 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008959 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008960 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008961 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008962 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008963 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008964 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008965
8966 /* Fill fcn. */
8967 fcn->name = strdup(name);
8968 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008969 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008970 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008971
8972 /* List head */
8973 sck->list.n = sck->list.p = NULL;
8974
8975 /* converter keyword. */
8976 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008977 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008978 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008979 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008980
8981 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8982 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008983 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 +01008984 sck->kw[0].val_args = NULL;
8985 sck->kw[0].in_type = SMP_T_STR;
8986 sck->kw[0].out_type = SMP_T_STR;
8987 sck->kw[0].private = fcn;
8988
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008989 /* Register this new converter */
8990 sample_register_convs(sck);
8991
8992 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008993
8994 alloc_error:
8995 release_hlua_function(fcn);
8996 ha_free(&sck);
8997 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8998 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008999}
9000
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009001/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009002 * "sample-fetch" functions. It expects a converter name used
9003 * in the haproxy configuration file, and an LUA function.
9004 */
9005__LJMP static int hlua_register_fetches(lua_State *L)
9006{
9007 const char *name;
9008 int ref;
9009 int len;
9010 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009011 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009012 struct sample_fetch *sf;
9013 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009014
9015 MAY_LJMP(check_args(L, 2, "register_fetches"));
9016
9017 /* First argument : sample-fetch name. */
9018 name = MAY_LJMP(luaL_checkstring(L, 1));
9019
9020 /* Second argument : lua function. */
9021 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9022
Thierry Fournierf67442e2020-11-28 20:41:07 +01009023 /* Check if the sample-fetch is already registered */
9024 trash = get_trash_chunk();
9025 chunk_printf(trash, "lua.%s", name);
9026 sf = find_sample_fetch(trash->area, trash->data);
9027 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009028 fcn = sf->private;
9029 if (fcn->function_ref[hlua_state_id] != -1) {
9030 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9031 "This will become a hard error in version 2.5.\n", name);
9032 }
9033 fcn->function_ref[hlua_state_id] = ref;
9034 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009035 }
9036
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009037 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009038 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009039 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009040 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009041 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009042 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009043 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009044
9045 /* Fill fcn. */
9046 fcn->name = strdup(name);
9047 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009048 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009049 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009050
9051 /* List head */
9052 sfk->list.n = sfk->list.p = NULL;
9053
9054 /* sample-fetch keyword. */
9055 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009056 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009057 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009058 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009059
9060 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9061 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009062 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 +01009063 sfk->kw[0].val_args = NULL;
9064 sfk->kw[0].out_type = SMP_T_STR;
9065 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9066 sfk->kw[0].val = 0;
9067 sfk->kw[0].private = fcn;
9068
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009069 /* Register this new fetch. */
9070 sample_register_fetches(sfk);
9071
9072 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009073
9074 alloc_error:
9075 release_hlua_function(fcn);
9076 ha_free(&sfk);
9077 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9078 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009079}
9080
Christopher Faulet501465d2020-02-26 14:54:16 +01009081/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009082 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009083__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009084{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009085 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009086 unsigned int delay;
9087 unsigned int wakeup_ms;
9088
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009089 /* Get hlua struct, or NULL if we execute from main lua state */
9090 hlua = hlua_gethlua(L);
9091 if (!hlua) {
9092 return 0;
9093 }
9094
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009095 MAY_LJMP(check_args(L, 1, "wake_time"));
9096
9097 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9098 wakeup_ms = tick_add(now_ms, delay);
9099 hlua->wake_time = wakeup_ms;
9100 return 0;
9101}
9102
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009103/* This function is a wrapper to execute each LUA function declared as an action
9104 * wrapper during the initialisation period. This function may return any
9105 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9106 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9107 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009108 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009109static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009110 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009111{
9112 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009113 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009114 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009115 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009116
9117 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009118 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9119 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9120 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9121 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009122 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009123 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009124 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009125 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009126
Willy Tarreau87b09662015-04-03 00:22:06 +02009127 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009128 * Lua context can be not initialized. This behavior
9129 * permits to save performances because a systematic
9130 * Lua initialization cause 5% performances loss.
9131 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009132 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009133 struct hlua *hlua;
9134
9135 hlua = pool_alloc(pool_head_hlua);
9136 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009137 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009138 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009139 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009140 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009141 HLUA_INIT(hlua);
9142 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009143 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 +01009144 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009145 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009146 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009147 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009148 }
9149
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009150 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009151 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009152
9153 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009154 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009155 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9156 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009157 else
9158 error = "critical error";
9159 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009160 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009161 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009162 }
9163
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009164 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009165 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009166 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009167 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009168 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009169 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009170 }
9171
9172 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009173 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 +01009174
Willy Tarreau87b09662015-04-03 00:22:06 +02009175 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009176 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009177 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009178 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009179 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009180 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009181 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009182 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009183
9184 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009185 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009186 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009187 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009188 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009189 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009190 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009191 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009192 lua_pushstring(s->hlua->T, *arg);
9193 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009194 }
9195
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009196 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009197 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009198
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009199 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009200 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009201 }
9202
9203 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009204 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009205 /* finished. */
9206 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009207 /* Catch the return value */
9208 if (lua_gettop(s->hlua->T) > 0)
9209 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009210
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009211 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009212 if (act_ret == ACT_RET_YIELD) {
9213 if (flags & ACT_OPT_FINAL)
9214 goto err_yield;
9215
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009216 if (dir == SMP_OPT_DIR_REQ)
9217 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9218 s->hlua->wake_time);
9219 else
9220 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9221 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009222 }
9223 goto end;
9224
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009225 /* yield. */
9226 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009227 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009228 if (dir == SMP_OPT_DIR_REQ)
9229 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9230 s->hlua->wake_time);
9231 else
9232 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9233 s->hlua->wake_time);
9234
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009235 /* Some actions can be wake up when a "write" event
9236 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009237 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009238 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009239 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009240 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009241 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009242 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009243 act_ret = ACT_RET_YIELD;
9244 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009245
9246 /* finished with error. */
9247 case HLUA_E_ERRMSG:
9248 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009249 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009250 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009251 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009252 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009253
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009254 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009255 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009256 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009257
9258 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009259 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009260 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009261
9262 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009263 err_yield:
9264 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009265 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009266 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009267 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009268
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009269 case HLUA_E_ERR:
9270 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009271 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009272 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009273
9274 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009275 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009276 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009277
9278 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009279 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009280 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009281 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009282}
9283
Willy Tarreau144f84a2021-03-02 16:09:26 +01009284struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009285{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009286 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009287
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009288 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009289 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009290 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009291}
9292
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009293static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009294{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009295 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009296 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009297 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009298 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299 struct task *task;
9300 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009301 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009302
Willy Tarreaubafbe012017-11-24 17:34:44 +01009303 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009304 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009305 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009306 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009307 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009308 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009309 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009310 tcp_ctx->hlua = hlua;
9311 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009312
9313 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009314 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009315 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009316 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009317 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009318 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009319 }
9320 task->nice = 0;
9321 task->context = ctx;
9322 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009323 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009324
9325 /* In the execution wrappers linked with a stream, the
9326 * Lua context can be not initialized. This behavior
9327 * permits to save performances because a systematic
9328 * Lua initialization cause 5% performances loss.
9329 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009330 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 +01009331 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009332 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009333 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009334 }
9335
9336 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009337 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009338
9339 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009340 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009341 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9342 error = lua_tostring(hlua->T, -1);
9343 else
9344 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009345 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009346 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009347 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009348 }
9349
9350 /* Check stack available size. */
9351 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009352 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009353 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009354 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009355 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009356 }
9357
9358 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009359 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009360
9361 /* Create and and push object stream in the stack. */
9362 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009363 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009364 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009365 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009366 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009367 }
9368 hlua->nargs = 1;
9369
9370 /* push keywords in the stack. */
9371 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9372 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009373 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009374 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009375 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009376 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009377 }
9378 lua_pushstring(hlua->T, *arg);
9379 hlua->nargs++;
9380 }
9381
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009382 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009383
9384 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009385 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009386 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387
Christopher Fauletc9929382022-05-12 11:52:27 +02009388 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009389}
9390
Willy Tarreau60409db2019-08-21 14:14:50 +02009391void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009392{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009393 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009394 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009395 struct stream *strm = __sc_strm(sc);
9396 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009397 struct act_rule *rule = ctx->rule;
9398 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009399 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009400
9401 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009402 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009403 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009404 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009405 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009406 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009407
9408 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009409 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009410 return;
9411
9412 /* Execute the function. */
9413 switch (hlua_ctx_resume(hlua, 1)) {
9414 /* finished. */
9415 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009416 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009417
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009418 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009419 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009420 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009421 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009422 return;
9423
9424 /* yield. */
9425 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009426 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009427 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009428 return;
9429
9430 /* finished with error. */
9431 case HLUA_E_ERRMSG:
9432 /* Display log. */
9433 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009434 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009435 lua_pop(hlua->T, 1);
9436 goto error;
9437
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009438 case HLUA_E_ETMOUT:
9439 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009440 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009441 goto error;
9442
9443 case HLUA_E_NOMEM:
9444 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009445 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009446 goto error;
9447
9448 case HLUA_E_YIELD: /* unexpected */
9449 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009450 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009451 goto error;
9452
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009453 case HLUA_E_ERR:
9454 /* Display log. */
9455 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009456 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009457 goto error;
9458
9459 default:
9460 goto error;
9461 }
9462
9463error:
9464
9465 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009466 sc_shutw(sc);
9467 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009468 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009469}
9470
9471static void hlua_applet_tcp_release(struct appctx *ctx)
9472{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009473 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9474
9475 task_destroy(tcp_ctx->task);
9476 tcp_ctx->task = NULL;
9477 hlua_ctx_destroy(tcp_ctx->hlua);
9478 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009479}
9480
Christopher Fauletc9929382022-05-12 11:52:27 +02009481/* The function returns 0 if the initialisation is complete or -1 if
9482 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009483 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009484static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009485{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009486 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009487 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009488 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009489 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009490 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009491 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009492 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009493 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009494
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009495 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009496 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009497 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009498 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009499 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009500 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009501 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009502 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009503 http_ctx->hlua = hlua;
9504 http_ctx->left_bytes = -1;
9505 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009506
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009507 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009508 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009509
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009510 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009511 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009512 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009513 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009514 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009515 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009516 }
9517 task->nice = 0;
9518 task->context = ctx;
9519 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009520 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009521
9522 /* In the execution wrappers linked with a stream, the
9523 * Lua context can be not initialized. This behavior
9524 * permits to save performances because a systematic
9525 * Lua initialization cause 5% performances loss.
9526 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009527 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 +01009528 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009529 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009530 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009531 }
9532
9533 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009534 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009535
9536 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009537 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009538 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9539 error = lua_tostring(hlua->T, -1);
9540 else
9541 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009542 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009543 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009544 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009545 }
9546
9547 /* Check stack available size. */
9548 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009549 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009550 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009551 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009552 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009553 }
9554
9555 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009556 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009557
9558 /* Create and and push object stream in the stack. */
9559 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009560 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009561 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009562 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009563 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009564 }
9565 hlua->nargs = 1;
9566
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009567 /* push keywords in the stack. */
9568 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9569 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009570 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009571 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009572 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009573 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009574 }
9575 lua_pushstring(hlua->T, *arg);
9576 hlua->nargs++;
9577 }
9578
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009579 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009580
9581 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009582 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009583
Christopher Fauletc9929382022-05-12 11:52:27 +02009584 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009585}
9586
Willy Tarreau60409db2019-08-21 14:14:50 +02009587void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009588{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009589 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009590 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009591 struct stream *strm = __sc_strm(sc);
9592 struct channel *req = sc_oc(sc);
9593 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009594 struct act_rule *rule = ctx->rule;
9595 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009596 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009597 struct htx *req_htx, *res_htx;
9598
9599 res_htx = htx_from_buf(&res->buf);
9600
9601 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009602 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009603 goto out;
9604
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009605 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009606 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009607 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009608 goto out;
9609 }
9610 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009611 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009612 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009613
9614 /* Set the currently running flag. */
9615 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009616 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009617 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009618 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009619 goto out;
9620 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009621 }
9622
9623 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009624 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009625
9626 /* Execute the function. */
9627 switch (hlua_ctx_resume(hlua, 1)) {
9628 /* finished. */
9629 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009630 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009631 break;
9632
9633 /* yield. */
9634 case HLUA_E_AGAIN:
9635 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009636 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009637 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009638
9639 /* finished with error. */
9640 case HLUA_E_ERRMSG:
9641 /* Display log. */
9642 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009643 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009644 lua_pop(hlua->T, 1);
9645 goto error;
9646
9647 case HLUA_E_ETMOUT:
9648 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009649 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009650 goto error;
9651
9652 case HLUA_E_NOMEM:
9653 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009654 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009655 goto error;
9656
9657 case HLUA_E_YIELD: /* unexpected */
9658 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009659 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009660 goto error;
9661
9662 case HLUA_E_ERR:
9663 /* Display log. */
9664 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009665 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009666 goto error;
9667
9668 default:
9669 goto error;
9670 }
9671 }
9672
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009673 if (http_ctx->flags & APPLET_DONE) {
9674 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009675 goto done;
9676
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009677 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009678 goto error;
9679
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009680 /* no more data are expected. If the response buffer is empty
9681 * for a chunked message, be sure to add something (EOT block in
9682 * this case) to have something to send. It is important to be
9683 * sure the EOM flags will be handled by the endpoint.
9684 */
9685 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9686 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009687 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009688 goto out;
9689 }
9690 channel_add_input(res, 1);
9691 }
9692
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009693 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009694 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009695 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009696 strm->txn->status = http_ctx->status;
9697 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009698 }
9699
9700 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009701 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009702 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009703 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009704 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009705 }
9706
9707 /* eat the whole request */
9708 if (co_data(req)) {
9709 req_htx = htx_from_buf(&req->buf);
9710 co_htx_skip(req, req_htx, co_data(req));
9711 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009712 }
9713 }
9714
9715 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009716 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009717 return;
9718
9719 error:
9720
9721 /* If we are in HTTP mode, and we are not send any
9722 * data, return a 500 server error in best effort:
9723 * if there is no room available in the buffer,
9724 * just close the connection.
9725 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009726 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009727 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009728
9729 channel_erase(res);
9730 res->buf.data = b_data(err);
9731 memcpy(res->buf.area, b_head(err), b_data(err));
9732 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009733 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009734 }
9735 if (!(strm->flags & SF_ERR_MASK))
9736 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009737 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009738 goto done;
9739}
9740
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009741static void hlua_applet_http_release(struct appctx *ctx)
9742{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009743 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9744
9745 task_destroy(http_ctx->task);
9746 http_ctx->task = NULL;
9747 hlua_ctx_destroy(http_ctx->hlua);
9748 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009749}
9750
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009751/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009752 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009753 *
9754 * This function can fail with an abort() due to an Lua critical error.
9755 * We are in the configuration parsing process of HAProxy, this abort() is
9756 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009757 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009758static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9759 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009760{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009761 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009762 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009763
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009764 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009765 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009766 if (!rule->arg.hlua_rule) {
9767 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009768 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009769 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009770
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009771 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009772 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9773 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009774 if (!rule->arg.hlua_rule->args) {
9775 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009776 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009777 }
9778
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009779 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009780 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009781
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009782 /* Expect some arguments */
9783 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009784 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009785 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009786 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009787 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009788 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009789 if (!rule->arg.hlua_rule->args[i]) {
9790 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009791 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009792 }
9793 (*cur_arg)++;
9794 }
9795 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009796
Thierry FOURNIER42148732015-09-02 17:17:33 +02009797 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009798 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009799 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009800
9801 error:
9802 if (rule->arg.hlua_rule) {
9803 if (rule->arg.hlua_rule->args) {
9804 for (i = 0; i < fcn->nargs; i++)
9805 ha_free(&rule->arg.hlua_rule->args[i]);
9806 ha_free(&rule->arg.hlua_rule->args);
9807 }
9808 ha_free(&rule->arg.hlua_rule);
9809 }
9810 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009811}
9812
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009813static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9814 struct act_rule *rule, char **err)
9815{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009816 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009817
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009818 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009819 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009820 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009821 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009822 * the call of this analyzer.
9823 */
9824 if (rule->from != ACT_F_HTTP_REQ) {
9825 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9826 return ACT_RET_PRS_ERR;
9827 }
9828
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009829 /* Memory for the rule. */
9830 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9831 if (!rule->arg.hlua_rule) {
9832 memprintf(err, "out of memory error");
9833 return ACT_RET_PRS_ERR;
9834 }
9835
9836 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009837 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009838
9839 /* TODO: later accept arguments. */
9840 rule->arg.hlua_rule->args = NULL;
9841
9842 /* Add applet pointer in the rule. */
9843 rule->applet.obj_type = OBJ_TYPE_APPLET;
9844 rule->applet.name = fcn->name;
9845 rule->applet.init = hlua_applet_http_init;
9846 rule->applet.fct = hlua_applet_http_fct;
9847 rule->applet.release = hlua_applet_http_release;
9848 rule->applet.timeout = hlua_timeout_applet;
9849
9850 return ACT_RET_PRS_OK;
9851}
9852
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009853/* This function is an LUA binding used for registering
9854 * "sample-conv" functions. It expects a converter name used
9855 * in the haproxy configuration file, and an LUA function.
9856 */
9857__LJMP static int hlua_register_action(lua_State *L)
9858{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009859 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009860 const char *name;
9861 int ref;
9862 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009863 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009864 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009865 struct buffer *trash;
9866 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009867
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009868 /* Initialise the number of expected arguments at 0. */
9869 nargs = 0;
9870
9871 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9872 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009873
9874 /* First argument : converter name. */
9875 name = MAY_LJMP(luaL_checkstring(L, 1));
9876
9877 /* Second argument : environment. */
9878 if (lua_type(L, 2) != LUA_TTABLE)
9879 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9880
9881 /* Third argument : lua function. */
9882 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9883
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009884 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009885 if (lua_gettop(L) >= 4)
9886 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9887
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009888 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009889 lua_pushnil(L);
9890 while (lua_next(L, 2) != 0) {
9891 if (lua_type(L, -1) != LUA_TSTRING)
9892 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9893
Thierry Fournierf67442e2020-11-28 20:41:07 +01009894 /* Check if action exists */
9895 trash = get_trash_chunk();
9896 chunk_printf(trash, "lua.%s", name);
9897 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9898 akw = tcp_req_cont_action(trash->area);
9899 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9900 akw = tcp_res_cont_action(trash->area);
9901 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9902 akw = action_http_req_custom(trash->area);
9903 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9904 akw = action_http_res_custom(trash->area);
9905 } else {
9906 akw = NULL;
9907 }
9908 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009909 fcn = akw->private;
9910 if (fcn->function_ref[hlua_state_id] != -1) {
9911 ha_warning("Trying to register action 'lua.%s' more than once. "
9912 "This will become a hard error in version 2.5.\n", name);
9913 }
9914 fcn->function_ref[hlua_state_id] = ref;
9915
9916 /* pop the environment string. */
9917 lua_pop(L, 1);
9918 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009919 }
9920
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009921 /* Check required environment. Only accepted "http" or "tcp". */
9922 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009923 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009924 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009925 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009926 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009927 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009928 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009929
9930 /* Fill fcn. */
9931 fcn->name = strdup(name);
9932 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009933 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009934 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009935
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009936 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009937 fcn->nargs = nargs;
9938
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009939 /* List head */
9940 akl->list.n = akl->list.p = NULL;
9941
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009942 /* action keyword. */
9943 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009944 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009945 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009946 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009947
9948 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9949
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009950 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009951 akl->kw[0].private = fcn;
9952 akl->kw[0].parse = action_register_lua;
9953
9954 /* select the action registering point. */
9955 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9956 tcp_req_cont_keywords_register(akl);
9957 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9958 tcp_res_cont_keywords_register(akl);
9959 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9960 http_req_keywords_register(akl);
9961 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9962 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009963 else {
9964 release_hlua_function(fcn);
9965 if (akl)
9966 ha_free((char **)&(akl->kw[0].kw));
9967 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009968 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009969 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9970 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009971 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009972
9973 /* pop the environment string. */
9974 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009975
9976 /* reset for next loop */
9977 akl = NULL;
9978 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009979 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009980 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009981
9982 alloc_error:
9983 release_hlua_function(fcn);
9984 ha_free(&akl);
9985 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9986 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009987}
9988
9989static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9990 struct act_rule *rule, char **err)
9991{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009992 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009993
Christopher Faulet280f85b2019-07-15 15:02:04 +02009994 if (px->mode == PR_MODE_HTTP) {
9995 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009996 return ACT_RET_PRS_ERR;
9997 }
9998
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009999 /* Memory for the rule. */
10000 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10001 if (!rule->arg.hlua_rule) {
10002 memprintf(err, "out of memory error");
10003 return ACT_RET_PRS_ERR;
10004 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010005
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010006 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010007 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010008
10009 /* TODO: later accept arguments. */
10010 rule->arg.hlua_rule->args = NULL;
10011
10012 /* Add applet pointer in the rule. */
10013 rule->applet.obj_type = OBJ_TYPE_APPLET;
10014 rule->applet.name = fcn->name;
10015 rule->applet.init = hlua_applet_tcp_init;
10016 rule->applet.fct = hlua_applet_tcp_fct;
10017 rule->applet.release = hlua_applet_tcp_release;
10018 rule->applet.timeout = hlua_timeout_applet;
10019
10020 return 0;
10021}
10022
10023/* This function is an LUA binding used for registering
10024 * "sample-conv" functions. It expects a converter name used
10025 * in the haproxy configuration file, and an LUA function.
10026 */
10027__LJMP static int hlua_register_service(lua_State *L)
10028{
10029 struct action_kw_list *akl;
10030 const char *name;
10031 const char *env;
10032 int ref;
10033 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010034 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010035 struct buffer *trash;
10036 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010037
10038 MAY_LJMP(check_args(L, 3, "register_service"));
10039
10040 /* First argument : converter name. */
10041 name = MAY_LJMP(luaL_checkstring(L, 1));
10042
10043 /* Second argument : environment. */
10044 env = MAY_LJMP(luaL_checkstring(L, 2));
10045
10046 /* Third argument : lua function. */
10047 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10048
Thierry Fournierf67442e2020-11-28 20:41:07 +010010049 /* Check for service already registered */
10050 trash = get_trash_chunk();
10051 chunk_printf(trash, "lua.%s", name);
10052 akw = service_find(trash->area);
10053 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010054 fcn = akw->private;
10055 if (fcn->function_ref[hlua_state_id] != -1) {
10056 ha_warning("Trying to register service 'lua.%s' more than once. "
10057 "This will become a hard error in version 2.5.\n", name);
10058 }
10059 fcn->function_ref[hlua_state_id] = ref;
10060 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010061 }
10062
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010063 /* Allocate and fill the sample fetch keyword struct. */
10064 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10065 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010066 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010067 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010068 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010069 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010070
10071 /* Fill fcn. */
10072 len = strlen("<lua.>") + strlen(name) + 1;
10073 fcn->name = calloc(1, len);
10074 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010075 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010076 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010077 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010078
10079 /* List head */
10080 akl->list.n = akl->list.p = NULL;
10081
10082 /* converter keyword. */
10083 len = strlen("lua.") + strlen(name) + 1;
10084 akl->kw[0].kw = calloc(1, len);
10085 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010086 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010087
10088 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10089
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010090 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010091 if (strcmp(env, "tcp") == 0)
10092 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010093 else if (strcmp(env, "http") == 0)
10094 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010095 else {
10096 release_hlua_function(fcn);
10097 if (akl)
10098 ha_free((char **)&(akl->kw[0].kw));
10099 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010100 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010101 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010102 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010103
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010104 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010105 akl->kw[0].private = fcn;
10106
10107 /* End of array. */
10108 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10109
10110 /* Register this new converter */
10111 service_keywords_register(akl);
10112
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010113 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010114
10115 alloc_error:
10116 release_hlua_function(fcn);
10117 ha_free(&akl);
10118 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10119 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010120}
10121
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010122/* This function initialises Lua cli handler. It copies the
10123 * arguments in the Lua stack and create channel IO objects.
10124 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010125static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010126{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010127 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010128 struct hlua *hlua;
10129 struct hlua_function *fcn;
10130 int i;
10131 const char *error;
10132
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010133 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010134 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010135
Willy Tarreaubafbe012017-11-24 17:34:44 +010010136 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010137 if (!hlua) {
10138 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010139 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010140 }
10141 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010142 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010143
10144 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010145 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010146 * applet_http. It is absolutely compatible.
10147 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010148 ctx->task = task_new_here();
10149 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010150 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010151 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010152 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010153 ctx->task->nice = 0;
10154 ctx->task->context = appctx;
10155 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010156
10157 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010158 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010159 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010160 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010161 }
10162
10163 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010164 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010165 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10166 error = lua_tostring(hlua->T, -1);
10167 else
10168 error = "critical error";
10169 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10170 goto error;
10171 }
10172
10173 /* Check stack available size. */
10174 if (!lua_checkstack(hlua->T, 2)) {
10175 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10176 goto error;
10177 }
10178
10179 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010180 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010181
10182 /* Once the arguments parsed, the CLI is like an AppletTCP,
10183 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010184 */
10185 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10186 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10187 goto error;
10188 }
10189 hlua->nargs = 1;
10190
10191 /* push keywords in the stack. */
10192 for (i = 0; *args[i]; i++) {
10193 /* Check stack available size. */
10194 if (!lua_checkstack(hlua->T, 1)) {
10195 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10196 goto error;
10197 }
10198 lua_pushstring(hlua->T, args[i]);
10199 hlua->nargs++;
10200 }
10201
10202 /* We must initialize the execution timeouts. */
10203 hlua->max_time = hlua_timeout_session;
10204
10205 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010206 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010207
10208 /* It's ok */
10209 return 0;
10210
10211 /* It's not ok. */
10212error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010213 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010214 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010215 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010216 return 1;
10217}
10218
10219static int hlua_cli_io_handler_fct(struct appctx *appctx)
10220{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010221 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010222 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010223 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010224 struct hlua_function *fcn;
10225
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010226 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010227 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010228 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010229
10230 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010231 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010232 return 1;
10233
10234 /* Execute the function. */
10235 switch (hlua_ctx_resume(hlua, 1)) {
10236
10237 /* finished. */
10238 case HLUA_E_OK:
10239 return 1;
10240
10241 /* yield. */
10242 case HLUA_E_AGAIN:
10243 /* We want write. */
10244 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010245 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010246 /* Set the timeout. */
10247 if (hlua->wake_time != TICK_ETERNITY)
10248 task_schedule(hlua->task, hlua->wake_time);
10249 return 0;
10250
10251 /* finished with error. */
10252 case HLUA_E_ERRMSG:
10253 /* Display log. */
10254 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10255 fcn->name, lua_tostring(hlua->T, -1));
10256 lua_pop(hlua->T, 1);
10257 return 1;
10258
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010259 case HLUA_E_ETMOUT:
10260 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10261 fcn->name);
10262 return 1;
10263
10264 case HLUA_E_NOMEM:
10265 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10266 fcn->name);
10267 return 1;
10268
10269 case HLUA_E_YIELD: /* unexpected */
10270 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10271 fcn->name);
10272 return 1;
10273
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010274 case HLUA_E_ERR:
10275 /* Display log. */
10276 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10277 fcn->name);
10278 return 1;
10279
10280 default:
10281 return 1;
10282 }
10283
10284 return 1;
10285}
10286
10287static void hlua_cli_io_release_fct(struct appctx *appctx)
10288{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010289 struct hlua_cli_ctx *ctx = appctx->svcctx;
10290
10291 hlua_ctx_destroy(ctx->hlua);
10292 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010293}
10294
10295/* This function is an LUA binding used for registering
10296 * new keywords in the cli. It expects a list of keywords
10297 * which are the "path". It is limited to 5 keywords. A
10298 * description of the command, a function to be executed
10299 * for the parsing and a function for io handlers.
10300 */
10301__LJMP static int hlua_register_cli(lua_State *L)
10302{
10303 struct cli_kw_list *cli_kws;
10304 const char *message;
10305 int ref_io;
10306 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010307 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010308 int index;
10309 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010310 struct buffer *trash;
10311 const char *kw[5];
10312 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010313 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010314
10315 MAY_LJMP(check_args(L, 3, "register_cli"));
10316
10317 /* First argument : an array of maximum 5 keywords. */
10318 if (!lua_istable(L, 1))
10319 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10320
10321 /* Second argument : string with contextual message. */
10322 message = MAY_LJMP(luaL_checkstring(L, 2));
10323
10324 /* Third and fourth argument : lua function. */
10325 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10326
Thierry Fournierf67442e2020-11-28 20:41:07 +010010327 /* Check for CLI service already registered */
10328 trash = get_trash_chunk();
10329 index = 0;
10330 lua_pushnil(L);
10331 memset(kw, 0, sizeof(kw));
10332 while (lua_next(L, 1) != 0) {
10333 if (index >= CLI_PREFIX_KW_NB)
10334 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10335 if (lua_type(L, -1) != LUA_TSTRING)
10336 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10337 kw[index] = lua_tostring(L, -1);
10338 if (index == 0)
10339 chunk_printf(trash, "%s", kw[index]);
10340 else
10341 chunk_appendf(trash, " %s", kw[index]);
10342 index++;
10343 lua_pop(L, 1);
10344 }
10345 cli_kw = cli_find_kw_exact((char **)kw);
10346 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010347 fcn = cli_kw->private;
10348 if (fcn->function_ref[hlua_state_id] != -1) {
10349 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10350 "This will become a hard error in version 2.5.\n", trash->area);
10351 }
10352 fcn->function_ref[hlua_state_id] = ref_io;
10353 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010354 }
10355
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010356 /* Allocate and fill the sample fetch keyword struct. */
10357 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010358 if (!cli_kws) {
10359 errmsg = "Lua out of memory error.";
10360 goto error;
10361 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010362 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010363 if (!fcn) {
10364 errmsg = "Lua out of memory error.";
10365 goto error;
10366 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010367
10368 /* Fill path. */
10369 index = 0;
10370 lua_pushnil(L);
10371 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010372 if (index >= 5) {
10373 errmsg = "1st argument must be a table with a maximum of 5 entries";
10374 goto error;
10375 }
10376 if (lua_type(L, -1) != LUA_TSTRING) {
10377 errmsg = "1st argument must be a table filled with strings";
10378 goto error;
10379 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010380 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010381 if (!cli_kws->kw[0].str_kw[index]) {
10382 errmsg = "Lua out of memory error.";
10383 goto error;
10384 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010385 index++;
10386 lua_pop(L, 1);
10387 }
10388
10389 /* Copy help message. */
10390 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010391 if (!cli_kws->kw[0].usage) {
10392 errmsg = "Lua out of memory error.";
10393 goto error;
10394 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010395
10396 /* Fill fcn io handler. */
10397 len = strlen("<lua.cli>") + 1;
10398 for (i = 0; i < index; i++)
10399 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10400 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010401 if (!fcn->name) {
10402 errmsg = "Lua out of memory error.";
10403 goto error;
10404 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010405 strncat((char *)fcn->name, "<lua.cli", len);
10406 for (i = 0; i < index; i++) {
10407 strncat((char *)fcn->name, ".", len);
10408 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10409 }
10410 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010411 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010412
10413 /* Fill last entries. */
10414 cli_kws->kw[0].private = fcn;
10415 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10416 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10417 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10418
10419 /* Register this new converter */
10420 cli_register_kw(cli_kws);
10421
10422 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010423
10424 error:
10425 release_hlua_function(fcn);
10426 if (cli_kws) {
10427 for (i = 0; i < index; i++)
10428 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10429 ha_free((char **)&(cli_kws->kw[0].usage));
10430 }
10431 ha_free(&cli_kws);
10432 WILL_LJMP(luaL_error(L, errmsg));
10433 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010434}
10435
Christopher Faulet69c581a2021-05-31 08:54:04 +020010436static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10437{
10438 struct hlua_flt_config *conf = fconf->conf;
10439 lua_State *L;
10440 int error, pos, state_id, flt_ref;
10441
10442 state_id = reg_flt_to_stack_id(conf->reg);
10443 L = hlua_states[state_id];
10444 pos = lua_gettop(L);
10445
10446 /* The filter parsing function */
10447 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10448
10449 /* Push the filter class on the stack and resolve all callbacks */
10450 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10451
10452 /* Duplicate the filter class so each filter will have its own copy */
10453 lua_newtable(L);
10454 lua_pushnil(L);
10455
10456 while (lua_next(L, pos+2)) {
10457 lua_pushvalue(L, -2);
10458 lua_insert(L, -2);
10459 lua_settable(L, -4);
10460 }
10461 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10462
10463 /* Remove the original lua filter class from the stack */
10464 lua_pop(L, 1);
10465
10466 /* Push the copy on the stack */
10467 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10468
10469 /* extra args are pushed in a table */
10470 lua_newtable(L);
10471 for (pos = 0; conf->args[pos]; pos++) {
10472 /* Check stack available size. */
10473 if (!lua_checkstack(L, 1)) {
10474 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10475 goto error;
10476 }
10477 lua_pushstring(L, conf->args[pos]);
10478 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10479 }
10480
10481 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10482 switch (error) {
10483 case LUA_OK:
10484 /* replace the filter ref */
10485 conf->ref[state_id] = flt_ref;
10486 break;
10487 case LUA_ERRRUN:
10488 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10489 goto error;
10490 case LUA_ERRMEM:
10491 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10492 goto error;
10493 case LUA_ERRERR:
10494 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10495 goto error;
10496#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10497 case LUA_ERRGCMM:
10498 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10499 goto error;
10500#endif
10501 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010502 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010503 goto error;
10504 }
10505
10506 lua_settop(L, 0);
10507 return 0;
10508
10509 error:
10510 lua_settop(L, 0);
10511 return -1;
10512}
10513
10514static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10515{
10516 struct hlua_flt_config *conf = fconf->conf;
10517 lua_State *L;
10518 int state_id;
10519
10520 if (!conf)
10521 return;
10522
10523 state_id = reg_flt_to_stack_id(conf->reg);
10524 L = hlua_states[state_id];
10525 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10526}
10527
10528static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10529{
10530 struct hlua_flt_config *conf = fconf->conf;
10531 int state_id = reg_flt_to_stack_id(conf->reg);
10532
10533 /* Rely on per-thread init for global scripts */
10534 if (!state_id)
10535 return hlua_filter_init_per_thread(px, fconf);
10536 return 0;
10537}
10538
10539static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10540{
10541
10542 if (fconf->conf) {
10543 struct hlua_flt_config *conf = fconf->conf;
10544 int state_id = reg_flt_to_stack_id(conf->reg);
10545 int pos;
10546
10547 /* Rely on per-thread deinit for global scripts */
10548 if (!state_id)
10549 hlua_filter_deinit_per_thread(px, fconf);
10550
10551 for (pos = 0; conf->args[pos]; pos++)
10552 free(conf->args[pos]);
10553 free(conf->args);
10554 }
10555 ha_free(&fconf->conf);
10556 ha_free((char **)&fconf->id);
10557 ha_free(&fconf->ops);
10558}
10559
10560static int hlua_filter_new(struct stream *s, struct filter *filter)
10561{
10562 struct hlua_flt_config *conf = FLT_CONF(filter);
10563 struct hlua_flt_ctx *flt_ctx = NULL;
10564 int ret = 1;
10565
10566 /* In the execution wrappers linked with a stream, the
10567 * Lua context can be not initialized. This behavior
10568 * permits to save performances because a systematic
10569 * Lua initialization cause 5% performances loss.
10570 */
10571 if (!s->hlua) {
10572 struct hlua *hlua;
10573
10574 hlua = pool_alloc(pool_head_hlua);
10575 if (!hlua) {
10576 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10577 conf->reg->name);
10578 ret = 0;
10579 goto end;
10580 }
10581 HLUA_INIT(hlua);
10582 s->hlua = hlua;
10583 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10584 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10585 conf->reg->name);
10586 ret = 0;
10587 goto end;
10588 }
10589 }
10590
10591 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10592 if (!flt_ctx) {
10593 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10594 conf->reg->name);
10595 ret = 0;
10596 goto end;
10597 }
10598 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10599 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10600 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10601 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10602 conf->reg->name);
10603 ret = 0;
10604 goto end;
10605 }
10606 HLUA_INIT(flt_ctx->hlua[0]);
10607 HLUA_INIT(flt_ctx->hlua[1]);
10608 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10609 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10610 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10611 conf->reg->name);
10612 ret = 0;
10613 goto end;
10614 }
10615
10616 if (!HLUA_IS_RUNNING(s->hlua)) {
10617 /* The following Lua calls can fail. */
10618 if (!SET_SAFE_LJMP(s->hlua)) {
10619 const char *error;
10620
10621 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10622 error = lua_tostring(s->hlua->T, -1);
10623 else
10624 error = "critical error";
10625 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10626 ret = 0;
10627 goto end;
10628 }
10629
10630 /* Check stack size. */
10631 if (!lua_checkstack(s->hlua->T, 1)) {
10632 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010633 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010634 ret = 0;
10635 goto end;
10636 }
10637
10638 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10639 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10640 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10641 conf->reg->name);
10642 RESET_SAFE_LJMP(s->hlua);
10643 ret = 0;
10644 goto end;
10645 }
10646 lua_insert(s->hlua->T, -2);
10647
10648 /* Push the copy on the stack */
10649 s->hlua->nargs = 1;
10650
10651 /* We must initialize the execution timeouts. */
10652 s->hlua->max_time = hlua_timeout_session;
10653
10654 /* At this point the execution is safe. */
10655 RESET_SAFE_LJMP(s->hlua);
10656 }
10657
10658 switch (hlua_ctx_resume(s->hlua, 0)) {
10659 case HLUA_E_OK:
10660 /* Nothing returned or not a table, ignore the filter for current stream */
10661 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10662 ret = 0;
10663 goto end;
10664 }
10665
10666 /* Attached the filter pointer to the ctx */
10667 lua_pushstring(s->hlua->T, "__filter");
10668 lua_pushlightuserdata(s->hlua->T, filter);
10669 lua_settable(s->hlua->T, -3);
10670
10671 /* Save a ref on the filter ctx */
10672 lua_pushvalue(s->hlua->T, 1);
10673 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10674 filter->ctx = flt_ctx;
10675 break;
10676 case HLUA_E_ERRMSG:
10677 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10678 ret = -1;
10679 goto end;
10680 case HLUA_E_ETMOUT:
10681 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10682 ret = 0;
10683 goto end;
10684 case HLUA_E_NOMEM:
10685 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10686 ret = 0;
10687 goto end;
10688 case HLUA_E_AGAIN:
10689 case HLUA_E_YIELD:
10690 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10691 " are not allowed from 'new' function.\n", conf->reg->name);
10692 ret = 0;
10693 goto end;
10694 case HLUA_E_ERR:
10695 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10696 ret = 0;
10697 goto end;
10698 default:
10699 ret = 0;
10700 goto end;
10701 }
10702
10703 end:
10704 if (s->hlua)
10705 lua_settop(s->hlua->T, 0);
10706 if (ret <= 0) {
10707 if (flt_ctx) {
10708 hlua_ctx_destroy(flt_ctx->hlua[0]);
10709 hlua_ctx_destroy(flt_ctx->hlua[1]);
10710 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10711 }
10712 }
10713 return ret;
10714}
10715
10716static void hlua_filter_delete(struct stream *s, struct filter *filter)
10717{
10718 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10719
10720 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10721 hlua_ctx_destroy(flt_ctx->hlua[0]);
10722 hlua_ctx_destroy(flt_ctx->hlua[1]);
10723 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10724 filter->ctx = NULL;
10725}
10726
Christopher Faulet9f55a502020-02-25 15:21:02 +010010727static int hlua_filter_from_payload(struct filter *filter)
10728{
10729 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10730
10731 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10732}
10733
Christopher Fauletc404f112020-02-26 15:03:09 +010010734static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10735 int dir, unsigned int flags)
10736{
10737 struct hlua *flt_hlua;
10738 struct hlua_flt_config *conf = FLT_CONF(filter);
10739 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10740 unsigned int hflags = HLUA_TXN_FLT_CTX;
10741 int ret = 1;
10742
10743 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10744 if (!flt_hlua)
10745 goto end;
10746
10747 if (!HLUA_IS_RUNNING(flt_hlua)) {
10748 int extra_idx = lua_gettop(flt_hlua->T);
10749
10750 /* The following Lua calls can fail. */
10751 if (!SET_SAFE_LJMP(flt_hlua)) {
10752 const char *error;
10753
10754 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10755 error = lua_tostring(flt_hlua->T, -1);
10756 else
10757 error = "critical error";
10758 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10759 goto end;
10760 }
10761
10762 /* Check stack size. */
10763 if (!lua_checkstack(flt_hlua->T, 3)) {
10764 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10765 RESET_SAFE_LJMP(flt_hlua);
10766 goto end;
10767 }
10768
10769 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10770 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10771 RESET_SAFE_LJMP(flt_hlua);
10772 goto end;
10773 }
10774 lua_insert(flt_hlua->T, -2);
10775
10776 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10777 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10778 RESET_SAFE_LJMP(flt_hlua);
10779 goto end;
10780 }
10781 flt_hlua->nargs = 2;
10782
10783 if (flags & HLUA_FLT_CB_ARG_CHN) {
10784 if (dir == SMP_OPT_DIR_REQ)
10785 lua_getfield(flt_hlua->T, -1, "req");
10786 else
10787 lua_getfield(flt_hlua->T, -1, "res");
10788 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10789 lua_pushstring(flt_hlua->T, "__filter");
10790 lua_pushlightuserdata(flt_hlua->T, filter);
10791 lua_settable(flt_hlua->T, -3);
10792 }
10793 flt_hlua->nargs++;
10794 }
10795 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010796 if (dir == SMP_OPT_DIR_REQ)
10797 lua_getfield(flt_hlua->T, -1, "http_req");
10798 else
10799 lua_getfield(flt_hlua->T, -1, "http_res");
10800 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10801 lua_pushstring(flt_hlua->T, "__filter");
10802 lua_pushlightuserdata(flt_hlua->T, filter);
10803 lua_settable(flt_hlua->T, -3);
10804 }
10805 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010806 }
10807
10808 /* Check stack size. */
10809 if (!lua_checkstack(flt_hlua->T, 1)) {
10810 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10811 RESET_SAFE_LJMP(flt_hlua);
10812 goto end;
10813 }
10814
10815 while (extra_idx--) {
10816 lua_pushvalue(flt_hlua->T, 1);
10817 lua_remove(flt_hlua->T, 1);
10818 flt_hlua->nargs++;
10819 }
10820
10821 /* We must initialize the execution timeouts. */
10822 flt_hlua->max_time = hlua_timeout_session;
10823
10824 /* At this point the execution is safe. */
10825 RESET_SAFE_LJMP(flt_hlua);
10826 }
10827
10828 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10829 case HLUA_E_OK:
10830 /* Catch the return value if it required */
10831 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10832 ret = lua_tointeger(flt_hlua->T, -1);
10833 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10834 }
10835
10836 /* Set timeout in the required channel. */
10837 if (flt_hlua->wake_time != TICK_ETERNITY) {
10838 if (dir == SMP_OPT_DIR_REQ)
10839 s->req.analyse_exp = flt_hlua->wake_time;
10840 else
10841 s->res.analyse_exp = flt_hlua->wake_time;
10842 }
10843 break;
10844 case HLUA_E_AGAIN:
10845 /* Set timeout in the required channel. */
10846 if (flt_hlua->wake_time != TICK_ETERNITY) {
10847 if (dir == SMP_OPT_DIR_REQ)
10848 s->req.analyse_exp = flt_hlua->wake_time;
10849 else
10850 s->res.analyse_exp = flt_hlua->wake_time;
10851 }
10852 /* Some actions can be wake up when a "write" event
10853 * is detected on a response channel. This is useful
10854 * only for actions targeted on the requests.
10855 */
10856 if (HLUA_IS_WAKERESWR(flt_hlua))
10857 s->res.flags |= CF_WAKE_WRITE;
10858 if (HLUA_IS_WAKEREQWR(flt_hlua))
10859 s->req.flags |= CF_WAKE_WRITE;
10860 ret = 0;
10861 goto end;
10862 case HLUA_E_ERRMSG:
10863 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10864 ret = -1;
10865 goto end;
10866 case HLUA_E_ETMOUT:
10867 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10868 goto end;
10869 case HLUA_E_NOMEM:
10870 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10871 goto end;
10872 case HLUA_E_YIELD:
10873 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10874 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10875 goto end;
10876 case HLUA_E_ERR:
10877 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10878 goto end;
10879 default:
10880 goto end;
10881 }
10882
10883
10884 end:
10885 return ret;
10886}
10887
10888static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10889{
10890 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10891
10892 flt_ctx->flags = 0;
10893 return hlua_filter_callback(s, filter, "start_analyze",
10894 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10895 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10896}
10897
10898static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10899{
10900 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10901
10902 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10903 return hlua_filter_callback(s, filter, "end_analyze",
10904 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10905 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10906}
10907
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010908static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10909{
10910 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10911
10912 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10913 return hlua_filter_callback(s, filter, "http_headers",
10914 (!(msg->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_HTTP_MSG));
10916}
10917
10918static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10919 unsigned int offset, unsigned int len)
10920{
10921 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10922 struct hlua *flt_hlua;
10923 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10924 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10925 int ret;
10926
10927 flt_hlua = flt_ctx->hlua[idx];
10928 flt_ctx->cur_off[idx] = offset;
10929 flt_ctx->cur_len[idx] = len;
10930 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10931 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10932 if (ret != -1) {
10933 ret = flt_ctx->cur_len[idx];
10934 if (lua_gettop(flt_hlua->T) > 0) {
10935 ret = lua_tointeger(flt_hlua->T, -1);
10936 if (ret > flt_ctx->cur_len[idx])
10937 ret = flt_ctx->cur_len[idx];
10938 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10939 }
10940 }
10941 return ret;
10942}
10943
10944static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10945{
10946 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10947
10948 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10949 return hlua_filter_callback(s, filter, "http_end",
10950 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10951 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10952}
10953
Christopher Fauletc404f112020-02-26 15:03:09 +010010954static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10955 unsigned int offset, unsigned int len)
10956{
10957 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10958 struct hlua *flt_hlua;
10959 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10960 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10961 int ret;
10962
10963 flt_hlua = flt_ctx->hlua[idx];
10964 flt_ctx->cur_off[idx] = offset;
10965 flt_ctx->cur_len[idx] = len;
10966 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10967 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10968 if (ret != -1) {
10969 ret = flt_ctx->cur_len[idx];
10970 if (lua_gettop(flt_hlua->T) > 0) {
10971 ret = lua_tointeger(flt_hlua->T, -1);
10972 if (ret > flt_ctx->cur_len[idx])
10973 ret = flt_ctx->cur_len[idx];
10974 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10975 }
10976 }
10977 return ret;
10978}
10979
Christopher Faulet69c581a2021-05-31 08:54:04 +020010980static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10981 struct flt_conf *fconf, char **err, void *private)
10982{
10983 struct hlua_reg_filter *reg_flt = private;
10984 lua_State *L;
10985 struct hlua_flt_config *conf = NULL;
10986 const char *flt_id = NULL;
10987 int state_id, pos, flt_flags = 0;
10988 struct flt_ops *hlua_flt_ops = NULL;
10989
10990 state_id = reg_flt_to_stack_id(reg_flt);
10991 L = hlua_states[state_id];
10992
10993 /* Initialize the filter ops with default callbacks */
10994 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010995 if (!hlua_flt_ops)
10996 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010997 hlua_flt_ops->init = hlua_filter_init;
10998 hlua_flt_ops->deinit = hlua_filter_deinit;
10999 if (state_id) {
11000 /* Set per-thread callback if script is loaded per-thread */
11001 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11002 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11003 }
11004 hlua_flt_ops->attach = hlua_filter_new;
11005 hlua_flt_ops->detach = hlua_filter_delete;
11006
11007 /* Push the filter class on the stack and resolve all callbacks */
11008 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11009
Christopher Fauletc404f112020-02-26 15:03:09 +010011010 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11011 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11012 lua_pop(L, 1);
11013 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11014 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11015 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011016 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11017 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11018 lua_pop(L, 1);
11019 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11020 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11021 lua_pop(L, 1);
11022 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11023 hlua_flt_ops->http_end = hlua_filter_http_end;
11024 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011025 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11026 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11027 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011028
11029 /* Get id and flags of the filter class */
11030 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11031 flt_id = lua_tostring(L, -1);
11032 lua_pop(L, 1);
11033 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11034 flt_flags = lua_tointeger(L, -1);
11035 lua_pop(L, 1);
11036
11037 /* Create the filter config */
11038 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011039 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011040 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011041 conf->reg = reg_flt;
11042
11043 /* duplicate args */
11044 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11045 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011046 if (!conf->args)
11047 goto error;
11048 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011049 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011050 if (!conf->args[pos])
11051 goto error;
11052 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011053 conf->args[pos] = NULL;
11054 *cur_arg += pos + 1;
11055
Christopher Fauletc86bb872021-08-13 08:33:57 +020011056 if (flt_id) {
11057 fconf->id = strdup(flt_id);
11058 if (!fconf->id)
11059 goto error;
11060 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011061 fconf->flags = flt_flags;
11062 fconf->conf = conf;
11063 fconf->ops = hlua_flt_ops;
11064
11065 lua_settop(L, 0);
11066 return 0;
11067
11068 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011069 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011070 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011071 if (conf && conf->args) {
11072 for (pos = 0; conf->args[pos]; pos++)
11073 free(conf->args[pos]);
11074 free(conf->args);
11075 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011076 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011077 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011078 lua_settop(L, 0);
11079 return -1;
11080}
11081
Christopher Fauletc404f112020-02-26 15:03:09 +010011082__LJMP static int hlua_register_data_filter(lua_State *L)
11083{
11084 struct filter *filter;
11085 struct channel *chn;
11086
11087 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11088 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11089 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11090
11091 lua_getfield(L, 1, "__filter");
11092 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11093 filter = lua_touserdata (L, -1);
11094 lua_pop(L, 1);
11095
11096 register_data_filter(chn_strm(chn), chn, filter);
11097 return 1;
11098}
11099
11100__LJMP static int hlua_unregister_data_filter(lua_State *L)
11101{
11102 struct filter *filter;
11103 struct channel *chn;
11104
11105 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11106 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11107 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11108
11109 lua_getfield(L, 1, "__filter");
11110 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11111 filter = lua_touserdata (L, -1);
11112 lua_pop(L, 1);
11113
11114 unregister_data_filter(chn_strm(chn), chn, filter);
11115 return 1;
11116}
11117
Christopher Faulet69c581a2021-05-31 08:54:04 +020011118/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011119 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011120 * parse configuration arguments.
11121 */
11122__LJMP static int hlua_register_filter(lua_State *L)
11123{
11124 struct buffer *trash;
11125 struct flt_kw_list *fkl;
11126 struct flt_kw *fkw;
11127 const char *name;
11128 struct hlua_reg_filter *reg_flt= NULL;
11129 int flt_ref, fun_ref;
11130 int len;
11131
11132 MAY_LJMP(check_args(L, 3, "register_filter"));
11133
11134 /* First argument : filter name. */
11135 name = MAY_LJMP(luaL_checkstring(L, 1));
11136
11137 /* Second argument : The filter class */
11138 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11139
11140 /* Third argument : lua function. */
11141 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11142
11143 trash = get_trash_chunk();
11144 chunk_printf(trash, "lua.%s", name);
11145 fkw = flt_find_kw(trash->area);
11146 if (fkw != NULL) {
11147 reg_flt = fkw->private;
11148 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11149 ha_warning("Trying to register filter 'lua.%s' more than once. "
11150 "This will become a hard error in version 2.5.\n", name);
11151 }
11152 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11153 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11154 return 0;
11155 }
11156
11157 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11158 if (!fkl)
11159 goto alloc_error;
11160 fkl->scope = "HLUA";
11161
11162 reg_flt = new_hlua_reg_filter(name);
11163 if (!reg_flt)
11164 goto alloc_error;
11165
11166 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11167 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11168
11169 /* The filter keyword */
11170 len = strlen("lua.") + strlen(name) + 1;
11171 fkl->kw[0].kw = calloc(1, len);
11172 if (!fkl->kw[0].kw)
11173 goto alloc_error;
11174
11175 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11176
11177 fkl->kw[0].parse = hlua_filter_parse_fct;
11178 fkl->kw[0].private = reg_flt;
11179 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11180
11181 /* Register this new filter */
11182 flt_register_keywords(fkl);
11183
11184 return 0;
11185
11186 alloc_error:
11187 release_hlua_reg_filter(reg_flt);
11188 ha_free(&fkl);
11189 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11190 return 0; /* Never reached */
11191}
11192
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011193static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011194 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011195 char **err, unsigned int *timeout)
11196{
11197 const char *error;
11198
11199 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011200 if (error == PARSE_TIME_OVER) {
11201 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11202 args[1], args[0]);
11203 return -1;
11204 }
11205 else if (error == PARSE_TIME_UNDER) {
11206 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11207 args[1], args[0]);
11208 return -1;
11209 }
11210 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011211 memprintf(err, "%s: invalid timeout", args[0]);
11212 return -1;
11213 }
11214 return 0;
11215}
11216
11217static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011218 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011219 char **err)
11220{
11221 return hlua_read_timeout(args, section_type, curpx, defpx,
11222 file, line, err, &hlua_timeout_session);
11223}
11224
11225static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011226 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011227 char **err)
11228{
11229 return hlua_read_timeout(args, section_type, curpx, defpx,
11230 file, line, err, &hlua_timeout_task);
11231}
11232
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011233static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011234 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011235 char **err)
11236{
11237 return hlua_read_timeout(args, section_type, curpx, defpx,
11238 file, line, err, &hlua_timeout_applet);
11239}
11240
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011241static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011242 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011243 char **err)
11244{
11245 char *error;
11246
11247 hlua_nb_instruction = strtoll(args[1], &error, 10);
11248 if (*error != '\0') {
11249 memprintf(err, "%s: invalid number", args[0]);
11250 return -1;
11251 }
11252 return 0;
11253}
11254
Willy Tarreau32f61e22015-03-18 17:54:59 +010011255static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011256 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011257 char **err)
11258{
11259 char *error;
11260
11261 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011262 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011263 return -1;
11264 }
11265 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11266 if (*error != '\0') {
11267 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11268 return -1;
11269 }
11270 return 0;
11271}
11272
11273
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011274/* This function is called by the main configuration key "lua-load". It loads and
11275 * execute an lua file during the parsing of the HAProxy configuration file. It is
11276 * the main lua entry point.
11277 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011278 * This function runs with the HAProxy keywords API. It returns -1 if an error
11279 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011280 *
11281 * In some error case, LUA set an error message in top of the stack. This function
11282 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011283 *
11284 * This function can fail with an abort() due to an Lua critical error.
11285 * We are in the configuration parsing process of HAProxy, this abort() is
11286 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011287 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011288static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011289{
11290 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011291 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011292
11293 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011294 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011295 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011296 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011297 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011298 return -1;
11299 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011300
11301 /* Push args in the Lua stack, except the first one which is the filename */
11302 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011303 /* Check stack size. */
11304 if (!lua_checkstack(L, 1)) {
11305 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11306 return -1;
11307 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011308 lua_pushstring(L, args[nargs]);
11309 }
11310 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011311
11312 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011313 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011314 switch (error) {
11315 case LUA_OK:
11316 break;
11317 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011318 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011319 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011320 return -1;
11321 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011322 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011323 return -1;
11324 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011325 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011326 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011327 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011328#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011329 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011330 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011331 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011332 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011333#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011334 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011335 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011336 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011337 return -1;
11338 }
11339
11340 return 0;
11341}
11342
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011343static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011344 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011345 char **err)
11346{
11347 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011348 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011349 return -1;
11350 }
11351
Thierry Fournier59f11be2020-11-29 00:37:41 +010011352 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011353 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011354 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011355 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011356}
11357
Thierry Fournier59f11be2020-11-29 00:37:41 +010011358static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011359 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011360 char **err)
11361{
11362 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011363 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011364
11365 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011366 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011367 return -1;
11368 }
11369
11370 if (per_thread_load == NULL) {
11371 /* allocate the first entry large enough to store the final NULL */
11372 per_thread_load = calloc(1, sizeof(*per_thread_load));
11373 if (per_thread_load == NULL) {
11374 memprintf(err, "out of memory error");
11375 return -1;
11376 }
11377 }
11378
11379 /* count used entries */
11380 for (len = 0; per_thread_load[len] != NULL; len++)
11381 ;
11382
11383 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11384 if (per_thread_load == NULL) {
11385 memprintf(err, "out of memory error");
11386 return -1;
11387 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011388 per_thread_load[len + 1] = NULL;
11389
Thierry Fournierae6b5682022-09-19 09:04:16 +020011390 /* count args excepting the first, allocate array and copy args */
11391 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011392 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011393 if (per_thread_load[len] == NULL) {
11394 memprintf(err, "out of memory error");
11395 return -1;
11396 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011397 for (i = 1; *(args[i]) != 0; i++) {
11398 per_thread_load[len][i - 1] = strdup(args[i]);
11399 if (per_thread_load[len][i - 1] == NULL) {
11400 memprintf(err, "out of memory error");
11401 return -1;
11402 }
11403 }
11404 per_thread_load[len][i - 1] = strdup("");
11405 if (per_thread_load[len][i - 1] == NULL) {
11406 memprintf(err, "out of memory error");
11407 return -1;
11408 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011409
11410 /* loading for thread 1 only */
11411 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011412 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011413 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011414}
11415
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011416/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11417 * in the given <ctx>.
11418 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011419static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011420{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011421 lua_getglobal(L, "package"); /* push package variable */
11422 lua_pushstring(L, path); /* push given path */
11423 lua_pushstring(L, ";"); /* push semicolon */
11424 lua_getfield(L, -3, type); /* push old path */
11425 lua_concat(L, 3); /* concatenate to new path */
11426 lua_setfield(L, -2, type); /* store new path */
11427 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011428
11429 return 0;
11430}
11431
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011432static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011433 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011434 char **err)
11435{
11436 char *path;
11437 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011438 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011439 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011440
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011441 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011442 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011443 }
11444
11445 if (!(*args[1])) {
11446 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011447 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011448 }
11449 path = args[1];
11450
11451 if (*args[2]) {
11452 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11453 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011454 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011455 }
11456 type = args[2];
11457 }
11458
Thierry Fournier59f11be2020-11-29 00:37:41 +010011459 p = calloc(1, sizeof(*p));
11460 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011461 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011462 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011463 }
11464 p->path = strdup(path);
11465 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011466 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011467 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011468 }
11469 p->type = strdup(type);
11470 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011471 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011472 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011473 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011474 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011475
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011476 /* Handle the global state and the per-thread state for the first
11477 * thread. The remaining threads will be initialized based on
11478 * prepend_path_list.
11479 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011480 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011481 lua_State *L = hlua_states[i];
11482 const char *error;
11483
11484 if (setjmp(safe_ljmp_env) != 0) {
11485 lua_atpanic(L, hlua_panic_safe);
11486 if (lua_type(L, -1) == LUA_TSTRING)
11487 error = lua_tostring(L, -1);
11488 else
11489 error = "critical error";
11490 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11491 exit(1);
11492 } else {
11493 lua_atpanic(L, hlua_panic_ljmp);
11494 }
11495
11496 hlua_prepend_path(L, type, path);
11497
11498 lua_atpanic(L, hlua_panic_safe);
11499 }
11500
Thierry Fournier59f11be2020-11-29 00:37:41 +010011501 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011502
11503err2:
11504 free(p->type);
11505 free(p->path);
11506err:
11507 free(p);
11508 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011509}
11510
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011511/* configuration keywords declaration */
11512static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011513 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011514 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011515 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011516 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11517 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011518 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011519 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011520 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011521 { 0, NULL, NULL },
11522}};
11523
Willy Tarreau0108d902018-11-25 19:14:37 +010011524INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11525
William Lallemand52139182022-03-30 15:05:42 +020011526#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011527
William Lallemand30fcca12022-03-30 12:03:12 +020011528/*
11529 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11530 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11531 * difference is that the yield in lua and for the CLI is not handled the same
11532 * way.
11533 */
11534__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11535{
11536 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11537 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11538 struct ckch_inst *ckchi = *lua_ckchi;
11539 struct ckch_store *old_ckchs = lua_ckchs[0];
11540 struct ckch_store *new_ckchs = lua_ckchs[1];
11541 struct hlua *hlua;
11542 char *err = NULL;
11543 int y = 1;
11544
11545 hlua = hlua_gethlua(L);
11546
11547 /* get the first ckchi to copy */
11548 if (ckchi == NULL)
11549 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11550
11551 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11552 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11553 struct ckch_inst *new_inst;
11554
11555 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11556 if (y % 10 == 0) {
11557
11558 *lua_ckchi = ckchi;
11559
11560 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11561 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11562 }
11563
11564 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11565 goto error;
11566
11567 /* link the new ckch_inst to the duplicate */
11568 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11569 y++;
11570 }
11571
11572 /* The generation is finished, we can insert everything */
11573 ckch_store_replace(old_ckchs, new_ckchs);
11574
11575 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11576
11577 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11578
11579 return 0;
11580
11581error:
11582 ckch_store_free(new_ckchs);
11583 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11584 WILL_LJMP(luaL_error(L, "%s", err));
11585 free(err);
11586
11587 return 0;
11588}
11589
11590/*
11591 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11592 * from the table in parameter.
11593 *
11594 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11595 * means it does not need to have a transaction since everything is done in the
11596 * same function.
11597 *
11598 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11599 *
11600 */
11601__LJMP static int hlua_ckch_set(lua_State *L)
11602{
11603 struct hlua *hlua;
11604 struct ckch_inst **lua_ckchi;
11605 struct ckch_store **lua_ckchs;
11606 struct ckch_store *old_ckchs = NULL;
11607 struct ckch_store *new_ckchs = NULL;
11608 int errcode = 0;
11609 char *err = NULL;
11610 struct cert_exts *cert_ext = NULL;
11611 char *filename;
11612 struct cert_key_and_chain *ckch;
11613 int ret;
11614
11615 if (lua_type(L, -1) != LUA_TTABLE)
11616 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11617
11618 hlua = hlua_gethlua(L);
11619
11620 /* FIXME: this should not return an error but should come back later */
11621 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11622 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11623
11624 ret = lua_getfield(L, -1, "filename");
11625 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011626 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011627 errcode |= ERR_ALERT | ERR_FATAL;
11628 goto end;
11629 }
11630 filename = (char *)lua_tostring(L, -1);
11631
11632
11633 /* look for the filename in the tree */
11634 old_ckchs = ckchs_lookup(filename);
11635 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011636 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011637 errcode |= ERR_ALERT | ERR_FATAL;
11638 goto end;
11639 }
11640 /* TODO: handle extra_files_noext */
11641
11642 new_ckchs = ckchs_dup(old_ckchs);
11643 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011644 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011645 errcode |= ERR_ALERT | ERR_FATAL;
11646 goto end;
11647 }
11648
11649 ckch = new_ckchs->ckch;
11650
11651 /* loop on the field in the table, which have the same name as the
11652 * possible extensions of files */
11653 lua_pushnil(L);
11654 while (lua_next(L, 1)) {
11655 int i;
11656 const char *field = lua_tostring(L, -2);
11657 char *payload = (char *)lua_tostring(L, -1);
11658
11659 if (!field || strcmp(field, "filename") == 0) {
11660 lua_pop(L, 1);
11661 continue;
11662 }
11663
11664 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11665 if (strcmp(field, cert_exts[i].ext) == 0) {
11666 cert_ext = &cert_exts[i];
11667 break;
11668 }
11669 }
11670
11671 /* this is the default type, the field is not supported */
11672 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011673 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011674 errcode |= ERR_ALERT | ERR_FATAL;
11675 goto end;
11676 }
11677
11678 /* appply the change on the duplicate */
William Lallemandd8c195a2022-05-26 11:20:13 +020011679 if (cert_ext->load(filename, payload, ckch, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011680 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011681 errcode |= ERR_ALERT | ERR_FATAL;
11682 goto end;
11683 }
11684 lua_pop(L, 1);
11685 }
11686
11687 /* store the pointers on the lua stack */
11688 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11689 lua_ckchs[0] = old_ckchs;
11690 lua_ckchs[1] = new_ckchs;
11691 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11692 *lua_ckchi = NULL;
11693
11694 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11695 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11696
11697end:
11698 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11699
11700 if (errcode & ERR_CODE) {
11701 ckch_store_free(new_ckchs);
11702 WILL_LJMP(luaL_error(L, "%s", err));
11703 }
11704 free(err);
11705
11706 return 0;
11707}
11708
William Lallemand52139182022-03-30 15:05:42 +020011709#else
11710
11711__LJMP static int hlua_ckch_set(lua_State *L)
11712{
11713 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11714
11715 return 0;
11716}
11717#endif /* ! USE_OPENSSL */
11718
11719
11720
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011721/* This function can fail with an abort() due to an Lua critical error.
11722 * We are in the initialisation process of HAProxy, this abort() is
11723 * tolerated.
11724 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011725int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011726{
11727 struct hlua_init_function *init;
11728 const char *msg;
11729 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011730 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011731 const char *kind;
11732 const char *trace;
11733 int return_status = 1;
11734#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11735 int nres;
11736#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011737
Willy Tarreaucdb53462020-12-02 12:12:00 +010011738 /* disable memory limit checks if limit is not set */
11739 if (!hlua_global_allocator.limit)
11740 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11741
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011742 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011743 if (setjmp(safe_ljmp_env) != 0) {
11744 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011745 if (lua_type(L, -1) == LUA_TSTRING)
11746 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011747 else
11748 error = "critical error";
11749 fprintf(stderr, "Lua post-init: %s.\n", error);
11750 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011751 } else {
11752 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011753 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011754
Thierry Fournierb8cef172020-11-28 15:37:17 +010011755 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011756
Thierry Fournierc7492592020-11-28 23:57:24 +010011757 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011758 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011759
11760#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011761 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011762#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011763 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011764#endif
11765 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011766 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011767
11768 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011769 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011770 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011771
11772 case LUA_ERRERR:
11773 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011774 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011775 case LUA_ERRRUN:
11776 if (!kind)
11777 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011778 msg = lua_tostring(L, -1);
11779 lua_settop(L, 0); /* Empty the stack. */
11780 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011781 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011782 if (msg)
11783 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11784 else
11785 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11786 return_status = 0;
11787 break;
11788
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011789 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011790 /* Unknown error */
11791 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011792 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011793 case LUA_YIELD:
11794 /* yield is not configured at this step, this state doesn't happen */
11795 if (!kind)
11796 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011797 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011798 case LUA_ERRMEM:
11799 if (!kind)
11800 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011801 lua_settop(L, 0);
11802 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011803 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011804 ha_alert("Lua init: %s: %s\n", kind, trace);
11805 return_status = 0;
11806 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011807 }
Thierry Fournier670db242020-11-28 10:49:59 +010011808 if (!return_status)
11809 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011810 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011811
11812 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011813 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011814}
11815
Thierry Fournierb8cef172020-11-28 15:37:17 +010011816int hlua_post_init()
11817{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011818 int ret;
11819 int i;
11820 int errors;
11821 char *err = NULL;
11822 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011823 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011824
Willy Tarreaub1310492021-08-30 09:35:18 +020011825#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011826 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011827 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011828 int saved_used_backed = global.ssl_used_backend;
11829 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011830 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011831 global.ssl_used_backend = saved_used_backed;
11832 }
11833#endif
11834
Thierry Fournierc7492592020-11-28 23:57:24 +010011835 /* Perform post init of common thread */
11836 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011837 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011838 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11839 if (ret == 0)
11840 return 0;
11841
11842 /* init remaining lua states and load files */
11843 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11844
11845 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011846 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011847
11848 /* Init lua state */
11849 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11850
11851 /* Load lua files */
11852 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11853 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11854 if (ret != 0) {
11855 ha_alert("Lua init: %s\n", err);
11856 return 0;
11857 }
11858 }
11859 }
11860
11861 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011862 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011863
11864 /* Execute post init for all states */
11865 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11866
11867 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011868 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011869
11870 /* run post init */
11871 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11872 if (ret == 0)
11873 return 0;
11874 }
11875
11876 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011877 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011878
11879 /* control functions registering. Each function must have:
11880 * - only the function_ref[0] set positive and all other to -1
11881 * - only the function_ref[0] set to -1 and all other positive
11882 * This ensure a same reference is not used both in shared
11883 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011884 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011885 * complicated to found for the end user.
11886 */
11887 errors = 0;
11888 list_for_each_entry(fcn, &referenced_functions, l) {
11889 ret = 0;
11890 for (i = 1; i < global.nbthread + 1; i++) {
11891 if (fcn->function_ref[i] == -1)
11892 ret--;
11893 else
11894 ret++;
11895 }
11896 if (abs(ret) != global.nbthread) {
11897 ha_alert("Lua function '%s' is not referenced in all thread. "
11898 "Expect function in all thread or in none thread.\n", fcn->name);
11899 errors++;
11900 continue;
11901 }
11902
11903 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011904 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11905 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011906 "exclusive.\n", fcn->name);
11907 errors++;
11908 }
11909 }
11910
Christopher Faulet69c581a2021-05-31 08:54:04 +020011911 /* Do the same with registered filters */
11912 list_for_each_entry(reg_flt, &referenced_filters, l) {
11913 ret = 0;
11914 for (i = 1; i < global.nbthread + 1; i++) {
11915 if (reg_flt->flt_ref[i] == -1)
11916 ret--;
11917 else
11918 ret++;
11919 }
11920 if (abs(ret) != global.nbthread) {
11921 ha_alert("Lua filter '%s' is not referenced in all thread. "
11922 "Expect function in all thread or in none thread.\n", reg_flt->name);
11923 errors++;
11924 continue;
11925 }
11926
11927 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11928 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11929 "and per-thread Lua context (through lua-load-per-thread). these two context "
11930 "exclusive.\n", fcn->name);
11931 errors++;
11932 }
11933 }
11934
11935
Thierry Fournier59f11be2020-11-29 00:37:41 +010011936 if (errors > 0)
11937 return 0;
11938
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011939 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011940 * -1 in order to have probably a segfault if someone use it
11941 */
11942 hlua_state_id = -1;
11943
11944 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011945}
11946
Willy Tarreau32f61e22015-03-18 17:54:59 +010011947/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11948 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11949 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011950 * allocation. <nsize> is the requested new size. A new allocation is
11951 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011952 * zero. This one verifies that the limits are respected but is optimized
11953 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011954 *
11955 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11956 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11957 * that and will simply allocate zero as if it were the result of malloc(0),
11958 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11959 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011960 */
11961static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11962{
11963 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011964 size_t limit, old, new;
11965
11966 /* a limit of ~0 means unlimited and boot complete, so there's no need
11967 * for accounting anymore.
11968 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011969 if (likely(~zone->limit == 0)) {
11970 if (!nsize)
11971 ha_free(&ptr);
11972 else
11973 ptr = realloc(ptr, nsize);
11974 return ptr;
11975 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011976
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011977 if (!ptr)
11978 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011979
Willy Tarreaucdb53462020-12-02 12:12:00 +010011980 /* enforce strict limits across all threads */
11981 limit = zone->limit;
11982 old = _HA_ATOMIC_LOAD(&zone->allocated);
11983 do {
11984 new = old + nsize - osize;
11985 if (unlikely(nsize && limit && new > limit))
11986 return NULL;
11987 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011988
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011989 if (!nsize)
11990 ha_free(&ptr);
11991 else
11992 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011993
11994 if (unlikely(!ptr && nsize)) // failed
11995 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11996
11997 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011998 return ptr;
11999}
12000
Thierry Fournierecb83c22020-11-28 15:49:44 +010012001/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012002 * We are in the initialisation process of HAProxy, this abort() is
12003 * tolerated.
12004 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012005lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012006{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012007 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012008 int idx;
12009 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012010 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012011 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012012 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012013 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012014 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012015 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012016
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012017 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012018 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012019
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012020 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012021 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012022 *context = NULL;
12023
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012024 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012025 * the Lua function can fail with an abort. We are in the initialisation
12026 * process of HAProxy, this abort() is tolerated.
12027 */
12028
Thierry Fournier3c539322020-11-28 16:05:05 +010012029 /* Call post initialisation function in safe environment. */
12030 if (setjmp(safe_ljmp_env) != 0) {
12031 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012032 if (lua_type(L, -1) == LUA_TSTRING)
12033 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012034 else
12035 error_msg = "critical error";
12036 fprintf(stderr, "Lua init: %s.\n", error_msg);
12037 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012038 } else {
12039 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012040 }
12041
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012042 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012043 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012044#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12045#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12046#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012047 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012048#endif
12049#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012050 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012051#endif
12052#undef HLUA_PREPEND_PATH_TOSTRING
12053#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012054
Thierry Fournier59f11be2020-11-29 00:37:41 +010012055 /* Apply configured prepend path */
12056 list_for_each_entry(pp, &prepend_path_list, l)
12057 hlua_prepend_path(L, pp->type, pp->path);
12058
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012059 /*
12060 *
12061 * Create "core" object.
12062 *
12063 */
12064
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012065 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012066 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012067
Thierry Fournierecb83c22020-11-28 15:49:44 +010012068 /* set the thread id */
12069 hlua_class_const_int(L, "thread", thread_num);
12070
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012071 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012072 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012073 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012074
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012075 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012076 hlua_class_function(L, "register_init", hlua_register_init);
12077 hlua_class_function(L, "register_task", hlua_register_task);
12078 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12079 hlua_class_function(L, "register_converters", hlua_register_converters);
12080 hlua_class_function(L, "register_action", hlua_register_action);
12081 hlua_class_function(L, "register_service", hlua_register_service);
12082 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012083 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012084 hlua_class_function(L, "yield", hlua_yield);
12085 hlua_class_function(L, "set_nice", hlua_set_nice);
12086 hlua_class_function(L, "sleep", hlua_sleep);
12087 hlua_class_function(L, "msleep", hlua_msleep);
12088 hlua_class_function(L, "add_acl", hlua_add_acl);
12089 hlua_class_function(L, "del_acl", hlua_del_acl);
12090 hlua_class_function(L, "set_map", hlua_set_map);
12091 hlua_class_function(L, "del_map", hlua_del_map);
12092 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012093 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012094 hlua_class_function(L, "log", hlua_log);
12095 hlua_class_function(L, "Debug", hlua_log_debug);
12096 hlua_class_function(L, "Info", hlua_log_info);
12097 hlua_class_function(L, "Warning", hlua_log_warning);
12098 hlua_class_function(L, "Alert", hlua_log_alert);
12099 hlua_class_function(L, "done", hlua_done);
12100 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012101
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012102 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012103
12104 /*
12105 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012106 * Create "act" object.
12107 *
12108 */
12109
12110 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012111 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012112
12113 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012114 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12115 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12116 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12117 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12118 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12119 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12120 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12121 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012122
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012123 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012124
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012125 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012126
12127 /*
12128 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012129 * Create "Filter" object.
12130 *
12131 */
12132
12133 /* This table entry is the object "filter" base. */
12134 lua_newtable(L);
12135
12136 /* push flags and constants */
12137 hlua_class_const_int(L, "CONTINUE", 1);
12138 hlua_class_const_int(L, "WAIT", 0);
12139 hlua_class_const_int(L, "ERROR", -1);
12140
12141 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12142
Christopher Fauletc404f112020-02-26 15:03:09 +010012143 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12144 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12145 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12146
Christopher Faulet69c581a2021-05-31 08:54:04 +020012147 lua_setglobal(L, "filter");
12148
12149 /*
12150 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012151 * Register class Map
12152 *
12153 */
12154
12155 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012156 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012157
12158 /* register pattern types. */
12159 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012160 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012161 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012162 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012163 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012164 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012165
12166 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012167 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012168
12169 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012170 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012171
Ilya Shipitsind4259502020-04-08 01:07:56 +050012172 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012173 lua_pushstring(L, "__index");
12174 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012175
12176 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012177 hlua_class_function(L, "lookup", hlua_map_lookup);
12178 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012179
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012181
Thierry Fournier45e78d72016-02-19 18:34:46 +010012182 /* Register previous table in the registry with reference and named entry.
12183 * The function hlua_register_metatable() pops the stack, so we
12184 * previously create a copy of the table.
12185 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012186 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12187 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012188
12189 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012190 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012191
12192 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012193 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012194
12195 /*
12196 *
William Lallemand30fcca12022-03-30 12:03:12 +020012197 * Register "CertCache" class
12198 *
12199 */
12200
12201 /* Create and fill the metatable. */
12202 lua_newtable(L);
12203 /* Register */
12204 hlua_class_function(L, "set", hlua_ckch_set);
12205 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12206
12207 /*
12208 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012209 * Register class Channel
12210 *
12211 */
12212
12213 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012214 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012215
Ilya Shipitsind4259502020-04-08 01:07:56 +050012216 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012217 lua_pushstring(L, "__index");
12218 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012219
12220 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012221 hlua_class_function(L, "data", hlua_channel_get_data);
12222 hlua_class_function(L, "line", hlua_channel_get_line);
12223 hlua_class_function(L, "set", hlua_channel_set_data);
12224 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012225 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012226 hlua_class_function(L, "prepend", hlua_channel_prepend);
12227 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012228 hlua_class_function(L, "send", hlua_channel_send);
12229 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012230 hlua_class_function(L, "input", hlua_channel_get_in_len);
12231 hlua_class_function(L, "output", hlua_channel_get_out_len);
12232 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012233 hlua_class_function(L, "is_full", hlua_channel_is_full);
12234 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012235
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012236 /* Deprecated API */
12237 hlua_class_function(L, "get", hlua_channel_get);
12238 hlua_class_function(L, "dup", hlua_channel_dup);
12239 hlua_class_function(L, "getline", hlua_channel_getline);
12240 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12241 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12242
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012243 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012244
12245 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012246 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012247
12248 /*
12249 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012250 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012251 *
12252 */
12253
12254 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012255 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012256
Ilya Shipitsind4259502020-04-08 01:07:56 +050012257 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012258 lua_pushstring(L, "__index");
12259 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012260
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012261 /* Browse existing fetches and create the associated
12262 * object method.
12263 */
12264 sf = NULL;
12265 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012266 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12267 * by an underscore.
12268 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012269 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012270 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012271 if (*p == '.' || *p == '-' || *p == '+')
12272 *p = '_';
12273
12274 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012275 lua_pushstring(L, trash.area);
12276 lua_pushlightuserdata(L, sf);
12277 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12278 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012279 }
12280
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012281 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012282
12283 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012284 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012285
12286 /*
12287 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012288 * Register class Converters
12289 *
12290 */
12291
12292 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012293 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012294
12295 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012296 lua_pushstring(L, "__index");
12297 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012298
12299 /* Browse existing converters and create the associated
12300 * object method.
12301 */
12302 sc = NULL;
12303 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012304 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12305 * by an underscore.
12306 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012307 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012308 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012309 if (*p == '.' || *p == '-' || *p == '+')
12310 *p = '_';
12311
12312 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012313 lua_pushstring(L, trash.area);
12314 lua_pushlightuserdata(L, sc);
12315 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12316 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012317 }
12318
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012319 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012320
12321 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012322 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012323
12324 /*
12325 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012326 * Register class HTTP
12327 *
12328 */
12329
12330 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012331 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012332
Ilya Shipitsind4259502020-04-08 01:07:56 +050012333 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012334 lua_pushstring(L, "__index");
12335 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012336
12337 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012338 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12339 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12340 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12341 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12342 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12343 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12344 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12345 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12346 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12347 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012348
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012349 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12350 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12351 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12352 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12353 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12354 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12355 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012356
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012357 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012358
12359 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012360 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012361
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012362 /*
12363 *
12364 * Register class HTTPMessage
12365 *
12366 */
12367
12368 /* Create and fill the metatable. */
12369 lua_newtable(L);
12370
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012371 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012372 lua_pushstring(L, "__index");
12373 lua_newtable(L);
12374
12375 /* Register Lua functions. */
12376 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12377 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12378 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12379 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12380 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12381 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12382 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12383 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12384 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12385 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12386 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12387 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12388 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12389 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12390 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12391 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12392 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12393 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12394
12395 hlua_class_function(L, "body", hlua_http_msg_get_body);
12396 hlua_class_function(L, "set", hlua_http_msg_set_data);
12397 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12398 hlua_class_function(L, "append", hlua_http_msg_append);
12399 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12400 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12401 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12402 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12403
12404 hlua_class_function(L, "send", hlua_http_msg_send);
12405 hlua_class_function(L, "forward", hlua_http_msg_forward);
12406
12407 lua_rawset(L, -3);
12408
12409 /* Register previous table in the registry with reference and named entry. */
12410 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012411
12412 /*
12413 *
12414 * Register class HTTPClient
12415 *
12416 */
12417
12418 /* Create and fill the metatable. */
12419 lua_newtable(L);
12420 lua_pushstring(L, "__index");
12421 lua_newtable(L);
12422 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012423 hlua_class_function(L, "head", hlua_httpclient_head);
12424 hlua_class_function(L, "put", hlua_httpclient_put);
12425 hlua_class_function(L, "post", hlua_httpclient_post);
12426 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012427 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012428 /* Register the garbage collector entry. */
12429 lua_pushstring(L, "__gc");
12430 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12431 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12432
William Lallemand3956c4e2021-09-21 16:25:15 +020012433
12434
12435 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012436 /*
12437 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012438 * Register class AppletTCP
12439 *
12440 */
12441
12442 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012443 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012444
Ilya Shipitsind4259502020-04-08 01:07:56 +050012445 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012446 lua_pushstring(L, "__index");
12447 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012448
12449 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012450 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12451 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12452 hlua_class_function(L, "send", hlua_applet_tcp_send);
12453 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12454 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12455 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12456 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12457 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012458
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012459 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012460
12461 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012462 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012463
12464 /*
12465 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012466 * Register class AppletHTTP
12467 *
12468 */
12469
12470 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012471 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012472
Ilya Shipitsind4259502020-04-08 01:07:56 +050012473 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012474 lua_pushstring(L, "__index");
12475 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012476
12477 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012478 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12479 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12480 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12481 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12482 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12483 hlua_class_function(L, "getline", hlua_applet_http_getline);
12484 hlua_class_function(L, "receive", hlua_applet_http_recv);
12485 hlua_class_function(L, "send", hlua_applet_http_send);
12486 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12487 hlua_class_function(L, "set_status", hlua_applet_http_status);
12488 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012489
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012490 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012491
12492 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012493 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012494
12495 /*
12496 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012497 * Register class TXN
12498 *
12499 */
12500
12501 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012502 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012503
Ilya Shipitsind4259502020-04-08 01:07:56 +050012504 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012505 lua_pushstring(L, "__index");
12506 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012507
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012508 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012509 hlua_class_function(L, "set_priv", hlua_set_priv);
12510 hlua_class_function(L, "get_priv", hlua_get_priv);
12511 hlua_class_function(L, "set_var", hlua_set_var);
12512 hlua_class_function(L, "unset_var", hlua_unset_var);
12513 hlua_class_function(L, "get_var", hlua_get_var);
12514 hlua_class_function(L, "done", hlua_txn_done);
12515 hlua_class_function(L, "reply", hlua_txn_reply_new);
12516 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12517 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12518 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12519 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12520 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12521 hlua_class_function(L, "deflog", hlua_txn_deflog);
12522 hlua_class_function(L, "log", hlua_txn_log);
12523 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12524 hlua_class_function(L, "Info", hlua_txn_log_info);
12525 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12526 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012527
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012528 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012529
12530 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012531 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012532
12533 /*
12534 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012535 * Register class reply
12536 *
12537 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012538 lua_newtable(L);
12539 lua_pushstring(L, "__index");
12540 lua_newtable(L);
12541 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12542 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12543 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12544 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12545 lua_settable(L, -3); /* Sets the __index entry. */
12546 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012547
12548
12549 /*
12550 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012551 * Register class Socket
12552 *
12553 */
12554
12555 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012556 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012557
Ilya Shipitsind4259502020-04-08 01:07:56 +050012558 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012559 lua_pushstring(L, "__index");
12560 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012561
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012562#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012563 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012564#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012565 hlua_class_function(L, "connect", hlua_socket_connect);
12566 hlua_class_function(L, "send", hlua_socket_send);
12567 hlua_class_function(L, "receive", hlua_socket_receive);
12568 hlua_class_function(L, "close", hlua_socket_close);
12569 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12570 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12571 hlua_class_function(L, "setoption", hlua_socket_setoption);
12572 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012573
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012574 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012575
12576 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012577 lua_pushstring(L, "__gc");
12578 lua_pushcclosure(L, hlua_socket_gc, 0);
12579 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012580
12581 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012582 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012583
Thierry Fournieraafc7772020-12-04 11:47:47 +010012584 lua_atpanic(L, hlua_panic_safe);
12585
12586 return L;
12587}
12588
12589void hlua_init(void) {
12590 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012591 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012592#ifdef USE_OPENSSL
12593 struct srv_kw *kw;
12594 int tmp_error;
12595 char *error;
12596 char *args[] = { /* SSL client configuration. */
12597 "ssl",
12598 "verify",
12599 "none",
12600 NULL
12601 };
12602#endif
12603
12604 /* Init post init function list head */
12605 for (i = 0; i < MAX_THREADS + 1; i++)
12606 LIST_INIT(&hlua_init_functions[i]);
12607
12608 /* Init state for common/shared lua parts */
12609 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012610 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012611 hlua_states[0] = hlua_init_state(0);
12612
12613 /* Init state 1 for thread 0. We have at least one thread. */
12614 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012615 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012616 hlua_states[1] = hlua_init_state(1);
12617
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012618 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012619 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012620 if (!socket_proxy) {
12621 fprintf(stderr, "Lua init: %s\n", errmsg);
12622 exit(1);
12623 }
12624 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012625
12626 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012627 socket_tcp = new_server(socket_proxy);
12628 if (!socket_tcp) {
12629 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12630 exit(1);
12631 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012632
12633#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012634 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012635 socket_ssl = new_server(socket_proxy);
12636 if (!socket_ssl) {
12637 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12638 exit(1);
12639 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012640
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012641 socket_ssl->use_ssl = 1;
12642 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012643
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012644 for (i = 0; args[i] != NULL; i++) {
12645 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012646 /*
12647 *
12648 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012649 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012650 * features like client certificates and ssl_verify.
12651 *
12652 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012653 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012654 if (tmp_error != 0) {
12655 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12656 abort(); /* This must be never arrives because the command line
12657 not editable by the user. */
12658 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012659 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012660 }
12661 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012662#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012663
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012664}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012665
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012666static void hlua_deinit()
12667{
Willy Tarreau186f3762020-12-04 11:48:12 +010012668 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012669 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12670
12671 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12672 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012673
12674 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12675 if (hlua_states[thr])
12676 lua_close(hlua_states[thr]);
12677 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012678
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012679 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012680
Willy Tarreau0f143af2021-03-05 10:41:48 +010012681#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012682 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012683#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012684
12685 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012686}
12687
12688REGISTER_POST_DEINIT(hlua_deinit);
12689
Willy Tarreau80713382018-11-26 10:19:54 +010012690static void hlua_register_build_options(void)
12691{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012692 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012693
Willy Tarreaubb57d942016-12-21 19:04:56 +010012694 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12695 hap_register_build_opts(ptr, 1);
12696}
Willy Tarreau80713382018-11-26 10:19:54 +010012697
12698INITCALL0(STG_REGISTER, hlua_register_build_options);