blob: ccdf5389664c9751c7dc5df554aec95824bf2ed2 [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);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001251 if (!already_safe) {
1252 if (!SET_SAFE_LJMP_PARENT(lua)) {
1253 lua->Tref = LUA_REFNIL;
1254 return 0;
1255 }
1256 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001257 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001258 if (!lua->T) {
1259 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001260 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001261 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001262 return 0;
1263 }
1264 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001265 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001266 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001267 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001268 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001269 return 1;
1270}
1271
Willy Tarreau87b09662015-04-03 00:22:06 +02001272/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001273 * is destroyed. The destroy also the memory context. The struct "lua"
1274 * is not freed.
1275 */
1276void hlua_ctx_destroy(struct hlua *lua)
1277{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001278 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001279 return;
1280
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001281 if (!lua->T)
1282 goto end;
1283
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001284 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001285 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001286
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001287 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001288 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001289 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001290 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001291
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001292 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001293 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001294 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001295 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001296 /* Forces a garbage collecting process. If the Lua program is finished
1297 * without error, we run the GC on the thread pointer. Its freed all
1298 * the unused memory.
1299 * If the thread is finnish with an error or is currently yielded,
1300 * it seems that the GC applied on the thread doesn't clean anything,
1301 * so e run the GC on the main thread.
1302 * NOTE: maybe this action locks all the Lua threads untiml the en of
1303 * the garbage collection.
1304 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001305 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001306 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001307 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001308 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001309 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001310 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001311
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001312 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001313
1314end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001315 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001316}
1317
1318/* This function is used to restore the Lua context when a coroutine
1319 * fails. This function copy the common memory between old coroutine
1320 * and the new coroutine. The old coroutine is destroyed, and its
1321 * replaced by the new coroutine.
1322 * If the flag "keep_msg" is set, the last entry of the old is assumed
1323 * as string error message and it is copied in the new stack.
1324 */
1325static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1326{
1327 lua_State *T;
1328 int new_ref;
1329
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001330 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001331 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001332 if (!T)
1333 return 0;
1334
1335 /* Copy last error message. */
1336 if (keep_msg)
1337 lua_xmove(lua->T, T, 1);
1338
1339 /* Copy data between the coroutines. */
1340 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1341 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001342 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001343
1344 /* Destroy old data. */
1345 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1346
1347 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001348 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001349
1350 /* Fill the struct with the new coroutine values. */
1351 lua->Mref = new_ref;
1352 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001353 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001354
1355 /* Set context. */
1356 hlua_sethlua(lua);
1357
1358 return 1;
1359}
1360
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001361void hlua_hook(lua_State *L, lua_Debug *ar)
1362{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001363 struct hlua *hlua;
1364
1365 /* Get hlua struct, or NULL if we execute from main lua state */
1366 hlua = hlua_gethlua(L);
1367 if (!hlua)
1368 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001369
1370 /* Lua cannot yield when its returning from a function,
1371 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001372 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001373 */
1374 if (lua_gethookmask(L) & LUA_MASKRET) {
1375 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1376 return;
1377 }
1378
1379 /* restore the interrupt condition. */
1380 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1381
1382 /* If we interrupt the Lua processing in yieldable state, we yield.
1383 * If the state is not yieldable, trying yield causes an error.
1384 */
1385 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001386 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001387
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001388 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001389 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001390 hlua->run_time += now_ms - hlua->start_time;
1391 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001392 lua_pushfstring(L, "execution timeout");
1393 WILL_LJMP(lua_error(L));
1394 }
1395
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001396 /* Update the start time. */
1397 hlua->start_time = now_ms;
1398
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001399 /* Try to interrupt the process at the end of the current
1400 * unyieldable function.
1401 */
1402 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001403}
1404
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001405/* This function start or resumes the Lua stack execution. If the flag
1406 * "yield_allowed" if no set and the LUA stack execution returns a yield
1407 * The function return an error.
1408 *
1409 * The function can returns 4 values:
1410 * - HLUA_E_OK : The execution is terminated without any errors.
1411 * - HLUA_E_AGAIN : The execution must continue at the next associated
1412 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001413 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001414 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001415 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001416 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001417 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001418 * LUA code.
1419 */
1420static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1421{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001422#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1423 int nres;
1424#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001425 int ret;
1426 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001427 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001428
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001429 /* Initialise run time counter. */
1430 if (!HLUA_IS_RUNNING(lua))
1431 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001432
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001433 /* Lock the whole Lua execution. This lock must be before the
1434 * label "resume_execution".
1435 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001436 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001437 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001438
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001439resume_execution:
1440
1441 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1442 * instructions. it is used for preventing infinite loops.
1443 */
1444 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1445
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001446 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001447 HLUA_SET_RUN(lua);
1448 HLUA_CLR_CTRLYIELD(lua);
1449 HLUA_CLR_WAKERESWR(lua);
1450 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001451 HLUA_CLR_NOYIELD(lua);
1452 if (!yield_allowed)
1453 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001454
Christopher Fauletbc275a92020-02-26 14:55:16 +01001455 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001456 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001457 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001458
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001459 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001460#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001461 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001462#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001463 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001464#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001465 switch (ret) {
1466
1467 case LUA_OK:
1468 ret = HLUA_E_OK;
1469 break;
1470
1471 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001472 /* Check if the execution timeout is expired. It it is the case, we
1473 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001474 */
Willy Tarreau55542642021-10-08 09:33:24 +02001475 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001476 lua->run_time += now_ms - lua->start_time;
1477 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001478 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001479 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001480 break;
1481 }
1482 /* Process the forced yield. if the general yield is not allowed or
1483 * if no task were associated this the current Lua execution
1484 * coroutine, we resume the execution. Else we want to return in the
1485 * scheduler and we want to be waked up again, to continue the
1486 * current Lua execution. So we schedule our own task.
1487 */
1488 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001489 if (!yield_allowed || !lua->task)
1490 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001491 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001492 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001493 if (!yield_allowed) {
1494 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001495 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001496 break;
1497 }
1498 ret = HLUA_E_AGAIN;
1499 break;
1500
1501 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001502
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001503 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001504 * because the errors ares the only one mean to return immediately
1505 * from and lua execution.
1506 */
1507 if (lua->flags & HLUA_EXIT) {
1508 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001509 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001510 break;
1511 }
1512
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001513 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514 if (!lua_checkstack(lua->T, 1)) {
1515 ret = HLUA_E_ERR;
1516 break;
1517 }
1518 msg = lua_tostring(lua->T, -1);
1519 lua_settop(lua->T, 0); /* Empty the stack. */
1520 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001521 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001522 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001523 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001524 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001525 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 ret = HLUA_E_ERRMSG;
1527 break;
1528
1529 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001530 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001531 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001532 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001533 break;
1534
1535 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001536 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001537 if (!lua_checkstack(lua->T, 1)) {
1538 ret = HLUA_E_ERR;
1539 break;
1540 }
1541 msg = lua_tostring(lua->T, -1);
1542 lua_settop(lua->T, 0); /* Empty the stack. */
1543 lua_pop(lua->T, 1);
1544 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001545 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001546 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001547 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548 ret = HLUA_E_ERRMSG;
1549 break;
1550
1551 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001552 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001553 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001554 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001555 break;
1556 }
1557
1558 switch (ret) {
1559 case HLUA_E_AGAIN:
1560 break;
1561
1562 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001563 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001564 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001565 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001566 break;
1567
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001568 case HLUA_E_ETMOUT:
1569 case HLUA_E_NOMEM:
1570 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001571 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001572 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001573 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001574 hlua_ctx_renew(lua, 0);
1575 break;
1576
1577 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001578 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001579 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001580 break;
1581 }
1582
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001583 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001584 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001585 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001586
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001587 return ret;
1588}
1589
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001590/* This function exit the current code. */
1591__LJMP static int hlua_done(lua_State *L)
1592{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001593 struct hlua *hlua;
1594
1595 /* Get hlua struct, or NULL if we execute from main lua state */
1596 hlua = hlua_gethlua(L);
1597 if (!hlua)
1598 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001599
1600 hlua->flags |= HLUA_EXIT;
1601 WILL_LJMP(lua_error(L));
1602
1603 return 0;
1604}
1605
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001606/* This function is an LUA binding. It provides a function
1607 * for deleting ACL from a referenced ACL file.
1608 */
1609__LJMP static int hlua_del_acl(lua_State *L)
1610{
1611 const char *name;
1612 const char *key;
1613 struct pat_ref *ref;
1614
1615 MAY_LJMP(check_args(L, 2, "del_acl"));
1616
1617 name = MAY_LJMP(luaL_checkstring(L, 1));
1618 key = MAY_LJMP(luaL_checkstring(L, 2));
1619
1620 ref = pat_ref_lookup(name);
1621 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001622 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001623
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001624 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001625 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001626 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001627 return 0;
1628}
1629
1630/* This function is an LUA binding. It provides a function
1631 * for deleting map entry from a referenced map file.
1632 */
1633static int hlua_del_map(lua_State *L)
1634{
1635 const char *name;
1636 const char *key;
1637 struct pat_ref *ref;
1638
1639 MAY_LJMP(check_args(L, 2, "del_map"));
1640
1641 name = MAY_LJMP(luaL_checkstring(L, 1));
1642 key = MAY_LJMP(luaL_checkstring(L, 2));
1643
1644 ref = pat_ref_lookup(name);
1645 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001646 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001647
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001648 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001649 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001650 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001651 return 0;
1652}
1653
1654/* This function is an LUA binding. It provides a function
1655 * for adding ACL pattern from a referenced ACL file.
1656 */
1657static int hlua_add_acl(lua_State *L)
1658{
1659 const char *name;
1660 const char *key;
1661 struct pat_ref *ref;
1662
1663 MAY_LJMP(check_args(L, 2, "add_acl"));
1664
1665 name = MAY_LJMP(luaL_checkstring(L, 1));
1666 key = MAY_LJMP(luaL_checkstring(L, 2));
1667
1668 ref = pat_ref_lookup(name);
1669 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001670 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001671
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001672 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001673 if (pat_ref_find_elt(ref, key) == NULL)
1674 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001675 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001676 return 0;
1677}
1678
1679/* This function is an LUA binding. It provides a function
1680 * for setting map pattern and sample from a referenced map
1681 * file.
1682 */
1683static int hlua_set_map(lua_State *L)
1684{
1685 const char *name;
1686 const char *key;
1687 const char *value;
1688 struct pat_ref *ref;
1689
1690 MAY_LJMP(check_args(L, 3, "set_map"));
1691
1692 name = MAY_LJMP(luaL_checkstring(L, 1));
1693 key = MAY_LJMP(luaL_checkstring(L, 2));
1694 value = MAY_LJMP(luaL_checkstring(L, 3));
1695
1696 ref = pat_ref_lookup(name);
1697 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001698 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001699
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001700 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001701 if (pat_ref_find_elt(ref, key) != NULL)
1702 pat_ref_set(ref, key, value, NULL);
1703 else
1704 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001705 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001706 return 0;
1707}
1708
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001709/* A class is a lot of memory that contain data. This data can be a table,
1710 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001711 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001712 * the name of the object (_G[<name>] = <metable> ).
1713 *
1714 * A metable is a table that modify the standard behavior of a standard
1715 * access to the associated data. The entries of this new metatable are
1716 * defined as is:
1717 *
1718 * http://lua-users.org/wiki/MetatableEvents
1719 *
1720 * __index
1721 *
1722 * we access an absent field in a table, the result is nil. This is
1723 * true, but it is not the whole truth. Actually, such access triggers
1724 * the interpreter to look for an __index metamethod: If there is no
1725 * such method, as usually happens, then the access results in nil;
1726 * otherwise, the metamethod will provide the result.
1727 *
1728 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1729 * the key does not appear in the table, but the metatable has an __index
1730 * property:
1731 *
1732 * - if the value is a function, the function is called, passing in the
1733 * table and the key; the return value of that function is returned as
1734 * the result.
1735 *
1736 * - if the value is another table, the value of the key in that table is
1737 * asked for and returned (and if it doesn't exist in that table, but that
1738 * table's metatable has an __index property, then it continues on up)
1739 *
1740 * - Use "rawget(myTable,key)" to skip this metamethod.
1741 *
1742 * http://www.lua.org/pil/13.4.1.html
1743 *
1744 * __newindex
1745 *
1746 * Like __index, but control property assignment.
1747 *
1748 * __mode - Control weak references. A string value with one or both
1749 * of the characters 'k' and 'v' which specifies that the the
1750 * keys and/or values in the table are weak references.
1751 *
1752 * __call - Treat a table like a function. When a table is followed by
1753 * parenthesis such as "myTable( 'foo' )" and the metatable has
1754 * a __call key pointing to a function, that function is invoked
1755 * (passing any specified arguments) and the return value is
1756 * returned.
1757 *
1758 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1759 * called, if the metatable for myTable has a __metatable
1760 * key, the value of that key is returned instead of the
1761 * actual metatable.
1762 *
1763 * __tostring - Control string representation. When the builtin
1764 * "tostring( myTable )" function is called, if the metatable
1765 * for myTable has a __tostring property set to a function,
1766 * that function is invoked (passing myTable to it) and the
1767 * return value is used as the string representation.
1768 *
1769 * __len - Control table length. When the table length is requested using
1770 * the length operator ( '#' ), if the metatable for myTable has
1771 * a __len key pointing to a function, that function is invoked
1772 * (passing myTable to it) and the return value used as the value
1773 * of "#myTable".
1774 *
1775 * __gc - Userdata finalizer code. When userdata is set to be garbage
1776 * collected, if the metatable has a __gc field pointing to a
1777 * function, that function is first invoked, passing the userdata
1778 * to it. The __gc metamethod is not called for tables.
1779 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1780 *
1781 * Special metamethods for redefining standard operators:
1782 * http://www.lua.org/pil/13.1.html
1783 *
1784 * __add "+"
1785 * __sub "-"
1786 * __mul "*"
1787 * __div "/"
1788 * __unm "!"
1789 * __pow "^"
1790 * __concat ".."
1791 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001792 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001793 * http://www.lua.org/pil/13.2.html
1794 *
1795 * __eq "=="
1796 * __lt "<"
1797 * __le "<="
1798 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799
1800/*
1801 *
1802 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001803 * Class Map
1804 *
1805 *
1806 */
1807
1808/* Returns a struct hlua_map if the stack entry "ud" is
1809 * a class session, otherwise it throws an error.
1810 */
1811__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1812{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001813 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001814}
1815
1816/* This function is the map constructor. It don't need
1817 * the class Map object. It creates and return a new Map
1818 * object. It must be called only during "body" or "init"
1819 * context because it process some filesystem accesses.
1820 */
1821__LJMP static int hlua_map_new(struct lua_State *L)
1822{
1823 const char *fn;
1824 int match = PAT_MATCH_STR;
1825 struct sample_conv conv;
1826 const char *file = "";
1827 int line = 0;
1828 lua_Debug ar;
1829 char *err = NULL;
1830 struct arg args[2];
1831
1832 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1833 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1834
1835 fn = MAY_LJMP(luaL_checkstring(L, 1));
1836
1837 if (lua_gettop(L) >= 2) {
1838 match = MAY_LJMP(luaL_checkinteger(L, 2));
1839 if (match < 0 || match >= PAT_MATCH_NUM)
1840 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1841 }
1842
1843 /* Get Lua filename and line number. */
1844 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1845 lua_getinfo(L, "Sl", &ar); /* get info about it */
1846 if (ar.currentline > 0) { /* is there info? */
1847 file = ar.short_src;
1848 line = ar.currentline;
1849 }
1850 }
1851
1852 /* fill fake sample_conv struct. */
1853 conv.kw = ""; /* unused. */
1854 conv.process = NULL; /* unused. */
1855 conv.arg_mask = 0; /* unused. */
1856 conv.val_args = NULL; /* unused. */
1857 conv.out_type = SMP_T_STR;
1858 conv.private = (void *)(long)match;
1859 switch (match) {
1860 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1861 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1862 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1863 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1864 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1865 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1866 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001867 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001868 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1869 default:
1870 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1871 }
1872
1873 /* fill fake args. */
1874 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001875 args[0].data.str.area = strdup(fn);
1876 args[0].data.str.data = strlen(fn);
1877 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001878 args[1].type = ARGT_STOP;
1879
1880 /* load the map. */
1881 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001882 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001883 * free the err variable.
1884 */
1885 luaL_where(L, 1);
1886 lua_pushfstring(L, "'new': %s.", err);
1887 lua_concat(L, 2);
1888 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001889 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001890 WILL_LJMP(lua_error(L));
1891 }
1892
1893 /* create the lua object. */
1894 lua_newtable(L);
1895 lua_pushlightuserdata(L, args[0].data.map);
1896 lua_rawseti(L, -2, 0);
1897
1898 /* Pop a class Map metatable and affect it to the userdata. */
1899 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1900 lua_setmetatable(L, -2);
1901
1902
1903 return 1;
1904}
1905
1906__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1907{
1908 struct map_descriptor *desc;
1909 struct pattern *pat;
1910 struct sample smp;
1911
1912 MAY_LJMP(check_args(L, 2, "lookup"));
1913 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001914 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001915 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001916 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001917 }
1918 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001919 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001920 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001921 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 +01001922 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001923 }
1924
1925 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001926 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001927 if (str)
1928 lua_pushstring(L, "");
1929 else
1930 lua_pushnil(L);
1931 return 1;
1932 }
1933
1934 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001935 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001936 return 1;
1937}
1938
1939__LJMP static int hlua_map_lookup(struct lua_State *L)
1940{
1941 return _hlua_map_lookup(L, 0);
1942}
1943
1944__LJMP static int hlua_map_slookup(struct lua_State *L)
1945{
1946 return _hlua_map_lookup(L, 1);
1947}
1948
1949/*
1950 *
1951 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001952 * Class Socket
1953 *
1954 *
1955 */
1956
1957__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1958{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001959 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001960}
1961
1962/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001963 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964 * received.
1965 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001966static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967{
Willy Tarreau5321da92022-05-06 11:57:34 +02001968 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02001969 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970
Willy Tarreau5321da92022-05-06 11:57:34 +02001971 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02001972 sc_shutw(sc);
1973 sc_shutr(sc);
1974 sc_ic(sc)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001975 notification_wake(&ctx->wake_on_read);
1976 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02001977 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001978 }
1979
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001980 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001981 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001982 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001983
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001984 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001985 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001986 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001987
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001988 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001989 * to be notified whenever the connection completes.
1990 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001991 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02001992 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02001993 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02001994 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001995 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001996 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997
1998 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001999 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002000
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002001 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002002 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002003 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004
2005 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002006 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002007 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002008
2009 /* Some data were injected in the buffer, notify the stream
2010 * interface.
2011 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002012 if (!channel_is_empty(sc_ic(sc)))
2013 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002014
2015 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002016 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002017 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002018 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002019 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020}
2021
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002022static int hlua_socket_init(struct appctx *appctx)
2023{
2024 struct hlua_csk_ctx *ctx = appctx->svcctx;
2025 struct stream *s;
2026
2027 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2028 goto error;
2029
2030 s = appctx_strm(appctx);
2031
Willy Tarreau4596fe22022-05-17 19:07:51 +02002032 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002033 * and retrieve data from the server. The connection is initialized
2034 * with the "struct server".
2035 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002036 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002037
2038 /* Force destination server. */
2039 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2040 s->target = &socket_tcp->obj_type;
2041
2042 ctx->appctx = appctx;
2043 return 0;
2044
2045 error:
2046 return -1;
2047}
2048
Willy Tarreau87b09662015-04-03 00:22:06 +02002049/* This function is called when the "struct stream" is destroyed.
2050 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051 * Wake all the pending signals.
2052 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002053static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002054{
Willy Tarreau5321da92022-05-06 11:57:34 +02002055 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002056 struct xref *peer;
2057
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002058 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002059 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002060 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002061 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062
2063 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002064 notification_wake(&ctx->wake_on_read);
2065 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066}
2067
2068/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002069 * uses this object. If the stream does not exists, just quit.
2070 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071 * pending signal can rest in the read and write lists. destroy
2072 * it.
2073 */
2074__LJMP static int hlua_socket_gc(lua_State *L)
2075{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002076 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002077 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002078 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002080 MAY_LJMP(check_args(L, 1, "__gc"));
2081
2082 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002083 peer = xref_get_peer_and_lock(&socket->xref);
2084 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002086
2087 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002089 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002090 ctx->die = 1;
2091 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002092
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002093 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002094 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 return 0;
2096}
2097
2098/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002099 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002100 */
sada05ed3302018-05-11 11:48:18 -07002101__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002102{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002103 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002104 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002105 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002106 struct hlua *hlua;
2107
2108 /* Get hlua struct, or NULL if we execute from main lua state */
2109 hlua = hlua_gethlua(L);
2110 if (!hlua)
2111 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002113 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002114
2115 /* Check if we run on the same thread than the xreator thread.
2116 * We cannot access to the socket if the thread is different.
2117 */
2118 if (socket->tid != tid)
2119 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2120
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002121 peer = xref_get_peer_and_lock(&socket->xref);
2122 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002123 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002124
2125 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002126 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002127
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002128 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002129 ctx->die = 1;
2130 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002132 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002133 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134 return 0;
2135}
2136
sada05ed3302018-05-11 11:48:18 -07002137/* The close function calls close_helper.
2138 */
2139__LJMP static int hlua_socket_close(lua_State *L)
2140{
2141 MAY_LJMP(check_args(L, 1, "close"));
2142 return hlua_socket_close_helper(L);
2143}
2144
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145/* This Lua function assumes that the stack contain three parameters.
2146 * 1 - USERDATA containing a struct socket
2147 * 2 - INTEGER with values of the macro defined below
2148 * If the integer is -1, we must read at most one line.
2149 * If the integer is -2, we ust read all the data until the
2150 * end of the stream.
2151 * If the integer is positive value, we must read a number of
2152 * bytes corresponding to this value.
2153 */
2154#define HLSR_READ_LINE (-1)
2155#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002156__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157{
2158 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2159 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002160 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002161 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002163 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002165 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002166 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002167 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002168 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002169 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002170 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002171 struct stream *s;
2172 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002173 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002175 /* Get hlua struct, or NULL if we execute from main lua state */
2176 hlua = hlua_gethlua(L);
2177
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178 /* Check if this lua stack is schedulable. */
2179 if (!hlua || !hlua->task)
2180 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2181 "'frontend', 'backend' or 'task'"));
2182
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002183 /* Check if we run on the same thread than the xreator thread.
2184 * We cannot access to the socket if the thread is different.
2185 */
2186 if (socket->tid != tid)
2187 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2188
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002189 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002190 peer = xref_get_peer_and_lock(&socket->xref);
2191 if (!peer)
2192 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002193
2194 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2195 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002196 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002198 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002201 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202 if (nblk < 0) /* Connection close. */
2203 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002204 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002206
2207 /* remove final \r\n. */
2208 if (nblk == 1) {
2209 if (blk1[len1-1] == '\n') {
2210 len1--;
2211 skip_at_end++;
2212 if (blk1[len1-1] == '\r') {
2213 len1--;
2214 skip_at_end++;
2215 }
2216 }
2217 }
2218 else {
2219 if (blk2[len2-1] == '\n') {
2220 len2--;
2221 skip_at_end++;
2222 if (blk2[len2-1] == '\r') {
2223 len2--;
2224 skip_at_end++;
2225 }
2226 }
2227 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 }
2229
2230 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002232 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002233 if (nblk < 0) /* Connection close. */
2234 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002235 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 goto connection_empty;
2237 }
2238
2239 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002241 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242 if (nblk < 0) /* Connection close. */
2243 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002244 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245 goto connection_empty;
2246
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002247 missing_bytes = wanted - socket->b.n;
2248 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002250 len1 = missing_bytes;
2251 } if (nblk == 2 && len1 + len2 > missing_bytes)
2252 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253 }
2254
2255 len = len1;
2256
2257 luaL_addlstring(&socket->b, blk1, len1);
2258 if (nblk == 2) {
2259 len += len2;
2260 luaL_addlstring(&socket->b, blk2, len2);
2261 }
2262
2263 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002264 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265
2266 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002267 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268
2269 /* If the pattern reclaim to read all the data
2270 * in the connection, got out.
2271 */
2272 if (wanted == HLSR_READ_ALL)
2273 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002274 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 goto connection_empty;
2276
2277 /* Return result. */
2278 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280 return 1;
2281
2282connection_closed:
2283
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002284 xref_unlock(&socket->xref, peer);
2285
2286no_peer:
2287
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 /* If the buffer containds data. */
2289 if (socket->b.n > 0) {
2290 luaL_pushresult(&socket->b);
2291 return 1;
2292 }
2293 lua_pushnil(L);
2294 lua_pushstring(L, "connection closed.");
2295 return 2;
2296
2297connection_empty:
2298
Willy Tarreau5321da92022-05-06 11:57:34 +02002299 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002300 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002302 }
2303 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002304 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305 return 0;
2306}
2307
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002308/* This Lua function gets two parameters. The first one can be string
2309 * or a number. If the string is "*l", the user requires one line. If
2310 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 * If the value is a number, the user require a number of bytes equal
2312 * to the value. The default value is "*l" (a line).
2313 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002314 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 * integer takes this values:
2316 * -1 : read a line
2317 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002318 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002320 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 * concatenated with the read data.
2322 */
2323__LJMP static int hlua_socket_receive(struct lua_State *L)
2324{
2325 int wanted = HLSR_READ_LINE;
2326 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002327 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 char *error;
2329 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002330 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
2332 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2333 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2334
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002335 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002337 /* Check if we run on the same thread than the xreator thread.
2338 * We cannot access to the socket if the thread is different.
2339 */
2340 if (socket->tid != tid)
2341 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2342
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 /* check for pattern. */
2344 if (lua_gettop(L) >= 2) {
2345 type = lua_type(L, 2);
2346 if (type == LUA_TSTRING) {
2347 pattern = lua_tostring(L, 2);
2348 if (strcmp(pattern, "*a") == 0)
2349 wanted = HLSR_READ_ALL;
2350 else if (strcmp(pattern, "*l") == 0)
2351 wanted = HLSR_READ_LINE;
2352 else {
2353 wanted = strtoll(pattern, &error, 10);
2354 if (*error != '\0')
2355 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2356 }
2357 }
2358 else if (type == LUA_TNUMBER) {
2359 wanted = lua_tointeger(L, 2);
2360 if (wanted < 0)
2361 WILL_LJMP(luaL_error(L, "Unsupported size."));
2362 }
2363 }
2364
2365 /* Set pattern. */
2366 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002367
2368 /* Check if we would replace the top by itself. */
2369 if (lua_gettop(L) != 2)
2370 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371
Christopher Fauletc31b2002021-05-03 10:11:13 +02002372 /* Save index of the top of the stack because since buffers are used, it
2373 * may change
2374 */
2375 lastarg = lua_gettop(L);
2376
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002377 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378 luaL_buffinit(L, &socket->b);
2379
2380 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002381 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002382 if (lua_type(L, 3) != LUA_TSTRING)
2383 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2384 pattern = lua_tolstring(L, 3, &len);
2385 luaL_addlstring(&socket->b, pattern, len);
2386 }
2387
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002388 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389}
2390
2391/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002392 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002394static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395{
2396 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002397 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002398 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 struct appctx *appctx;
2400 size_t buf_len;
2401 const char *buf;
2402 int len;
2403 int send_len;
2404 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002405 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002406 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002407 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002409 /* Get hlua struct, or NULL if we execute from main lua state */
2410 hlua = hlua_gethlua(L);
2411
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 /* Check if this lua stack is schedulable. */
2413 if (!hlua || !hlua->task)
2414 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2415 "'frontend', 'backend' or 'task'"));
2416
2417 /* Get object */
2418 socket = MAY_LJMP(hlua_checksocket(L, 1));
2419 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002420 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002422 /* Check if we run on the same thread than the xreator thread.
2423 * We cannot access to the socket if the thread is different.
2424 */
2425 if (socket->tid != tid)
2426 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2427
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002429 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002430 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002431 lua_pushinteger(L, -1);
2432 return 1;
2433 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002434
2435 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2436 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002437 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002438 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002439
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002441 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002442 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443 lua_pushinteger(L, -1);
2444 return 1;
2445 }
2446
2447 /* Update the input buffer data. */
2448 buf += sent;
2449 send_len = buf_len - sent;
2450
2451 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002452 if (sent >= buf_len) {
2453 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002455 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002457 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002458 * the request buffer if its not required.
2459 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002460 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002461 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002462 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002463 }
2464
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002465 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002466 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002467 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002468 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002469 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
2471 /* send data */
2472 if (len < send_len)
2473 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002474 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475
2476 /* "Not enough space" (-1), "Buffer too little to contain
2477 * the data" (-2) are not expected because the available length
2478 * is tested.
2479 * Other unknown error are also not expected.
2480 */
2481 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002482 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002483 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002484
sada05ed3302018-05-11 11:48:18 -07002485 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002487 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002488 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002489 return 1;
2490 }
2491
2492 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002493 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002494
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002495 s->req.rex = TICK_ETERNITY;
2496 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002497
2498 /* Update length sent. */
2499 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002500 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501
2502 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002503 if (sent + len >= buf_len) {
2504 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002506 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002507
2508hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002509 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002510 xref_unlock(&socket->xref, peer);
2511 WILL_LJMP(luaL_error(L, "out of memory"));
2512 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002513 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002514 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 return 0;
2516}
2517
2518/* This function initiate the send of data. It just check the input
2519 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002520 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002521 * "hlua_socket_write_yield" that can yield.
2522 *
2523 * The Lua function gets between 3 and 4 parameters. The first one is
2524 * the associated object. The second is a string buffer. The third is
2525 * a facultative integer that represents where is the buffer position
2526 * of the start of the data that can send. The first byte is the
2527 * position "1". The default value is "1". The fourth argument is a
2528 * facultative integer that represents where is the buffer position
2529 * of the end of the data that can send. The default is the last byte.
2530 */
2531static int hlua_socket_send(struct lua_State *L)
2532{
2533 int i;
2534 int j;
2535 const char *buf;
2536 size_t buf_len;
2537
2538 /* Check number of arguments. */
2539 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2540 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2541
2542 /* Get the string. */
2543 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2544
2545 /* Get and check j. */
2546 if (lua_gettop(L) == 4) {
2547 j = MAY_LJMP(luaL_checkinteger(L, 4));
2548 if (j < 0)
2549 j = buf_len + j + 1;
2550 if (j > buf_len)
2551 j = buf_len + 1;
2552 lua_pop(L, 1);
2553 }
2554 else
2555 j = buf_len;
2556
2557 /* Get and check i. */
2558 if (lua_gettop(L) == 3) {
2559 i = MAY_LJMP(luaL_checkinteger(L, 3));
2560 if (i < 0)
2561 i = buf_len + i + 1;
2562 if (i > buf_len)
2563 i = buf_len + 1;
2564 lua_pop(L, 1);
2565 } else
2566 i = 1;
2567
2568 /* Check bth i and j. */
2569 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002570 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002571 return 1;
2572 }
2573 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002574 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575 return 1;
2576 }
2577 if (i == 0)
2578 i = 1;
2579 if (j == 0)
2580 j = 1;
2581
2582 /* Pop the string. */
2583 lua_pop(L, 1);
2584
2585 /* Update the buffer length. */
2586 buf += i - 1;
2587 buf_len = j - i + 1;
2588 lua_pushlstring(L, buf, buf_len);
2589
2590 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002591 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002592
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002593 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594}
2595
Willy Tarreau22b0a682015-06-17 19:43:49 +02002596#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002597__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598{
2599 static char buffer[SOCKET_INFO_MAX_LEN];
2600 int ret;
2601 int len;
2602 char *p;
2603
2604 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2605 if (ret <= 0) {
2606 lua_pushnil(L);
2607 return 1;
2608 }
2609
2610 if (ret == AF_UNIX) {
2611 lua_pushstring(L, buffer+1);
2612 return 1;
2613 }
2614 else if (ret == AF_INET6) {
2615 buffer[0] = '[';
2616 len = strlen(buffer);
2617 buffer[len] = ']';
2618 len++;
2619 buffer[len] = ':';
2620 len++;
2621 p = buffer;
2622 }
2623 else if (ret == AF_INET) {
2624 p = buffer + 1;
2625 len = strlen(p);
2626 p[len] = ':';
2627 len++;
2628 }
2629 else {
2630 lua_pushnil(L);
2631 return 1;
2632 }
2633
2634 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2635 lua_pushnil(L);
2636 return 1;
2637 }
2638
2639 lua_pushstring(L, p);
2640 return 1;
2641}
2642
2643/* Returns information about the peer of the connection. */
2644__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2645{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002646 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002647 struct xref *peer;
2648 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002649 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002650 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002651 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002652
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002653 MAY_LJMP(check_args(L, 1, "getpeername"));
2654
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002655 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002657 /* Check if we run on the same thread than the xreator thread.
2658 * We cannot access to the socket if the thread is different.
2659 */
2660 if (socket->tid != tid)
2661 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2662
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002663 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002664 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002665 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002666 lua_pushnil(L);
2667 return 1;
2668 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002669
2670 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002671 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002672 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002673 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002674 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002675 lua_pushnil(L);
2676 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677 }
2678
Christopher Faulet16f16af2021-10-27 09:34:56 +02002679 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002680 xref_unlock(&socket->xref, peer);
2681 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682}
2683
2684/* Returns information about my connection side. */
2685static int hlua_socket_getsockname(struct lua_State *L)
2686{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002687 struct hlua_socket *socket;
2688 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002689 struct appctx *appctx;
2690 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002691 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002692 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002693
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694 MAY_LJMP(check_args(L, 1, "getsockname"));
2695
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002696 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002697
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002698 /* Check if we run on the same thread than the xreator thread.
2699 * We cannot access to the socket if the thread is different.
2700 */
2701 if (socket->tid != tid)
2702 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2703
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002704 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002705 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002706 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002707 lua_pushnil(L);
2708 return 1;
2709 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002710
2711 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002712 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002714 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002715 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002716 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002717 lua_pushnil(L);
2718 return 1;
2719 }
2720
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002721 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002722 xref_unlock(&socket->xref, peer);
2723 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002724}
2725
2726/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002727static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002728 .obj_type = OBJ_TYPE_APPLET,
2729 .name = "<LUA_TCP>",
2730 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002731 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002732 .release = hlua_socket_release,
2733};
2734
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002735__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002736{
2737 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002738 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002739 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002740 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002741 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002742 struct stream *s;
2743
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002744 /* Get hlua struct, or NULL if we execute from main lua state */
2745 hlua = hlua_gethlua(L);
2746 if (!hlua)
2747 return 0;
2748
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002749 /* Check if we run on the same thread than the xreator thread.
2750 * We cannot access to the socket if the thread is different.
2751 */
2752 if (socket->tid != tid)
2753 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2754
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002755 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002756 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002757 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002758 lua_pushnil(L);
2759 lua_pushstring(L, "Can't connect");
2760 return 2;
2761 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002762
2763 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2764 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002765 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002766
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 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002770 if (socket->tid != tid) {
2771 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002772 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002773 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002774
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002775 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002776 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002777 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002778 lua_pushnil(L);
2779 lua_pushstring(L, "Can't connect");
2780 return 2;
2781 }
2782
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002783 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002784
2785 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002786 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002787 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002788 lua_pushinteger(L, 1);
2789 return 1;
2790 }
2791
Willy Tarreau5321da92022-05-06 11:57:34 +02002792 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002793 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002794 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002795 }
2796 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002797 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002798 return 0;
2799}
2800
2801/* This function fail or initite the connection. */
2802__LJMP static int hlua_socket_connect(struct lua_State *L)
2803{
2804 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002806 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002807 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002808 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002809 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002810 int low, high;
2811 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002812 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002813 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002814 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002815
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002816 if (lua_gettop(L) < 2)
2817 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002818
2819 /* Get args. */
2820 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002821
2822 /* Check if we run on the same thread than the xreator thread.
2823 * We cannot access to the socket if the thread is different.
2824 */
2825 if (socket->tid != tid)
2826 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2827
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002828 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002829 if (lua_gettop(L) >= 3) {
2830 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002831 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002832
Tim Duesterhus6edab862018-01-06 19:04:45 +01002833 /* Force the ip to end with a colon, to support IPv6 addresses
2834 * that are not enclosed within square brackets.
2835 */
2836 if (port > 0) {
2837 luaL_buffinit(L, &b);
2838 luaL_addstring(&b, ip);
2839 luaL_addchar(&b, ':');
2840 luaL_pushresult(&b);
2841 ip = lua_tolstring(L, lua_gettop(L), NULL);
2842 }
2843 }
2844
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002845 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002846 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002847 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002848 lua_pushnil(L);
2849 return 1;
2850 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002851
2852 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002853 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 +02002854 if (!addr) {
2855 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002856 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002857 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002858
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002859 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002860 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002861 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002862 if (port == -1) {
2863 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002864 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002865 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002866 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2867 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002868 if (port == -1) {
2869 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002870 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002871 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002872 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002873 }
2874 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002875
Willy Tarreau5321da92022-05-06 11:57:34 +02002876 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2877 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002878 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002879 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002880
Willy Tarreau3e7be362022-05-27 10:35:27 +02002881 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002882 xref_unlock(&socket->xref, peer);
2883 WILL_LJMP(luaL_error(L, "connect: internal error"));
2884 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002885
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002886 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002887 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002888 if (!hlua)
2889 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002890
2891 /* inform the stream that we want to be notified whenever the
2892 * connection completes.
2893 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002894 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002895 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002896 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002897
Willy Tarreauf31af932020-01-14 09:59:38 +01002898 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002899
Willy Tarreau5321da92022-05-06 11:57:34 +02002900 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002901 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002902 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002903 }
2904 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002905
2906 task_wakeup(s->task, TASK_WOKEN_INIT);
2907 /* Return yield waiting for connection. */
2908
Willy Tarreau9635e032018-10-16 17:52:55 +02002909 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910
2911 return 0;
2912}
2913
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002914#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002915__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2916{
2917 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002918 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002919 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002920
2921 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2922 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002923
2924 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002925 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002926 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927 lua_pushnil(L);
2928 return 1;
2929 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002930
Willy Tarreau0698c802022-05-11 14:09:57 +02002931 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002932
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002933 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002934 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002935 return MAY_LJMP(hlua_socket_connect(L));
2936}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002937#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002938
2939__LJMP static int hlua_socket_setoption(struct lua_State *L)
2940{
2941 return 0;
2942}
2943
2944__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2945{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002946 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002947 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002948 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002949 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002950 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002951
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952 MAY_LJMP(check_args(L, 2, "settimeout"));
2953
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002954 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002955
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002956 /* convert the timeout to millis */
2957 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002958
Thierry Fournier17a921b2018-03-08 09:59:02 +01002959 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002960 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002961 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2962
Mark Lakes56cc1252018-03-27 09:48:06 +02002963 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002964 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002965
2966 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002967 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002968 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002969
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002970 /* Check if we run on the same thread than the xreator thread.
2971 * We cannot access to the socket if the thread is different.
2972 */
2973 if (socket->tid != tid)
2974 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2975
Mark Lakes56cc1252018-03-27 09:48:06 +02002976 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002977 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002978 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002979 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2980 WILL_LJMP(lua_error(L));
2981 return 0;
2982 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002983
Willy Tarreau0698c802022-05-11 14:09:57 +02002984 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002985
Cyril Bonté7bb63452018-08-17 23:51:02 +02002986 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002987 s->req.rto = tmout;
2988 s->req.wto = tmout;
2989 s->res.rto = tmout;
2990 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002991 s->req.rex = tick_add_ifset(now_ms, tmout);
2992 s->req.wex = tick_add_ifset(now_ms, tmout);
2993 s->res.rex = tick_add_ifset(now_ms, tmout);
2994 s->res.wex = tick_add_ifset(now_ms, tmout);
2995
2996 s->task->expire = tick_add_ifset(now_ms, tmout);
2997 task_queue(s->task);
2998
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002999 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003000
Thierry Fourniere9636f12018-03-08 09:54:32 +01003001 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003002 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003003}
3004
3005__LJMP static int hlua_socket_new(lua_State *L)
3006{
3007 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003008 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003009 struct appctx *appctx;
3010
3011 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003012 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003013 hlua_pusherror(L, "socket: full stack");
3014 goto out_fail_conf;
3015 }
3016
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003017 /* Create the object: obj[0] = userdata. */
3018 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003019 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003020 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003022 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003023
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003024 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003025 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003026 hlua_pusherror(L, "socket: uninitialized pools.");
3027 goto out_fail_conf;
3028 }
3029
Willy Tarreau87b09662015-04-03 00:22:06 +02003030 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003031 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3032 lua_setmetatable(L, -2);
3033
Willy Tarreaud420a972015-04-06 00:39:18 +02003034 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003035 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003036 if (!appctx) {
3037 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003038 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003039 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003040 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3041 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003042 ctx->die = 0;
3043 LIST_INIT(&ctx->wake_on_write);
3044 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003045
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003046 if (appctx_init(appctx) == -1) {
3047 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003048 goto out_fail_appctx;
3049 }
3050
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003051 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003052 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003053 return 1;
3054
Christopher Faulet13a35e52021-12-20 15:34:16 +01003055 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003056 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003057 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003058 WILL_LJMP(lua_error(L));
3059 return 0;
3060}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003061
3062/*
3063 *
3064 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003065 * Class Channel
3066 *
3067 *
3068 */
3069
3070/* Returns the struct hlua_channel join to the class channel in the
3071 * stack entry "ud" or throws an argument error.
3072 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003073__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003074{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003075 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003076}
3077
Willy Tarreau47860ed2015-03-10 14:07:50 +01003078/* Pushes the channel onto the top of the stack. If the stask does not have a
3079 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003080 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003081static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003082{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003084 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085 return 0;
3086
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003087 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003088 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003089 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003090
3091 /* Pop a class sesison metatable and affect it to the userdata. */
3092 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3093 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003094 return 1;
3095}
3096
Christopher Faulet9f55a502020-02-25 15:21:02 +01003097/* Helper function returning a filter attached to a channel at the position <ud>
3098 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003099 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003100 * initialized.
3101 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003102static 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 +01003103{
3104 struct filter *filter = NULL;
3105
3106 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3107 struct hlua_flt_ctx *flt_ctx;
3108
3109 filter = lua_touserdata (L, -1);
3110 flt_ctx = filter->ctx;
3111 if (hlua_filter_from_payload(filter)) {
3112 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3113 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3114 }
3115 }
3116
3117 lua_pop(L, 1);
3118 return filter;
3119}
3120
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003121/* Copies <len> bytes of data present in the channel's buffer, starting at the
3122* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003123* responsibility to ensure <len> and <offset> are valid. It always return the
3124* length of the built string. <len> may be 0, in this case, an empty string is
3125* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003126*/
3127static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003129 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003130 luaL_Buffer b;
3131
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003132 block1 = len;
3133 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3134 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3135 block2 = len - block1;
3136
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003137 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003138 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3139 if (block2)
3140 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003141 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003142 return len;
3143}
3144
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003145/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3146 * function returns -1 if data cannot be copied. Otherwise, it returns the
3147 * number of bytes copied.
3148 */
3149static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3150{
3151 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003152
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003153 /* Nothing to do, just return */
3154 if (unlikely(istlen(str) == 0))
3155 goto end;
3156
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003157 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003158 ret = -1;
3159 goto end;
3160 }
3161 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3162
3163 end:
3164 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003165}
3166
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003167/* Removes <len> bytes of data at the absolute position <offset>.
3168 */
3169static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3170{
3171 size_t end = offset + len;
3172
3173 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3174 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3175 b_data(&chn->buf) - end, -len);
3176 b_sub(&chn->buf, len);
3177}
3178
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003179/* Copies input data in the channel's buffer. It is possible to set a specific
3180 * offset (0 by default) and a length (all remaining input data starting for the
3181 * offset by default). If there is not enough input data and more data can be
3182 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003183 *
3184 * From an action, All input data are considered. For a filter, the offset and
3185 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003186 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003187__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003188{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003189 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003190 struct filter *filter;
3191 size_t input, output;
3192 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003193
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003194 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003195
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003196 output = co_data(chn);
3197 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003198
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003199 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3200 if (filter && !hlua_filter_from_payload(filter))
3201 WILL_LJMP(lua_error(L));
3202
3203 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003204 if (lua_gettop(L) > 1) {
3205 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3206 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003207 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208 offset += output;
3209 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 lua_pushfstring(L, "offset out of range.");
3211 WILL_LJMP(lua_error(L));
3212 }
3213 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003214 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003215 if (lua_gettop(L) == 3) {
3216 len = MAY_LJMP(luaL_checkinteger(L, 3));
3217 if (!len)
3218 goto dup;
3219 if (len == -1)
3220 len = global.tune.bufsize;
3221 if (len < 0) {
3222 lua_pushfstring(L, "length out of range.");
3223 WILL_LJMP(lua_error(L));
3224 }
3225 }
3226
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003227 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3229 /* Yield waiting for more data, as requested */
3230 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3231 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003232 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003233 }
3234
3235 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003237 return 1;
3238}
3239
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003240/* Copies the first line (including the trailing LF) of input data in the
3241 * channel's buffer. It is possible to set a specific offset (0 by default) and
3242 * a length (all remaining input data starting for the offset by default). If
3243 * there is not enough input data and more data can be received, the function
3244 * yields. If a length is explicitly specified, no more data are
3245 * copied. Otherwise, if no LF is found and more data can be received, this
3246 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003247 *
3248 * From an action, All input data are considered. For a filter, the offset and
3249 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003250 */
3251__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003252{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003253 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 struct filter *filter;
3255 size_t l, input, output;
3256 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003257
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003258 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003259 output = co_data(chn);
3260 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003261
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003262 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3263 if (filter && !hlua_filter_from_payload(filter))
3264 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003265
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003266 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003267 if (lua_gettop(L) > 1) {
3268 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3269 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003270 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003271 offset += output;
3272 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003273 lua_pushfstring(L, "offset out of range.");
3274 WILL_LJMP(lua_error(L));
3275 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003276 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003277
3278 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003279 if (lua_gettop(L) == 3) {
3280 len = MAY_LJMP(luaL_checkinteger(L, 3));
3281 if (!len)
3282 goto dup;
3283 if (len == -1)
3284 len = global.tune.bufsize;
3285 if (len < 0) {
3286 lua_pushfstring(L, "length out of range.");
3287 WILL_LJMP(lua_error(L));
3288 }
3289 }
3290
3291 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003292 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003293 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003294 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003295 len = l+1;
3296 goto dup;
3297 }
3298 }
3299
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003301 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3302 /* Yield waiting for more data */
3303 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3304 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003305 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003306 }
3307
3308 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003309 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003310 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003311}
3312
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003313/* [ DEPRECATED ]
3314 *
3315 * Duplicate all input data foud in the channel's buffer. The data are not
3316 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003317 *
3318 * From an action, All input data are considered. For a filter, the offset and
3319 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003320 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003321__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003322{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003323 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003324 struct filter *filter;
3325 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003326
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003327 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003328 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003329 if (IS_HTX_STRM(chn_strm(chn))) {
3330 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3331 WILL_LJMP(lua_error(L));
3332 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003333
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003334 offset = co_data(chn);
3335 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003336
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003337 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3338 if (filter && !hlua_filter_from_payload(filter))
3339 WILL_LJMP(lua_error(L));
3340
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003341 if (!ci_data(chn) && channel_input_closed(chn)) {
3342 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003343 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003344 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003345
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003346 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003347 return 1;
3348}
3349
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003350/* [ DEPRECATED ]
3351 *
3352 * Get all input data foud in the channel's buffer. The data are removed from
3353 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3354 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003355 *
3356 * From an action, All input data are considered. For a filter, the offset and
3357 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003358 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003359__LJMP static int hlua_channel_get(lua_State *L)
3360{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003361 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003362 struct filter *filter;
3363 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003364 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003365
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003366 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003367 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3368 if (IS_HTX_STRM(chn_strm(chn))) {
3369 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3370 WILL_LJMP(lua_error(L));
3371 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003372
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003373 offset = co_data(chn);
3374 len = ci_data(chn);
3375
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003376 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3377 if (filter && !hlua_filter_from_payload(filter))
3378 WILL_LJMP(lua_error(L));
3379
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003380 if (!ci_data(chn) && channel_input_closed(chn)) {
3381 lua_pushnil(L);
3382 return 1;
3383 }
3384
3385 ret = _hlua_channel_dup(chn, L, offset, len);
3386 _hlua_channel_delete(chn, offset, ret);
3387 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003388}
3389
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003390/* This functions consumes and returns one line. If the channel is closed,
3391 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003392 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003393 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003394 *
3395 * From an action, All input data are considered. For a filter, the offset and
3396 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003397 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003398__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003399{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003400 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003401 struct filter *filter;
3402 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003403 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003404
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003405 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003406
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003407 offset = co_data(chn);
3408 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003409
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003410 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3411 if (filter && !hlua_filter_from_payload(filter))
3412 WILL_LJMP(lua_error(L));
3413
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003414 if (!ci_data(chn) && channel_input_closed(chn)) {
3415 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003416 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003417 }
3418
3419 for (l = 0; l < len; l++) {
3420 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3421 len = l+1;
3422 goto dup;
3423 }
3424 }
3425
3426 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3427 /* Yield waiting for more data */
3428 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3429 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003430
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003431 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003432 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003433 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003434 return 1;
3435}
3436
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003437/* [ DEPRECATED ]
3438 *
3439 * Check arguments for the function "hlua_channel_getline_yield".
3440 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003441__LJMP static int hlua_channel_getline(lua_State *L)
3442{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003443 struct channel *chn;
3444
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003445 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003446 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3447 if (IS_HTX_STRM(chn_strm(chn))) {
3448 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3449 WILL_LJMP(lua_error(L));
3450 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003451 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3452}
3453
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003454/* Retrieves a given amount of input data at the given offset. By default all
3455 * available input data are returned. The offset may be negactive to start from
3456 * the end of input data. The length may be -1 to set it to the maximum buffer
3457 * size.
3458 */
3459__LJMP static int hlua_channel_get_data(lua_State *L)
3460{
3461 struct channel *chn;
3462
3463 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3464 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3465 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3466 if (IS_HTX_STRM(chn_strm(chn))) {
3467 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3468 WILL_LJMP(lua_error(L));
3469 }
3470 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3471}
3472
3473/* Retrieves a given amount of input data at the given offset. By default all
3474 * available input data are returned. The offset may be negactive to start from
3475 * the end of input data. The length may be -1 to set it to the maximum buffer
3476 * size.
3477 */
3478__LJMP static int hlua_channel_get_line(lua_State *L)
3479{
3480 struct channel *chn;
3481
3482 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3483 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3484 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3485 if (IS_HTX_STRM(chn_strm(chn))) {
3486 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3487 WILL_LJMP(lua_error(L));
3488 }
3489 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3490}
3491
3492/* Appends a string into the input side of channel. It returns the length of the
3493 * written string, or -1 if the channel is closed or if the buffer size is too
3494 * little for the data. 0 may be returned if nothing is copied. This function
3495 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003496 *
3497 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003498 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003499__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003500{
Christopher Faulet23976d92021-08-06 09:59:49 +02003501 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003502 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003503 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003504 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003505 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003506
3507 MAY_LJMP(check_args(L, 2, "append"));
3508 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003509 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003510 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003511 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003512 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003513 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003514
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003515 offset = co_data(chn);
3516 len = ci_data(chn);
3517
3518 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3519 if (filter && !hlua_filter_from_payload(filter))
3520 WILL_LJMP(lua_error(L));
3521
3522 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3523 if (ret > 0 && filter) {
3524 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3525
3526 flt_update_offsets(filter, chn, ret);
3527 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3528 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003529 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003530 return 1;
3531}
3532
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003533/* Prepends a string into the input side of channel. It returns the length of the
3534 * written string, or -1 if the channel is closed or if the buffer size is too
3535 * little for the data. 0 may be returned if nothing is copied. This function
3536 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 *
3538 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003539 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003540__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003541{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003542 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003543 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003544 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003545 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003546 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003547
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003548 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003549 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003550 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3551 if (IS_HTX_STRM(chn_strm(chn))) {
3552 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3553 WILL_LJMP(lua_error(L));
3554 }
3555
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003556 offset = co_data(chn);
3557 len = ci_data(chn);
3558
3559 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3560 if (filter && !hlua_filter_from_payload(filter))
3561 WILL_LJMP(lua_error(L));
3562
3563 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3564 if (ret > 0 && filter) {
3565 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3566
3567 flt_update_offsets(filter, chn, ret);
3568 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3569 }
3570
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 lua_pushinteger(L, ret);
3572 return 1;
3573}
3574
3575/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003576 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003577 * returns the length of the written string, or -1 if the channel is closed or
3578 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003579 *
3580 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 */
3582__LJMP static int hlua_channel_insert_data(lua_State *L)
3583{
3584 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003586 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003587 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588 int ret, offset;
3589
3590 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3591 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3592 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3593 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003594
3595 output = co_data(chn);
3596 input = ci_data(chn);
3597
3598 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3599 if (filter && !hlua_filter_from_payload(filter))
3600 WILL_LJMP(lua_error(L));
3601
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003602 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003606 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003607 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003608 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003609 lua_pushfstring(L, "offset out of range.");
3610 WILL_LJMP(lua_error(L));
3611 }
3612 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003613 if (IS_HTX_STRM(chn_strm(chn))) {
3614 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3615 WILL_LJMP(lua_error(L));
3616 }
3617
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003618 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3619 if (ret > 0 && filter) {
3620 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003622 flt_update_offsets(filter, chn, ret);
3623 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624 }
3625
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003626 lua_pushinteger(L, ret);
3627 return 1;
3628}
3629/* Replaces a given amount of input data at the given offset by a string
3630 * content. By default all remaining data are removed (offset = 0 and len =
3631 * -1). It returns the length of the written string, or -1 if the channel is
3632 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003633 *
3634 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 */
3636__LJMP static int hlua_channel_set_data(lua_State *L)
3637{
3638 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003639 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003640 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003641 size_t sz, input, output;
3642 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003643
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3645 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3646 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3647 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003648
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003649 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003650 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003651 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003652 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003653
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003654 output = co_data(chn);
3655 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003656
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3658 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003659 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003660
3661 offset = output;
3662 if (lua_gettop(L) > 2) {
3663 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3664 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003665 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666 offset += output;
3667 if (offset < output || offset > input + output) {
3668 lua_pushfstring(L, "offset out of range.");
3669 WILL_LJMP(lua_error(L));
3670 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003671 }
3672
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003673 len = output + input - offset;
3674 if (lua_gettop(L) == 4) {
3675 len = MAY_LJMP(luaL_checkinteger(L, 4));
3676 if (!len)
3677 goto set;
3678 if (len == -1)
3679 len = output + input - offset;
3680 if (len < 0 || offset + len > output + input) {
3681 lua_pushfstring(L, "length out of range.");
3682 WILL_LJMP(lua_error(L));
3683 }
3684 }
3685
3686 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003687 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003689 lua_pushinteger(L, -1);
3690 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003691 _hlua_channel_delete(chn, offset, len);
3692 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3693 if (filter) {
3694 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3695
3696 len -= (ret > 0 ? ret : 0);
3697 flt_update_offsets(filter, chn, -len);
3698 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3699 }
3700
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003701 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003702 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 return 1;
3704}
3705
3706/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003707 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003708 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003709 *
3710 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003711 */
3712__LJMP static int hlua_channel_del_data(lua_State *L)
3713{
3714 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003715 struct filter *filter;
3716 size_t input, output;
3717 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003718
3719 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3720 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3721 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003722
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003723 if (IS_HTX_STRM(chn_strm(chn))) {
3724 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3725 WILL_LJMP(lua_error(L));
3726 }
3727
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003728 output = co_data(chn);
3729 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003730
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003731 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3732 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003733 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003734
3735 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003736 if (lua_gettop(L) > 1) {
3737 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003738 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003739 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003740 offset += output;
3741 if (offset < output || offset > input + output) {
3742 lua_pushfstring(L, "offset out of range.");
3743 WILL_LJMP(lua_error(L));
3744 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003745 }
3746
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003748 if (lua_gettop(L) == 3) {
3749 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003750 if (!len)
3751 goto end;
3752 if (len == -1)
3753 len = output + input - offset;
3754 if (len < 0 || offset + len > output + input) {
3755 lua_pushfstring(L, "length out of range.");
3756 WILL_LJMP(lua_error(L));
3757 }
3758 }
3759
3760 _hlua_channel_delete(chn, offset, len);
3761 if (filter) {
3762 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3763
3764 flt_update_offsets(filter, chn, -len);
3765 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3766 }
3767
3768 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003769 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003770 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003771}
3772
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003773/* Append data in the output side of the buffer. This data is immediately
3774 * sent. The function returns the amount of data written. If the buffer
3775 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003776 * if the channel is closed.
3777 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003778__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003779{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003780 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003781 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003782 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003783 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003784 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003785 struct hlua *hlua;
3786
3787 /* Get hlua struct, or NULL if we execute from main lua state */
3788 hlua = hlua_gethlua(L);
3789 if (!hlua) {
3790 lua_pushnil(L);
3791 return 1;
3792 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003793
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003794 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3795 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3796 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003797
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003798 offset = co_data(chn);
3799 len = ci_data(chn);
3800
3801 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3802 if (filter && !hlua_filter_from_payload(filter))
3803 WILL_LJMP(lua_error(L));
3804
3805
Willy Tarreau47860ed2015-03-10 14:07:50 +01003806 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003807 lua_pushinteger(L, -1);
3808 return 1;
3809 }
3810
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003811 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003812 if (len > sz -l) {
3813 if (filter) {
3814 lua_pushinteger(L, -1);
3815 return 1;
3816 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003817 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003818 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003819
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003820 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003821 if (ret == -1) {
3822 lua_pop(L, 1);
3823 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003824 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003825 }
3826 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003827 if (filter) {
3828 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3829
3830
3831 flt_update_offsets(filter, chn, ret);
3832 FLT_OFF(filter, chn) += ret;
3833 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3834 }
3835 else
3836 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003837
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 l += ret;
3839 lua_pop(L, 1);
3840 lua_pushinteger(L, l);
3841 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003843 if (l < sz) {
3844 /* Yield only if the channel's output is not empty.
3845 * Otherwise it means we cannot add more data. */
3846 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003847 return 1;
3848
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003849 /* If we are waiting for space in the response buffer, we
3850 * must set the flag WAKERESWR. This flag required the task
3851 * wake up if any activity is detected on the response buffer.
3852 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003853 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003854 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003855 else
3856 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003857 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003858 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003859
3860 return 1;
3861}
3862
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003863/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003864 * yield the LUA process, and resume it without checking the
3865 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003866 *
3867 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868 */
3869__LJMP static int hlua_channel_send(lua_State *L)
3870{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003871 struct channel *chn;
3872
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003873 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003874 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3875 if (IS_HTX_STRM(chn_strm(chn))) {
3876 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3877 WILL_LJMP(lua_error(L));
3878 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003879 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003880 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003881}
3882
3883/* This function forward and amount of butes. The data pass from
3884 * the input side of the buffer to the output side, and can be
3885 * forwarded. This function never fails.
3886 *
3887 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003888 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003889 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003890__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003891{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003892 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003893 struct filter *filter;
3894 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003895 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003896 struct hlua *hlua;
3897
3898 /* Get hlua struct, or NULL if we execute from main lua state */
3899 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003900 if (!hlua) {
3901 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003902 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003903 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003904
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003905 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003906 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907 l = MAY_LJMP(luaL_checkinteger(L, -1));
3908
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003909 offset = co_data(chn);
3910 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003911
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003912 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3913 if (filter && !hlua_filter_from_payload(filter))
3914 WILL_LJMP(lua_error(L));
3915
3916 max = fwd - l;
3917 if (max > len)
3918 max = len;
3919
3920 if (filter) {
3921 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3922
3923 FLT_OFF(filter, chn) += max;
3924 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3925 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3926 }
3927 else
3928 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003929
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003930 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003931 lua_pop(L, 1);
3932 lua_pushinteger(L, l);
3933
3934 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003935 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003936 /* The the input channel or the output channel are closed, we
3937 * must return the amount of data forwarded.
3938 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003939 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003940 return 1;
3941
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003942 /* If we are waiting for space data in the response buffer, we
3943 * must set the flag WAKERESWR. This flag required the task
3944 * wake up if any activity is detected on the response buffer.
3945 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003946 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003947 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003948 else
3949 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003950
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003951 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003952 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003953 }
3954
3955 return 1;
3956}
3957
3958/* Just check the input and prepare the stack for the previous
3959 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960 *
3961 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003962 */
3963__LJMP static int hlua_channel_forward(lua_State *L)
3964{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003965 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003966
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003967 MAY_LJMP(check_args(L, 2, "forward"));
3968 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3969 if (IS_HTX_STRM(chn_strm(chn))) {
3970 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3971 WILL_LJMP(lua_error(L));
3972 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003973 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003974 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003975}
3976
3977/* Just returns the number of bytes available in the input
3978 * side of the buffer. This function never fails.
3979 */
3980__LJMP static int hlua_channel_get_in_len(lua_State *L)
3981{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003982 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003983 struct filter *filter;
3984 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003985
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003986 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003987 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003988
3989 output = co_data(chn);
3990 input = ci_data(chn);
3991 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3992 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3993 lua_pushinteger(L, input);
3994 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003995 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003996
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003997 lua_pushinteger(L, htx->data - co_data(chn));
3998 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003999 return 1;
4000}
4001
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004002/* Returns true if the channel is full. */
4003__LJMP static int hlua_channel_is_full(lua_State *L)
4004{
4005 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004006
4007 MAY_LJMP(check_args(L, 1, "is_full"));
4008 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004009 /* ignore the reserve, we are not on a producer side (ie in an
4010 * applet).
4011 */
4012 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004013 return 1;
4014}
4015
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004016/* Returns true if the channel may still receive data. */
4017__LJMP static int hlua_channel_may_recv(lua_State *L)
4018{
4019 struct channel *chn;
4020
4021 MAY_LJMP(check_args(L, 1, "may_recv"));
4022 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4023 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4024 return 1;
4025}
4026
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004027/* Returns true if the channel is the response channel. */
4028__LJMP static int hlua_channel_is_resp(lua_State *L)
4029{
4030 struct channel *chn;
4031
4032 MAY_LJMP(check_args(L, 1, "is_resp"));
4033 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4034
4035 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4036 return 1;
4037}
4038
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004039/* Just returns the number of bytes available in the output
4040 * side of the buffer. This function never fails.
4041 */
4042__LJMP static int hlua_channel_get_out_len(lua_State *L)
4043{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004044 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004045 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004046
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004047 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004048 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004049
4050 output = co_data(chn);
4051 input = ci_data(chn);
4052 hlua_channel_filter(L, 1, chn, &output, &input);
4053
4054 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004055 return 1;
4056}
4057
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004058/*
4059 *
4060 *
4061 * Class Fetches
4062 *
4063 *
4064 */
4065
4066/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004067 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004068 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004069__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004070{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004071 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004072}
4073
4074/* This function creates and push in the stack a fetch object according
4075 * with a current TXN.
4076 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004077static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078{
Willy Tarreau7073c472015-04-06 11:15:40 +02004079 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004080
4081 /* Check stack size. */
4082 if (!lua_checkstack(L, 3))
4083 return 0;
4084
4085 /* Create the object: obj[0] = userdata.
4086 * Note that the base of the Fetches object is the
4087 * transaction object.
4088 */
4089 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004090 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004091 lua_rawseti(L, -2, 0);
4092
Willy Tarreau7073c472015-04-06 11:15:40 +02004093 hsmp->s = txn->s;
4094 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004095 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004096 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004097
4098 /* Pop a class sesison metatable and affect it to the userdata. */
4099 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4100 lua_setmetatable(L, -2);
4101
4102 return 1;
4103}
4104
4105/* This function is an LUA binding. It is called with each sample-fetch.
4106 * It uses closure argument to store the associated sample-fetch. It
4107 * returns only one argument or throws an error. An error is thrown
4108 * only if an error is encountered during the argument parsing. If
4109 * the "sample-fetch" function fails, nil is returned.
4110 */
4111__LJMP static int hlua_run_sample_fetch(lua_State *L)
4112{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004113 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004114 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004115 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004116 int i;
4117 struct sample smp;
4118
4119 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004120 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004121
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004122 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004123 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004124
Thierry FOURNIERca988662015-12-20 18:43:03 +01004125 /* Check execution authorization. */
4126 if (f->use & SMP_USE_HTTP_ANY &&
4127 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4128 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4129 "is not available in Lua services", f->kw);
4130 WILL_LJMP(lua_error(L));
4131 }
4132
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004133 /* Get extra arguments. */
4134 for (i = 0; i < lua_gettop(L) - 1; i++) {
4135 if (i >= ARGM_NBARGS)
4136 break;
4137 hlua_lua2arg(L, i + 2, &args[i]);
4138 }
4139 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004140 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004141
4142 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004143 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004144
4145 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004146 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004147 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004148 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004149 }
4150
4151 /* Initialise the sample. */
4152 memset(&smp, 0, sizeof(smp));
4153
4154 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004155 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004156 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004157 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004158 lua_pushstring(L, "");
4159 else
4160 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004161 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004162 }
4163
4164 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004165 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004166 hlua_smp2lua_str(L, &smp);
4167 else
4168 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004169
4170 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004171 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004172 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004173
4174 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004175 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004176 WILL_LJMP(lua_error(L));
4177 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004178}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004179
4180/*
4181 *
4182 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004183 * Class Converters
4184 *
4185 *
4186 */
4187
4188/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004189 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004190 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004191__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004192{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004193 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004194}
4195
4196/* This function creates and push in the stack a Converters object
4197 * according with a current TXN.
4198 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004199static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004200{
Willy Tarreau7073c472015-04-06 11:15:40 +02004201 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004202
4203 /* Check stack size. */
4204 if (!lua_checkstack(L, 3))
4205 return 0;
4206
4207 /* Create the object: obj[0] = userdata.
4208 * Note that the base of the Converters object is the
4209 * same than the TXN object.
4210 */
4211 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004212 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213 lua_rawseti(L, -2, 0);
4214
Willy Tarreau7073c472015-04-06 11:15:40 +02004215 hsmp->s = txn->s;
4216 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004217 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004218 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004219
Willy Tarreau87b09662015-04-03 00:22:06 +02004220 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004221 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4222 lua_setmetatable(L, -2);
4223
4224 return 1;
4225}
4226
4227/* This function is an LUA binding. It is called with each converter.
4228 * It uses closure argument to store the associated converter. It
4229 * returns only one argument or throws an error. An error is thrown
4230 * only if an error is encountered during the argument parsing. If
4231 * the converter function function fails, nil is returned.
4232 */
4233__LJMP static int hlua_run_sample_conv(lua_State *L)
4234{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004235 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004236 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004237 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238 int i;
4239 struct sample smp;
4240
4241 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004242 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004243
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004244 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004245 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004246
4247 /* Get extra arguments. */
4248 for (i = 0; i < lua_gettop(L) - 2; i++) {
4249 if (i >= ARGM_NBARGS)
4250 break;
4251 hlua_lua2arg(L, i + 3, &args[i]);
4252 }
4253 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004254 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004255
4256 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004257 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004258
4259 /* Run the special args checker. */
4260 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4261 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004262 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004263 }
4264
4265 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004266 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004267 if (!hlua_lua2smp(L, 2, &smp)) {
4268 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004269 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004270 }
4271
Willy Tarreau1777ea62016-03-10 16:15:46 +01004272 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4273
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004274 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004275 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004276 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004277 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004278 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004279 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004280 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4281 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004282 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004283 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004284 }
4285
4286 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004287 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004288 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004289 lua_pushstring(L, "");
4290 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004291 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004292 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004293 }
4294
4295 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004296 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004297 hlua_smp2lua_str(L, &smp);
4298 else
4299 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004300 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004301 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004302 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004303
4304 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004305 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004306 WILL_LJMP(lua_error(L));
4307 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004308}
4309
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004310/*
4311 *
4312 *
4313 * Class AppletTCP
4314 *
4315 *
4316 */
4317
4318/* Returns a struct hlua_txn if the stack entry "ud" is
4319 * a class stream, otherwise it throws an error.
4320 */
4321__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4322{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004323 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004324}
4325
4326/* This function creates and push in the stack an Applet object
4327 * according with a current TXN.
4328 */
4329static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4330{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004331 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004332 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004333 struct proxy *p;
4334
4335 ALREADY_CHECKED(s);
4336 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004337
4338 /* Check stack size. */
4339 if (!lua_checkstack(L, 3))
4340 return 0;
4341
4342 /* Create the object: obj[0] = userdata.
4343 * Note that the base of the Converters object is the
4344 * same than the TXN object.
4345 */
4346 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004347 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004348 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004349 luactx->appctx = ctx;
4350 luactx->htxn.s = s;
4351 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004352
4353 /* Create the "f" field that contains a list of fetches. */
4354 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004355 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004356 return 0;
4357 lua_settable(L, -3);
4358
4359 /* Create the "sf" field that contains a list of stringsafe fetches. */
4360 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004361 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004362 return 0;
4363 lua_settable(L, -3);
4364
4365 /* Create the "c" field that contains a list of converters. */
4366 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004368 return 0;
4369 lua_settable(L, -3);
4370
4371 /* Create the "sc" field that contains a list of stringsafe converters. */
4372 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004373 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004374 return 0;
4375 lua_settable(L, -3);
4376
4377 /* Pop a class stream metatable and affect it to the table. */
4378 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4379 lua_setmetatable(L, -2);
4380
4381 return 1;
4382}
4383
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004384__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4385{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004386 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004387 struct stream *s;
4388 const char *name;
4389 size_t len;
4390 struct sample smp;
4391
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004392 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4393 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004394
4395 /* It is useles to retrieve the stream, but this function
4396 * runs only in a stream context.
4397 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004398 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004399 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004400 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004401
4402 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004403 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004404 hlua_lua2smp(L, 3, &smp);
4405
4406 /* Store the sample in a variable. */
4407 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004408
4409 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4410 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4411 else
4412 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4413
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004414 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004415}
4416
4417__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4418{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004419 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004420 struct stream *s;
4421 const char *name;
4422 size_t len;
4423 struct sample smp;
4424
4425 MAY_LJMP(check_args(L, 2, "unset_var"));
4426
4427 /* It is useles to retrieve the stream, but this function
4428 * runs only in a stream context.
4429 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004430 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004431 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004432 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433
4434 /* Unset the variable. */
4435 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004436 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4437 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438}
4439
4440__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4441{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004442 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004443 struct stream *s;
4444 const char *name;
4445 size_t len;
4446 struct sample smp;
4447
4448 MAY_LJMP(check_args(L, 2, "get_var"));
4449
4450 /* It is useles to retrieve the stream, but this function
4451 * runs only in a stream context.
4452 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004453 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004454 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004455 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004456
4457 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004458 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004459 lua_pushnil(L);
4460 return 1;
4461 }
4462
4463 return hlua_smp2lua(L, &smp);
4464}
4465
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004466__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4467{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004468 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4469 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004470 struct hlua *hlua;
4471
4472 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004473 if (!s->hlua)
4474 return 0;
4475 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004476
4477 MAY_LJMP(check_args(L, 2, "set_priv"));
4478
4479 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004480 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004481
4482 /* Get and store new value. */
4483 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4484 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4485
4486 return 0;
4487}
4488
4489__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4490{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004491 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4492 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004493 struct hlua *hlua;
4494
4495 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004496 if (!s->hlua) {
4497 lua_pushnil(L);
4498 return 1;
4499 }
4500 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004501
4502 /* Push configuration index in the stack. */
4503 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4504
4505 return 1;
4506}
4507
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004508/* If expected data not yet available, it returns a yield. This function
4509 * consumes the data in the buffer. It returns a string containing the
4510 * data. This string can be empty.
4511 */
4512__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4513{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004514 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004515 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004517 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004518 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004519 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004520 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004522 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004523 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004524
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004525 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004526 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004527 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004528 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529 }
4530
4531 /* End of data: commit the total strings and return. */
4532 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004533 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004534 return 1;
4535 }
4536
4537 /* Ensure that the block 2 length is usable. */
4538 if (ret == 1)
4539 len2 = 0;
4540
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004541 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004542 luaL_addlstring(&luactx->b, blk1, len1);
4543 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544
4545 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004546 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004547 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004548 return 1;
4549}
4550
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004551/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004552__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4553{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004554 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004555
4556 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004557 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004558
4559 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4560}
4561
4562/* If expected data not yet available, it returns a yield. This function
4563 * consumes the data in the buffer. It returns a string containing the
4564 * data. This string can be empty.
4565 */
4566__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4567{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004568 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004569 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004570 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004571 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004572 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004573 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004574 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004575 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004577 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004578 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004579
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004580 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004581 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004582 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004583 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584 }
4585
4586 /* End of data: commit the total strings and return. */
4587 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004588 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589 return 1;
4590 }
4591
4592 /* Ensure that the block 2 length is usable. */
4593 if (ret == 1)
4594 len2 = 0;
4595
4596 if (len == -1) {
4597
4598 /* If len == -1, catenate all the data avalaile and
4599 * yield because we want to get all the data until
4600 * the end of data stream.
4601 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004602 luaL_addlstring(&luactx->b, blk1, len1);
4603 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004604 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004605 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004606 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607
4608 } else {
4609
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004610 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004611 if (len1 > len)
4612 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004613 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004614 len -= len1;
4615
4616 /* Copy the second block. */
4617 if (len2 > len)
4618 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004619 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004620 len -= len2;
4621
4622 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004623 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004624
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004625 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626 if (len > 0) {
4627 lua_pushinteger(L, len);
4628 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004629 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004630 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004631 }
4632
4633 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004634 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004635 return 1;
4636 }
4637
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004638 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004639 hlua_pusherror(L, "Lua: internal error");
4640 WILL_LJMP(lua_error(L));
4641 return 0;
4642}
4643
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004644/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004645__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4646{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004647 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004648 int len = -1;
4649
4650 if (lua_gettop(L) > 2)
4651 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4652 if (lua_gettop(L) >= 2) {
4653 len = MAY_LJMP(luaL_checkinteger(L, 2));
4654 lua_pop(L, 1);
4655 }
4656
4657 /* Confirm or set the required length */
4658 lua_pushinteger(L, len);
4659
4660 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004661 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004662
4663 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4664}
4665
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004666/* Append data in the output side of the buffer. This data is immediately
4667 * sent. The function returns the amount of data written. If the buffer
4668 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004669 * if the channel is closed.
4670 */
4671__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4672{
4673 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004674 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004675 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4676 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004677 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004678 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004679 int max;
4680
4681 /* Get the max amount of data which can write as input in the channel. */
4682 max = channel_recv_max(chn);
4683 if (max > (len - l))
4684 max = len - l;
4685
4686 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004687 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004688
4689 /* update counters. */
4690 l += max;
4691 lua_pop(L, 1);
4692 lua_pushinteger(L, l);
4693
4694 /* If some data is not send, declares the situation to the
4695 * applet, and returns a yield.
4696 */
4697 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004698 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004699 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004700 }
4701
4702 return 1;
4703}
4704
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004705/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004706 * yield the LUA process, and resume it without checking the
4707 * input arguments.
4708 */
4709__LJMP static int hlua_applet_tcp_send(lua_State *L)
4710{
4711 MAY_LJMP(check_args(L, 2, "send"));
4712 lua_pushinteger(L, 0);
4713
4714 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4715}
4716
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004717/*
4718 *
4719 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004720 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004721 *
4722 *
4723 */
4724
4725/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004726 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004727 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004728__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004730 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004731}
4732
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004733/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004734 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004735 * It relies on the caller to have already reserved the room in ctx->svcctx
4736 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004737 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004738static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004739{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004740 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004741 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004742 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004743 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004744 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004745 struct htx *htx;
4746 struct htx_blk *blk;
4747 struct htx_sl *sl;
4748 struct ist path;
4749 unsigned long long len = 0;
4750 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004751 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004752
4753 /* Check stack size. */
4754 if (!lua_checkstack(L, 3))
4755 return 0;
4756
4757 /* Create the object: obj[0] = userdata.
4758 * Note that the base of the Converters object is the
4759 * same than the TXN object.
4760 */
4761 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004762 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004763 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004764 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004765 http_ctx->status = 200; /* Default status code returned. */
4766 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 luactx->htxn.s = s;
4768 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004769
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004770 /* Create the "f" field that contains a list of fetches. */
4771 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004772 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004773 return 0;
4774 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004775
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004776 /* Create the "sf" field that contains a list of stringsafe fetches. */
4777 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004778 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004779 return 0;
4780 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004781
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004782 /* Create the "c" field that contains a list of converters. */
4783 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004784 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004785 return 0;
4786 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004788 /* Create the "sc" field that contains a list of stringsafe converters. */
4789 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004790 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004791 return 0;
4792 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004793
Christopher Fauleta2097962019-07-15 16:25:33 +02004794 htx = htxbuf(&s->req.buf);
4795 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004796 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004797 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004798
Christopher Fauleta2097962019-07-15 16:25:33 +02004799 /* Stores the request method. */
4800 lua_pushstring(L, "method");
4801 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4802 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004803
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 /* Stores the http version. */
4805 lua_pushstring(L, "version");
4806 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4807 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004808
Christopher Fauleta2097962019-07-15 16:25:33 +02004809 /* creates an array of headers. hlua_http_get_headers() crates and push
4810 * the array on the top of the stack.
4811 */
4812 lua_pushstring(L, "headers");
4813 htxn.s = s;
4814 htxn.p = px;
4815 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004816 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004817 return 0;
4818 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004819
Amaury Denoyellec453f952021-07-06 11:40:12 +02004820 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4821 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004822 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004823 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004824
Christopher Fauleta2097962019-07-15 16:25:33 +02004825 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004826 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004827 q = p;
4828 while (q < end && *q != '?')
4829 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004830
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004831 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004832 lua_pushstring(L, "path");
4833 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004834 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004835
Christopher Fauleta2097962019-07-15 16:25:33 +02004836 /* Stores the query string. */
4837 lua_pushstring(L, "qs");
4838 if (*q == '?')
4839 q++;
4840 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004841 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004842 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004843
Christopher Fauleta2097962019-07-15 16:25:33 +02004844 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4845 struct htx_blk *blk = htx_get_blk(htx, pos);
4846 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004847
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004848 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004849 break;
4850 if (type == HTX_BLK_DATA)
4851 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004852 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004853 if (htx->extra != ULLONG_MAX)
4854 len += htx->extra;
4855
4856 /* Stores the request path. */
4857 lua_pushstring(L, "length");
4858 lua_pushinteger(L, len);
4859 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004861 /* Create an empty array of HTTP request headers. */
4862 lua_pushstring(L, "response");
4863 lua_newtable(L);
4864 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004865
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004866 /* Pop a class stream metatable and affect it to the table. */
4867 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4868 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004869
4870 return 1;
4871}
4872
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004873__LJMP static int hlua_applet_http_set_var(lua_State *L)
4874{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004875 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004876 struct stream *s;
4877 const char *name;
4878 size_t len;
4879 struct sample smp;
4880
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004881 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4882 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883
4884 /* It is useles to retrieve the stream, but this function
4885 * runs only in a stream context.
4886 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004887 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004889 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004890
4891 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004892 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004893 hlua_lua2smp(L, 3, &smp);
4894
4895 /* Store the sample in a variable. */
4896 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004897
4898 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4899 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4900 else
4901 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4902
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004903 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904}
4905
4906__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4907{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004908 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004909 struct stream *s;
4910 const char *name;
4911 size_t len;
4912 struct sample smp;
4913
4914 MAY_LJMP(check_args(L, 2, "unset_var"));
4915
4916 /* It is useles to retrieve the stream, but this function
4917 * runs only in a stream context.
4918 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004919 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004920 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004921 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922
4923 /* Unset the variable. */
4924 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004925 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4926 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927}
4928
4929__LJMP static int hlua_applet_http_get_var(lua_State *L)
4930{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004931 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004932 struct stream *s;
4933 const char *name;
4934 size_t len;
4935 struct sample smp;
4936
4937 MAY_LJMP(check_args(L, 2, "get_var"));
4938
4939 /* It is useles to retrieve the stream, but this function
4940 * runs only in a stream context.
4941 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004942 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004943 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004944 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004945
4946 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004947 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004948 lua_pushnil(L);
4949 return 1;
4950 }
4951
4952 return hlua_smp2lua(L, &smp);
4953}
4954
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004955__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4956{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004957 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4958 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004959 struct hlua *hlua;
4960
4961 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004962 if (!s->hlua)
4963 return 0;
4964 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004965
4966 MAY_LJMP(check_args(L, 2, "set_priv"));
4967
4968 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004969 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004970
4971 /* Get and store new value. */
4972 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4973 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4974
4975 return 0;
4976}
4977
4978__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4979{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004980 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4981 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004982 struct hlua *hlua;
4983
4984 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004985 if (!s->hlua) {
4986 lua_pushnil(L);
4987 return 1;
4988 }
4989 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004990
4991 /* Push configuration index in the stack. */
4992 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4993
4994 return 1;
4995}
4996
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004997/* If expected data not yet available, it returns a yield. This function
4998 * consumes the data in the buffer. It returns a string containing the
4999 * data. This string can be empty.
5000 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005001__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005002{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005003 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005004 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005005 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005006 struct htx *htx;
5007 struct htx_blk *blk;
5008 size_t count;
5009 int stop = 0;
5010
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005011 htx = htx_from_buf(&req->buf);
5012 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005013 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005014
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005015 while (count && !stop && blk) {
5016 enum htx_blk_type type = htx_get_blk_type(blk);
5017 uint32_t sz = htx_get_blksz(blk);
5018 struct ist v;
5019 uint32_t vlen;
5020 char *nl;
5021
5022 vlen = sz;
5023 if (vlen > count) {
5024 if (type != HTX_BLK_DATA)
5025 break;
5026 vlen = count;
5027 }
5028
5029 switch (type) {
5030 case HTX_BLK_UNUSED:
5031 break;
5032
5033 case HTX_BLK_DATA:
5034 v = htx_get_blk_value(htx, blk);
5035 v.len = vlen;
5036 nl = istchr(v, '\n');
5037 if (nl != NULL) {
5038 stop = 1;
5039 vlen = nl - v.ptr + 1;
5040 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005041 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005042 break;
5043
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005044 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005045 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005046 stop = 1;
5047 break;
5048
5049 default:
5050 break;
5051 }
5052
Willy Tarreau84240042022-02-28 16:51:23 +01005053 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054 count -= vlen;
5055 if (sz == vlen)
5056 blk = htx_remove_blk(htx, blk);
5057 else {
5058 htx_cut_data_blk(htx, blk, vlen);
5059 break;
5060 }
5061 }
5062
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005063 /* The message was fully consumed and no more data are expected
5064 * (EOM flag set).
5065 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005066 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005067 stop = 1;
5068
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005069 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005070 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005071 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005072 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005073 }
5074
5075 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005076 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005077 return 1;
5078}
5079
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005080
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005081/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005082__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005083{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005084 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005085
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005086 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005087 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005088
Christopher Fauleta2097962019-07-15 16:25:33 +02005089 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005090}
5091
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005092/* If expected data not yet available, it returns a yield. This function
5093 * consumes the data in the buffer. It returns a string containing the
5094 * data. This string can be empty.
5095 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005096__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005097{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005098 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005099 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005100 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005101 struct htx *htx;
5102 struct htx_blk *blk;
5103 size_t count;
5104 int len;
5105
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005106 htx = htx_from_buf(&req->buf);
5107 len = MAY_LJMP(luaL_checkinteger(L, 2));
5108 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005109 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005110 while (count && len && blk) {
5111 enum htx_blk_type type = htx_get_blk_type(blk);
5112 uint32_t sz = htx_get_blksz(blk);
5113 struct ist v;
5114 uint32_t vlen;
5115
5116 vlen = sz;
5117 if (len > 0 && vlen > len)
5118 vlen = len;
5119 if (vlen > count) {
5120 if (type != HTX_BLK_DATA)
5121 break;
5122 vlen = count;
5123 }
5124
5125 switch (type) {
5126 case HTX_BLK_UNUSED:
5127 break;
5128
5129 case HTX_BLK_DATA:
5130 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005131 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005132 break;
5133
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005134 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005135 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005136 len = 0;
5137 break;
5138
5139 default:
5140 break;
5141 }
5142
Willy Tarreau84240042022-02-28 16:51:23 +01005143 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005144 count -= vlen;
5145 if (len > 0)
5146 len -= vlen;
5147 if (sz == vlen)
5148 blk = htx_remove_blk(htx, blk);
5149 else {
5150 htx_cut_data_blk(htx, blk, vlen);
5151 break;
5152 }
5153 }
5154
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005155 /* The message was fully consumed and no more data are expected
5156 * (EOM flag set).
5157 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005158 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005159 len = 0;
5160
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005161 htx_to_buf(htx, &req->buf);
5162
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005163 /* If we are no other data available, yield waiting for new data. */
5164 if (len) {
5165 if (len > 0) {
5166 lua_pushinteger(L, len);
5167 lua_replace(L, 2);
5168 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005169 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005170 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005171 }
5172
5173 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005174 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005175 return 1;
5176}
5177
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005178/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005179__LJMP static int hlua_applet_http_recv(lua_State *L)
5180{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005181 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005182 int len = -1;
5183
5184 /* Check arguments. */
5185 if (lua_gettop(L) > 2)
5186 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5187 if (lua_gettop(L) >= 2) {
5188 len = MAY_LJMP(luaL_checkinteger(L, 2));
5189 lua_pop(L, 1);
5190 }
5191
Christopher Fauleta2097962019-07-15 16:25:33 +02005192 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005193
Christopher Fauleta2097962019-07-15 16:25:33 +02005194 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005195 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005196
Christopher Fauleta2097962019-07-15 16:25:33 +02005197 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005198}
5199
5200/* Append data in the output side of the buffer. This data is immediately
5201 * sent. The function returns the amount of data written. If the buffer
5202 * cannot contain the data, the function yields. The function returns -1
5203 * if the channel is closed.
5204 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005205__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005206{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005207 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005208 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005209 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005210 struct htx *htx = htx_from_buf(&res->buf);
5211 const char *data;
5212 size_t len;
5213 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5214 int max;
5215
Christopher Faulet9060fc02019-07-03 11:39:30 +02005216 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005217 if (!max)
5218 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005219
5220 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5221
5222 /* Get the max amount of data which can write as input in the channel. */
5223 if (max > (len - l))
5224 max = len - l;
5225
5226 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005227 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005228 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005229
5230 /* update counters. */
5231 l += max;
5232 lua_pop(L, 1);
5233 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005234
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005235 /* If some data is not send, declares the situation to the
5236 * applet, and returns a yield.
5237 */
5238 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005239 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005240 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005241 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005242 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005243 }
5244
Christopher Fauleta2097962019-07-15 16:25:33 +02005245 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005246 return 1;
5247}
5248
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005249/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005250 * yield the LUA process, and resume it without checking the
5251 * input arguments.
5252 */
5253__LJMP static int hlua_applet_http_send(lua_State *L)
5254{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005255 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005256 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005257
5258 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005259 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005260 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5261 WILL_LJMP(lua_error(L));
5262 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005263
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005264 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005265 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005266
Christopher Fauleta2097962019-07-15 16:25:33 +02005267 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268}
5269
5270__LJMP static int hlua_applet_http_addheader(lua_State *L)
5271{
5272 const char *name;
5273 int ret;
5274
5275 MAY_LJMP(hlua_checkapplet_http(L, 1));
5276 name = MAY_LJMP(luaL_checkstring(L, 2));
5277 MAY_LJMP(luaL_checkstring(L, 3));
5278
5279 /* Push in the stack the "response" entry. */
5280 ret = lua_getfield(L, 1, "response");
5281 if (ret != LUA_TTABLE) {
5282 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5283 "is expected as an array. %s found", lua_typename(L, ret));
5284 WILL_LJMP(lua_error(L));
5285 }
5286
5287 /* check if the header is already registered if it is not
5288 * the case, register it.
5289 */
5290 ret = lua_getfield(L, -1, name);
5291 if (ret == LUA_TNIL) {
5292
5293 /* Entry not found. */
5294 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5295
5296 /* Insert the new header name in the array in the top of the stack.
5297 * It left the new array in the top of the stack.
5298 */
5299 lua_newtable(L);
5300 lua_pushvalue(L, 2);
5301 lua_pushvalue(L, -2);
5302 lua_settable(L, -4);
5303
5304 } else if (ret != LUA_TTABLE) {
5305
5306 /* corruption error. */
5307 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5308 "is expected as an array. %s found", name, lua_typename(L, ret));
5309 WILL_LJMP(lua_error(L));
5310 }
5311
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005312 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005313 * the header value as new entry.
5314 */
5315 lua_pushvalue(L, 3);
5316 ret = lua_rawlen(L, -2);
5317 lua_rawseti(L, -2, ret + 1);
5318 lua_pushboolean(L, 1);
5319 return 1;
5320}
5321
5322__LJMP static int hlua_applet_http_status(lua_State *L)
5323{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005324 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005325 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005326 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005327 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005328
5329 if (status < 100 || status > 599) {
5330 lua_pushboolean(L, 0);
5331 return 1;
5332 }
5333
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005334 http_ctx->status = status;
5335 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005336 lua_pushboolean(L, 1);
5337 return 1;
5338}
5339
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005340
Christopher Fauleta2097962019-07-15 16:25:33 +02005341__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005343 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005344 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005345 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005346 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005347 struct htx *htx;
5348 struct htx_sl *sl;
5349 struct h1m h1m;
5350 const char *status, *reason;
5351 const char *name, *value;
5352 size_t nlen, vlen;
5353 unsigned int flags;
5354
5355 /* Send the message at once. */
5356 htx = htx_from_buf(&res->buf);
5357 h1m_init_res(&h1m);
5358
5359 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005360 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5361 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005362 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005363 reason = http_get_reason(http_ctx->status);
5364 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005365 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5366 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5367 }
5368 else {
5369 flags = HTX_SL_F_IS_RESP;
5370 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5371 }
5372 if (!sl) {
5373 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005374 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005375 WILL_LJMP(lua_error(L));
5376 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005377 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005378
5379 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5381 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005382 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005383 WILL_LJMP(lua_error(L));
5384 }
5385
5386 /* Browse the list of headers. */
5387 lua_pushnil(L);
5388 while(lua_next(L, -2) != 0) {
5389 /* We expect a string as -2. */
5390 if (lua_type(L, -2) != LUA_TSTRING) {
5391 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\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 lua_typename(L, lua_type(L, -2)));
5394 WILL_LJMP(lua_error(L));
5395 }
5396 name = lua_tolstring(L, -2, &nlen);
5397
5398 /* We expect an array as -1. */
5399 if (lua_type(L, -1) != LUA_TTABLE) {
5400 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 +02005401 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005402 name,
5403 lua_typename(L, lua_type(L, -1)));
5404 WILL_LJMP(lua_error(L));
5405 }
5406
5407 /* Browse the table who is on the top of the stack. */
5408 lua_pushnil(L);
5409 while(lua_next(L, -2) != 0) {
5410 int id;
5411
5412 /* We expect a number as -2. */
5413 if (lua_type(L, -2) != LUA_TNUMBER) {
5414 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 +02005415 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005416 name,
5417 lua_typename(L, lua_type(L, -2)));
5418 WILL_LJMP(lua_error(L));
5419 }
5420 id = lua_tointeger(L, -2);
5421
5422 /* We expect a string as -2. */
5423 if (lua_type(L, -1) != LUA_TSTRING) {
5424 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 +02005425 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005426 name, id,
5427 lua_typename(L, lua_type(L, -1)));
5428 WILL_LJMP(lua_error(L));
5429 }
5430 value = lua_tolstring(L, -1, &vlen);
5431
5432 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005433 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5434 int ret;
5435
5436 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5437 if (ret < 0) {
5438 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5439 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5440 name);
5441 WILL_LJMP(lua_error(L));
5442 }
5443 else if (ret == 0)
5444 goto next; /* Skip it */
5445 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005446 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5447 struct ist v = ist2(value, vlen);
5448 int ret;
5449
5450 ret = h1_parse_cont_len_header(&h1m, &v);
5451 if (ret < 0) {
5452 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005453 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005454 name);
5455 WILL_LJMP(lua_error(L));
5456 }
5457 else if (ret == 0)
5458 goto next; /* Skip it */
5459 }
5460
5461 /* Add a new header */
5462 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5463 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005464 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005465 name);
5466 WILL_LJMP(lua_error(L));
5467 }
5468 next:
5469 /* Remove the array from the stack, and get next element with a remaining string. */
5470 lua_pop(L, 1);
5471 }
5472
5473 /* Remove the array from the stack, and get next element with a remaining string. */
5474 lua_pop(L, 1);
5475 }
5476
5477 if (h1m.flags & H1_MF_CHNK)
5478 h1m.flags &= ~H1_MF_CLEN;
5479 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5480 h1m.flags |= H1_MF_XFER_LEN;
5481
5482 /* Uset HTX start-line flags */
5483 if (h1m.flags & H1_MF_XFER_ENC)
5484 flags |= HTX_SL_F_XFER_ENC;
5485 if (h1m.flags & H1_MF_XFER_LEN) {
5486 flags |= HTX_SL_F_XFER_LEN;
5487 if (h1m.flags & H1_MF_CHNK)
5488 flags |= HTX_SL_F_CHNK;
5489 else if (h1m.flags & H1_MF_CLEN)
5490 flags |= HTX_SL_F_CLEN;
5491 if (h1m.body_len == 0)
5492 flags |= HTX_SL_F_BODYLESS;
5493 }
5494 sl->flags |= flags;
5495
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005496 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005497 * and the status code implies the presence of a message body, we must
5498 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005499 * for the keepalive compliance. If the applet announces a transfer-encoding
5500 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005501 */
5502 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005503 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005504 /* Add a new header */
5505 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5506 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5507 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005508 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005509 WILL_LJMP(lua_error(L));
5510 }
5511 }
5512
5513 /* Finalize headers. */
5514 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5515 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005516 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005517 WILL_LJMP(lua_error(L));
5518 }
5519
5520 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5521 b_reset(&res->buf);
5522 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5523 WILL_LJMP(lua_error(L));
5524 }
5525
5526 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005527 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005528
5529 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005530 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005531 return 0;
5532
5533}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005534/* We will build the status line and the headers of the HTTP response.
5535 * We will try send at once if its not possible, we give back the hand
5536 * waiting for more room.
5537 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005538__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005539{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005540 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005541 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005542 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005543
5544 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005545 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005546 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005547 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005548 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005549}
5550
5551
Christopher Fauleta2097962019-07-15 16:25:33 +02005552__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005553{
Christopher Fauleta2097962019-07-15 16:25:33 +02005554 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005555}
5556
Christopher Fauleta2097962019-07-15 16:25:33 +02005557/*
5558 *
5559 *
5560 * Class HTTP
5561 *
5562 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005563 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005564
5565/* Returns a struct hlua_txn if the stack entry "ud" is
5566 * a class stream, otherwise it throws an error.
5567 */
5568__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005569{
Christopher Fauleta2097962019-07-15 16:25:33 +02005570 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5571}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005572
Christopher Fauleta2097962019-07-15 16:25:33 +02005573/* This function creates and push in the stack a HTTP object
5574 * according with a current TXN.
5575 */
5576static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5577{
5578 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005579
Christopher Fauleta2097962019-07-15 16:25:33 +02005580 /* Check stack size. */
5581 if (!lua_checkstack(L, 3))
5582 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005583
Christopher Fauleta2097962019-07-15 16:25:33 +02005584 /* Create the object: obj[0] = userdata.
5585 * Note that the base of the Converters object is the
5586 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005587 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005588 lua_newtable(L);
5589 htxn = lua_newuserdata(L, sizeof(*htxn));
5590 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005591
5592 htxn->s = txn->s;
5593 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005594 htxn->dir = txn->dir;
5595 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005596
5597 /* Pop a class stream metatable and affect it to the table. */
5598 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5599 lua_setmetatable(L, -2);
5600
5601 return 1;
5602}
5603
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005604/* This function creates and returns an array containing the status-line
5605 * elements. This function does not fails.
5606 */
5607__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5608{
5609 /* Create the table. */
5610 lua_newtable(L);
5611
5612 if (sl->flags & HTX_SL_F_IS_RESP) {
5613 lua_pushstring(L, "version");
5614 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5615 lua_settable(L, -3);
5616 lua_pushstring(L, "code");
5617 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5618 lua_settable(L, -3);
5619 lua_pushstring(L, "reason");
5620 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5621 lua_settable(L, -3);
5622 }
5623 else {
5624 lua_pushstring(L, "method");
5625 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5626 lua_settable(L, -3);
5627 lua_pushstring(L, "uri");
5628 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5629 lua_settable(L, -3);
5630 lua_pushstring(L, "version");
5631 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5632 lua_settable(L, -3);
5633 }
5634 return 1;
5635}
5636
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005637/* This function creates ans returns an array of HTTP headers.
5638 * This function does not fails. It is used as wrapper with the
5639 * 2 following functions.
5640 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005641__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005642{
Christopher Fauleta2097962019-07-15 16:25:33 +02005643 struct htx *htx;
5644 int32_t pos;
5645
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005646 /* Create the table. */
5647 lua_newtable(L);
5648
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005649
Christopher Fauleta2097962019-07-15 16:25:33 +02005650 htx = htxbuf(&msg->chn->buf);
5651 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5652 struct htx_blk *blk = htx_get_blk(htx, pos);
5653 enum htx_blk_type type = htx_get_blk_type(blk);
5654 struct ist n, v;
5655 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005656
Christopher Fauleta2097962019-07-15 16:25:33 +02005657 if (type == HTX_BLK_HDR) {
5658 n = htx_get_blk_name(htx,blk);
5659 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005660 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005661 else if (type == HTX_BLK_EOH)
5662 break;
5663 else
5664 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005665
Christopher Fauleta2097962019-07-15 16:25:33 +02005666 /* Check for existing entry:
5667 * assume that the table is on the top of the stack, and
5668 * push the key in the stack, the function lua_gettable()
5669 * perform the lookup.
5670 */
5671 lua_pushlstring(L, n.ptr, n.len);
5672 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005673
Christopher Fauleta2097962019-07-15 16:25:33 +02005674 switch (lua_type(L, -1)) {
5675 case LUA_TNIL:
5676 /* Table not found, create it. */
5677 lua_pop(L, 1); /* remove the nil value. */
5678 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5679 lua_newtable(L); /* create and push empty table. */
5680 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5681 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5682 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005683 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005684
Christopher Fauleta2097962019-07-15 16:25:33 +02005685 case LUA_TTABLE:
5686 /* Entry found: push the value in the table. */
5687 len = lua_rawlen(L, -1);
5688 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5689 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5690 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5691 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005692
Christopher Fauleta2097962019-07-15 16:25:33 +02005693 default:
5694 /* Other cases are errors. */
5695 hlua_pusherror(L, "internal error during the parsing of headers.");
5696 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005697 }
5698 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005699 return 1;
5700}
5701
5702__LJMP static int hlua_http_req_get_headers(lua_State *L)
5703{
5704 struct hlua_txn *htxn;
5705
5706 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5707 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5708
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005709 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005710 WILL_LJMP(lua_error(L));
5711
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005712 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005713}
5714
5715__LJMP static int hlua_http_res_get_headers(lua_State *L)
5716{
5717 struct hlua_txn *htxn;
5718
5719 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5720 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5721
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005722 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005723 WILL_LJMP(lua_error(L));
5724
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005725 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005726}
5727
5728/* This function replace full header, or just a value in
5729 * the request or in the response. It is a wrapper fir the
5730 * 4 following functions.
5731 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005732__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005733{
5734 size_t name_len;
5735 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5736 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5737 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005738 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005739 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005740
Dragan Dosen26743032019-04-30 15:54:36 +02005741 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005742 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5743
Christopher Fauleta2097962019-07-15 16:25:33 +02005744 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005745 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005746 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005747 return 0;
5748}
5749
5750__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5751{
5752 struct hlua_txn *htxn;
5753
5754 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5755 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5756
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005757 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005758 WILL_LJMP(lua_error(L));
5759
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005760 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005761}
5762
5763__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5764{
5765 struct hlua_txn *htxn;
5766
5767 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5768 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5769
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005770 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005771 WILL_LJMP(lua_error(L));
5772
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005773 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005774}
5775
5776__LJMP static int hlua_http_req_rep_val(lua_State *L)
5777{
5778 struct hlua_txn *htxn;
5779
5780 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5781 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5782
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005783 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005784 WILL_LJMP(lua_error(L));
5785
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005786 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005787}
5788
5789__LJMP static int hlua_http_res_rep_val(lua_State *L)
5790{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005791 struct hlua_txn *htxn;
5792
5793 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5794 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5795
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005796 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005797 WILL_LJMP(lua_error(L));
5798
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005799 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005800}
5801
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005802/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005803 * It is a wrapper for the 2 following functions.
5804 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005805__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005806{
5807 size_t len;
5808 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005809 struct htx *htx = htxbuf(&msg->chn->buf);
5810 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005811
Christopher Fauleta2097962019-07-15 16:25:33 +02005812 ctx.blk = NULL;
5813 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5814 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005815 return 0;
5816}
5817
5818__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5819{
5820 struct hlua_txn *htxn;
5821
5822 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5823 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5824
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005825 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005826 WILL_LJMP(lua_error(L));
5827
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005828 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005829}
5830
5831__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5832{
5833 struct hlua_txn *htxn;
5834
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005835 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005836 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5837
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005838 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005839 WILL_LJMP(lua_error(L));
5840
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005841 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005842}
5843
5844/* This function adds an header. It is a wrapper used by
5845 * the 2 following functions.
5846 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005847__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005848{
5849 size_t name_len;
5850 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5851 size_t value_len;
5852 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005853 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005854
Christopher Fauleta2097962019-07-15 16:25:33 +02005855 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5856 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005857 return 0;
5858}
5859
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005860__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5861{
5862 struct hlua_txn *htxn;
5863
5864 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5865 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5866
5867 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5868 WILL_LJMP(lua_error(L));
5869
5870 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5871}
5872
5873__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5874{
5875 struct hlua_txn *htxn;
5876
5877 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5878 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5879
5880 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5881 WILL_LJMP(lua_error(L));
5882
5883 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5884}
5885
5886static int hlua_http_req_set_hdr(lua_State *L)
5887{
5888 struct hlua_txn *htxn;
5889
5890 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5891 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5892
5893 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5894 WILL_LJMP(lua_error(L));
5895
5896 hlua_http_del_hdr(L, &htxn->s->txn->req);
5897 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5898}
5899
5900static int hlua_http_res_set_hdr(lua_State *L)
5901{
5902 struct hlua_txn *htxn;
5903
5904 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5905 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5906
5907 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5908 WILL_LJMP(lua_error(L));
5909
5910 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5911 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5912}
5913
5914/* This function set the method. */
5915static int hlua_http_req_set_meth(lua_State *L)
5916{
5917 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5918 size_t name_len;
5919 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5920
5921 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5922 WILL_LJMP(lua_error(L));
5923
5924 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5925 return 1;
5926}
5927
5928/* This function set the method. */
5929static int hlua_http_req_set_path(lua_State *L)
5930{
5931 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5932 size_t name_len;
5933 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5934
5935 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5936 WILL_LJMP(lua_error(L));
5937
5938 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5939 return 1;
5940}
5941
5942/* This function set the query-string. */
5943static int hlua_http_req_set_query(lua_State *L)
5944{
5945 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5946 size_t name_len;
5947 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5948
5949 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5950 WILL_LJMP(lua_error(L));
5951
5952 /* Check length. */
5953 if (name_len > trash.size - 1) {
5954 lua_pushboolean(L, 0);
5955 return 1;
5956 }
5957
5958 /* Add the mark question as prefix. */
5959 chunk_reset(&trash);
5960 trash.area[trash.data++] = '?';
5961 memcpy(trash.area + trash.data, name, name_len);
5962 trash.data += name_len;
5963
5964 lua_pushboolean(L,
5965 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5966 return 1;
5967}
5968
5969/* This function set the uri. */
5970static int hlua_http_req_set_uri(lua_State *L)
5971{
5972 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5973 size_t name_len;
5974 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5975
5976 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5977 WILL_LJMP(lua_error(L));
5978
5979 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5980 return 1;
5981}
5982
5983/* This function set the response code & optionally reason. */
5984static int hlua_http_res_set_status(lua_State *L)
5985{
5986 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5987 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5988 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5989 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5990
5991 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5992 WILL_LJMP(lua_error(L));
5993
5994 http_res_set_status(code, reason, htxn->s);
5995 return 0;
5996}
5997
5998/*
5999 *
6000 *
6001 * Class HTTPMessage
6002 *
6003 *
6004 */
6005
6006/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6007 * otherwise it throws an error.
6008 */
6009__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6010{
6011 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6012}
6013
6014/* Creates and pushes on the stack a HTTP object according with a current TXN.
6015 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006016static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006017{
6018 /* Check stack size. */
6019 if (!lua_checkstack(L, 3))
6020 return 0;
6021
6022 lua_newtable(L);
6023 lua_pushlightuserdata(L, msg);
6024 lua_rawseti(L, -2, 0);
6025
6026 /* Create the "channel" field that contains the request channel object. */
6027 lua_pushstring(L, "channel");
6028 if (!hlua_channel_new(L, msg->chn))
6029 return 0;
6030 lua_rawset(L, -3);
6031
6032 /* Pop a class stream metatable and affect it to the table. */
6033 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6034 lua_setmetatable(L, -2);
6035
6036 return 1;
6037}
6038
6039/* Helper function returning a filter attached to the HTTP message at the
6040 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006041 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006042 * filled with output and input length respectively.
6043 */
6044static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6045{
6046 struct channel *chn = msg->chn;
6047 struct htx *htx = htxbuf(&chn->buf);
6048 struct filter *filter = NULL;
6049
6050 *offset = co_data(msg->chn);
6051 *len = htx->data - co_data(msg->chn);
6052
6053 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6054 filter = lua_touserdata (L, -1);
6055 if (msg->msg_state >= HTTP_MSG_DATA) {
6056 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6057
6058 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6059 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6060 }
6061 }
6062
6063 lua_pop(L, 1);
6064 return filter;
6065}
6066
6067/* Returns true if the channel attached to the HTTP message is the response
6068 * channel.
6069 */
6070__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6071{
6072 struct http_msg *msg;
6073
6074 MAY_LJMP(check_args(L, 1, "is_resp"));
6075 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6076
6077 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6078 return 1;
6079}
6080
6081/* Returns an array containing the elements status-line of the HTTP message. It relies
6082 * on hlua_http_get_stline().
6083 */
6084__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6085{
6086 struct http_msg *msg;
6087 struct htx *htx;
6088 struct htx_sl *sl;
6089
6090 MAY_LJMP(check_args(L, 1, "get_stline"));
6091 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6092
6093 if (msg->msg_state > HTTP_MSG_BODY)
6094 WILL_LJMP(lua_error(L));
6095
6096 htx = htxbuf(&msg->chn->buf);
6097 sl = http_get_stline(htx);
6098 if (!sl)
6099 return 0;
6100 return hlua_http_get_stline(L, sl);
6101}
6102
6103/* Returns an array containing all headers of the HTTP message. it relies on
6104 * hlua_http_get_headers().
6105 */
6106__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6107{
6108 struct http_msg *msg;
6109
6110 MAY_LJMP(check_args(L, 1, "get_headers"));
6111 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6112
6113 if (msg->msg_state > HTTP_MSG_BODY)
6114 WILL_LJMP(lua_error(L));
6115
6116 return hlua_http_get_headers(L, msg);
6117}
6118
6119/* Deletes all occurrences of an header in the HTTP message matching on its
6120 * name. It relies on hlua_http_del_hdr().
6121 */
6122__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6123{
6124 struct http_msg *msg;
6125
6126 MAY_LJMP(check_args(L, 2, "del_header"));
6127 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6128
6129 if (msg->msg_state > HTTP_MSG_BODY)
6130 WILL_LJMP(lua_error(L));
6131
6132 return hlua_http_del_hdr(L, msg);
6133}
6134
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006135/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006136 * message given its name against a regex and replaces it if it matches. It
6137 * relies on hlua_http_rep_hdr().
6138 */
6139__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6140{
6141 struct http_msg *msg;
6142
6143 MAY_LJMP(check_args(L, 4, "rep_header"));
6144 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6145
6146 if (msg->msg_state > HTTP_MSG_BODY)
6147 WILL_LJMP(lua_error(L));
6148
6149 return hlua_http_rep_hdr(L, msg, 1);
6150}
6151
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006152/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006153 * message given its name against a regex and replaces it if it matches. It
6154 * relies on hlua_http_rep_hdr().
6155 */
6156__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6157{
6158 struct http_msg *msg;
6159
6160 MAY_LJMP(check_args(L, 4, "rep_value"));
6161 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6162
6163 if (msg->msg_state > HTTP_MSG_BODY)
6164 WILL_LJMP(lua_error(L));
6165
6166 return hlua_http_rep_hdr(L, msg, 0);
6167}
6168
6169/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6170__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6171{
6172 struct http_msg *msg;
6173
6174 MAY_LJMP(check_args(L, 3, "add_header"));
6175 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6176
6177 if (msg->msg_state > HTTP_MSG_BODY)
6178 WILL_LJMP(lua_error(L));
6179
6180 return hlua_http_add_hdr(L, msg);
6181}
6182
6183/* Add an header in the HTTP message removing existing headers with the same
6184 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6185 */
6186__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6187{
6188 struct http_msg *msg;
6189
6190 MAY_LJMP(check_args(L, 3, "set_header"));
6191 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6192
6193 if (msg->msg_state > HTTP_MSG_BODY)
6194 WILL_LJMP(lua_error(L));
6195
6196 hlua_http_del_hdr(L, msg);
6197 return hlua_http_add_hdr(L, msg);
6198}
6199
6200/* Rewrites the request method. It relies on http_req_replace_stline(). */
6201__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6202{
6203 struct stream *s;
6204 struct http_msg *msg;
6205 const char *name;
6206 size_t name_len;
6207
6208 MAY_LJMP(check_args(L, 2, "set_method"));
6209 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6210 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6211
6212 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6213 WILL_LJMP(lua_error(L));
6214
6215 s = chn_strm(msg->chn);
6216 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6217 return 1;
6218}
6219
6220/* Rewrites the request path. It relies on http_req_replace_stline(). */
6221__LJMP static int hlua_http_msg_set_path(lua_State *L)
6222{
6223 struct stream *s;
6224 struct http_msg *msg;
6225 const char *name;
6226 size_t name_len;
6227
6228 MAY_LJMP(check_args(L, 2, "set_path"));
6229 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6230 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6231
6232 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6233 WILL_LJMP(lua_error(L));
6234
6235 s = chn_strm(msg->chn);
6236 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6237 return 1;
6238}
6239
6240/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6241__LJMP static int hlua_http_msg_set_query(lua_State *L)
6242{
6243 struct stream *s;
6244 struct http_msg *msg;
6245 const char *name;
6246 size_t name_len;
6247
6248 MAY_LJMP(check_args(L, 2, "set_query"));
6249 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6250 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6251
6252 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6253 WILL_LJMP(lua_error(L));
6254
6255 /* Check length. */
6256 if (name_len > trash.size - 1) {
6257 lua_pushboolean(L, 0);
6258 return 1;
6259 }
6260
6261 /* Add the mark question as prefix. */
6262 chunk_reset(&trash);
6263 trash.area[trash.data++] = '?';
6264 memcpy(trash.area + trash.data, name, name_len);
6265 trash.data += name_len;
6266
6267 s = chn_strm(msg->chn);
6268 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6269 return 1;
6270}
6271
6272/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6273__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6274{
6275 struct stream *s;
6276 struct http_msg *msg;
6277 const char *name;
6278 size_t name_len;
6279
6280 MAY_LJMP(check_args(L, 2, "set_uri"));
6281 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6282 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6283
6284 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6285 WILL_LJMP(lua_error(L));
6286
6287 s = chn_strm(msg->chn);
6288 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6289 return 1;
6290}
6291
6292/* Rewrites the response status code. It relies on http_res_set_status(). */
6293__LJMP static int hlua_http_msg_set_status(lua_State *L)
6294{
6295 struct http_msg *msg;
6296 unsigned int code;
6297 const char *reason;
6298 size_t reason_len;
6299
6300 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6301 code = MAY_LJMP(luaL_checkinteger(L, 2));
6302 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6303
6304 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6305 WILL_LJMP(lua_error(L));
6306
6307 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6308 return 1;
6309}
6310
6311/* Returns true if the HTTP message is full. */
6312__LJMP static int hlua_http_msg_is_full(lua_State *L)
6313{
6314 struct http_msg *msg;
6315
6316 MAY_LJMP(check_args(L, 1, "is_full"));
6317 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6318 lua_pushboolean(L, channel_full(msg->chn, 0));
6319 return 1;
6320}
6321
6322/* Returns true if the HTTP message may still receive data. */
6323__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6324{
6325 struct http_msg *msg;
6326 struct htx *htx;
6327
6328 MAY_LJMP(check_args(L, 1, "may_recv"));
6329 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6330 htx = htxbuf(&msg->chn->buf);
6331 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6332 return 1;
6333}
6334
6335/* Returns true if the HTTP message EOM was received */
6336__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6337{
6338 struct http_msg *msg;
6339 struct htx *htx;
6340
6341 MAY_LJMP(check_args(L, 1, "may_recv"));
6342 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6343 htx = htxbuf(&msg->chn->buf);
6344 lua_pushboolean(L, !htx_expect_more(htx));
6345 return 1;
6346}
6347
6348/* Returns the number of bytes available in the input side of the HTTP
6349 * message. This function never fails.
6350 */
6351__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6352{
6353 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006354 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006355
6356 MAY_LJMP(check_args(L, 1, "input"));
6357 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006358 hlua_http_msg_filter(L, 1, msg, &output, &input);
6359 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006360 return 1;
6361}
6362
6363/* Returns the number of bytes available in the output side of the HTTP
6364 * message. This function never fails.
6365 */
6366__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6367{
6368 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006369 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006370
6371 MAY_LJMP(check_args(L, 1, "output"));
6372 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006373 hlua_http_msg_filter(L, 1, msg, &output, &input);
6374 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006375 return 1;
6376}
6377
6378/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6379 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006380 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006381 * block. This function is called during the payload filtering, so the headers
6382 * are already scheduled for output (from the filter point of view).
6383 */
6384static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6385{
6386 struct htx *htx = htxbuf(&msg->chn->buf);
6387 struct htx_blk *blk;
6388 struct htx_ret htxret;
6389 luaL_Buffer b;
6390 int ret = 0;
6391
6392 luaL_buffinit(L, &b);
6393 htxret = htx_find_offset(htx, offset);
6394 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6395 enum htx_blk_type type = htx_get_blk_type(blk);
6396 struct ist v;
6397
6398 switch (type) {
6399 case HTX_BLK_UNUSED:
6400 break;
6401
6402 case HTX_BLK_DATA:
6403 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006404 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006405 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006406
6407 luaL_addlstring(&b, v.ptr, v.len);
6408 ret += v.len;
6409 break;
6410
6411 default:
vishnu0af4bd72021-10-24 06:46:24 +05306412 if (!ret)
6413 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006414 goto end;
6415 }
6416 offset = 0;
6417 }
6418
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006419end:
vishnu0af4bd72021-10-24 06:46:24 +05306420 if (!ret && (htx->flags & HTX_FL_EOM))
6421 goto no_data;
6422 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006423 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306424
6425 no_data:
6426 /* Remove the empty string and push nil on the stack */
6427 lua_pop(L, 1);
6428 lua_pushnil(L);
6429 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006430}
6431
6432/* Copies the string <str> to the HTTP message <msg> at the offset
6433 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006434 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006435 * the filter context.
6436 */
6437static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6438{
6439 struct htx *htx = htx_from_buf(&msg->chn->buf);
6440 struct htx_ret htxret;
6441 int /*max, */ret = 0;
6442
6443 /* Nothing to do, just return */
6444 if (unlikely(istlen(str) == 0))
6445 goto end;
6446
6447 if (istlen(str) > htx_free_data_space(htx)) {
6448 ret = -1;
6449 goto end;
6450 }
6451
6452 htxret = htx_find_offset(htx, offset);
6453 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6454 if (!htx_add_last_data(htx, str))
6455 goto end;
6456 }
6457 else {
6458 struct ist v = htx_get_blk_value(htx, htxret.blk);
6459 v.ptr += htxret.ret;
6460 v.len = 0;
6461 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6462 goto end;
6463 }
6464 ret = str.len;
6465 if (ret) {
6466 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6467 flt_update_offsets(filter, msg->chn, ret);
6468 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6469 }
6470
6471 end:
6472 htx_to_buf(htx, &msg->chn->buf);
6473 return ret;
6474}
6475
6476/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6477 * position <offset>. It stops on the first non-DATA HTX block. This function is
6478 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006479 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006480 * update the filter context.
6481 */
6482static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6483{
6484 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6485 struct htx *htx = htx_from_buf(&msg->chn->buf);
6486 struct htx_blk *blk;
6487 struct htx_ret htxret;
6488 size_t ret = 0;
6489
6490 /* Be sure <len> is always the amount of DATA to remove */
6491 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006492 /* When htx tail type == HTX_BLK_DATA, no need to take care
6493 * of special blocks like HTX_BLK_EOT.
6494 * We simply truncate after offset
6495 * (truncate targeted blk and discard the following ones)
6496 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006497 htx_truncate(htx, offset);
6498 ret = len;
6499 goto end;
6500 }
6501
6502 htxret = htx_find_offset(htx, offset);
6503 blk = htxret.blk;
6504 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006505 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006506 struct ist v;
6507
6508 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6509 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006510
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006511 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006512 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006513
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006514 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006515 /* trimming data in blk: discard everything after the offset
6516 * (replace 'v' with 'IST_NULL')
6517 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006518 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006519 if (blk && v.len < len) {
6520 /* In this case, caller wants to keep removing data,
6521 * but we need to spare current blk
6522 * because it was already trimmed
6523 */
6524 blk = htx_get_next_blk(htx, blk);
6525 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006526 len -= v.len;
6527 ret += v.len;
6528 }
6529
6530
6531 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006532 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006533 enum htx_blk_type type = htx_get_blk_type(blk);
6534 uint32_t sz = htx_get_blksz(blk);
6535
6536 switch (type) {
6537 case HTX_BLK_UNUSED:
6538 break;
6539
6540 case HTX_BLK_DATA:
6541 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006542 /* don't discard whole blk, only part of it
6543 * (from the beginning)
6544 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006545 htx_cut_data_blk(htx, blk, len);
6546 ret += len;
6547 goto end;
6548 }
6549 break;
6550
6551 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006552 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006553 goto end;
6554 }
6555
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006556 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006557 len -= sz;
6558 ret += sz;
6559 blk = htx_remove_blk(htx, blk);
6560 }
6561
6562end:
6563 flt_update_offsets(filter, msg->chn, -ret);
6564 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6565 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6566 * to loose the EOM flag if the message is empty.
6567 */
6568}
6569
6570/* Copies input data found in an HTTP message. Unlike the channel function used
6571 * to duplicate raw data, this one can only be called inside a filter, from
6572 * http_payload callback. So it cannot yield. An exception is returned if it is
6573 * called from another callback. If nothing was copied, a nil value is pushed on
6574 * the stack.
6575 */
6576__LJMP static int hlua_http_msg_get_body(lua_State *L)
6577{
6578 struct http_msg *msg;
6579 struct filter *filter;
6580 size_t output, input;
6581 int offset, len;
6582
6583 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6584 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6585 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6586
6587 if (msg->msg_state < HTTP_MSG_DATA)
6588 WILL_LJMP(lua_error(L));
6589
6590 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6591 if (!filter || !hlua_filter_from_payload(filter))
6592 WILL_LJMP(lua_error(L));
6593
6594 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6595 lua_pushnil(L);
6596 return 1;
6597 }
6598
6599 offset = output;
6600 if (lua_gettop(L) > 1) {
6601 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6602 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006603 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006604 offset += output;
6605 if (offset < output || offset > input + output) {
6606 lua_pushfstring(L, "offset out of range.");
6607 WILL_LJMP(lua_error(L));
6608 }
6609 }
6610 len = output + input - offset;
6611 if (lua_gettop(L) == 3) {
6612 len = MAY_LJMP(luaL_checkinteger(L, 3));
6613 if (!len)
6614 goto dup;
6615 if (len == -1)
6616 len = global.tune.bufsize;
6617 if (len < 0) {
6618 lua_pushfstring(L, "length out of range.");
6619 WILL_LJMP(lua_error(L));
6620 }
6621 }
6622
6623 dup:
6624 _hlua_http_msg_dup(msg, L, offset, len);
6625 return 1;
6626}
6627
6628/* Appends a string to the HTTP message, after all existing DATA blocks but
6629 * before the trailers, if any. It returns the amount of data written or -1 if
6630 * nothing was copied. Unlike the channel function used to append data, this one
6631 * can only be called inside a filter, from http_payload callback. So it cannot
6632 * yield. An exception is returned if it is called from another callback.
6633 */
6634__LJMP static int hlua_http_msg_append(lua_State *L)
6635{
6636 struct http_msg *msg;
6637 struct filter *filter;
6638 const char *str;
6639 size_t offset, len, sz;
6640 int ret;
6641
6642 MAY_LJMP(check_args(L, 2, "append"));
6643 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6644
6645 if (msg->msg_state < HTTP_MSG_DATA)
6646 WILL_LJMP(lua_error(L));
6647
6648 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6649 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6650 if (!filter || !hlua_filter_from_payload(filter))
6651 WILL_LJMP(lua_error(L));
6652
6653 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6654 lua_pushinteger(L, ret);
6655 return 1;
6656}
6657
6658/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6659 * returns the amount of data written or -1 if nothing was copied. Unlike the
6660 * channel function used to prepend data, this one can only be called inside a
6661 * filter, from http_payload callback. So it cannot yield. An exception is
6662 * returned if it is called from another callback.
6663 */
6664__LJMP static int hlua_http_msg_prepend(lua_State *L)
6665{
6666 struct http_msg *msg;
6667 struct filter *filter;
6668 const char *str;
6669 size_t offset, len, sz;
6670 int ret;
6671
6672 MAY_LJMP(check_args(L, 2, "prepend"));
6673 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006674
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006675 if (msg->msg_state < HTTP_MSG_DATA)
6676 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006677
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006678 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6679 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6680 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006681 WILL_LJMP(lua_error(L));
6682
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006683 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6684 lua_pushinteger(L, ret);
6685 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006686}
6687
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006688/* Inserts a string to the HTTP message at a given offset. By default the string
6689 * is appended at the end of DATA blocks. It returns the amount of data written
6690 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6691 * this one can only be called inside a filter, from http_payload callback. So
6692 * it cannot yield. An exception is returned if it is called from another
6693 * callback.
6694 */
6695__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006696{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006697 struct http_msg *msg;
6698 struct filter *filter;
6699 const char *str;
6700 size_t input, output, sz;
6701 int offset;
6702 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006703
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006704 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6705 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006707
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006708 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006709 WILL_LJMP(lua_error(L));
6710
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006711 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006712 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006713 if (!filter || !hlua_filter_from_payload(filter))
6714 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006715
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006716 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006717 if (lua_gettop(L) > 2) {
6718 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6719 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006720 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006721 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006722 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006723 lua_pushfstring(L, "offset out of range.");
6724 WILL_LJMP(lua_error(L));
6725 }
6726 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006727
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006728 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6729 lua_pushinteger(L, ret);
6730 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006731}
6732
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006733/* Removes a given amount of data from the HTTP message at a given offset. By
6734 * default all DATA blocks are removed. It returns the amount of data
6735 * removed. Unlike the channel function used to remove data, this one can only
6736 * be called inside a filter, from http_payload callback. So it cannot yield. An
6737 * exception is returned if it is called from another callback.
6738 */
6739__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006740{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006741 struct http_msg *msg;
6742 struct filter *filter;
6743 size_t input, output;
6744 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006745
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006747 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006748 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006749
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006750 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006751 WILL_LJMP(lua_error(L));
6752
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006753 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006754 if (!filter || !hlua_filter_from_payload(filter))
6755 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006756
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006757 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006758 if (lua_gettop(L) > 1) {
6759 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006760 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006761 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006762 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006763 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006764 lua_pushfstring(L, "offset out of range.");
6765 WILL_LJMP(lua_error(L));
6766 }
6767 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006768
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006769 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006770 if (lua_gettop(L) == 3) {
6771 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 if (!len)
6773 goto end;
6774 if (len == -1)
6775 len = output + input - offset;
6776 if (len < 0 || offset + len > output + input) {
6777 lua_pushfstring(L, "length out of range.");
6778 WILL_LJMP(lua_error(L));
6779 }
6780 }
6781
6782 _hlua_http_msg_delete(msg, filter, offset, len);
6783
6784 end:
6785 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006786 return 1;
6787}
6788
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006789/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006790 * all remaining data are removed, accordingly to the filter context. It returns
6791 * the amount of data written or -1 if nothing was copied. Unlike the channel
6792 * function used to replace data, this one can only be called inside a filter,
6793 * from http_payload callback. So it cannot yield. An exception is returned if
6794 * it is called from another callback.
6795 */
6796__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006797{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006798 struct http_msg *msg;
6799 struct filter *filter;
6800 struct htx *htx;
6801 const char *str;
6802 size_t input, output, sz;
6803 int offset, len;
6804 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006805
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006806 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6807 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6808 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6809
6810 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006811 WILL_LJMP(lua_error(L));
6812
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006813 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6814 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6815 if (!filter || !hlua_filter_from_payload(filter))
6816 WILL_LJMP(lua_error(L));
6817
6818 offset = output;
6819 if (lua_gettop(L) > 2) {
6820 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6821 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006822 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006823 offset += output;
6824 if (offset < output || offset > input + output) {
6825 lua_pushfstring(L, "offset out of range.");
6826 WILL_LJMP(lua_error(L));
6827 }
6828 }
6829
6830 len = output + input - offset;
6831 if (lua_gettop(L) == 4) {
6832 len = MAY_LJMP(luaL_checkinteger(L, 4));
6833 if (!len)
6834 goto set;
6835 if (len == -1)
6836 len = output + input - offset;
6837 if (len < 0 || offset + len > output + input) {
6838 lua_pushfstring(L, "length out of range.");
6839 WILL_LJMP(lua_error(L));
6840 }
6841 }
6842
6843 set:
6844 /* Be sure we can copied the string once input data will be removed. */
6845 htx = htx_from_buf(&msg->chn->buf);
6846 if (sz > htx_free_data_space(htx) + len)
6847 lua_pushinteger(L, -1);
6848 else {
6849 _hlua_http_msg_delete(msg, filter, offset, len);
6850 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6851 lua_pushinteger(L, ret);
6852 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006853 return 1;
6854}
6855
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006856/* Prepends data into an HTTP message and forward it, from the filter point of
6857 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6858 * the channel function used to send data, this one can only be called inside a
6859 * filter, from http_payload callback. So it cannot yield. An exception is
6860 * returned if it is called from another callback.
6861 */
6862__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006863{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006864 struct http_msg *msg;
6865 struct filter *filter;
6866 struct htx *htx;
6867 const char *str;
6868 size_t offset, len, sz;
6869 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006870
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006871 MAY_LJMP(check_args(L, 2, "send"));
6872 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6873
6874 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006875 WILL_LJMP(lua_error(L));
6876
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006877 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6878 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6879 if (!filter || !hlua_filter_from_payload(filter))
6880 WILL_LJMP(lua_error(L));
6881
6882 /* Return an error if the channel's output is closed */
6883 if (unlikely(channel_output_closed(msg->chn))) {
6884 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006885 return 1;
6886 }
6887
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006888 htx = htx_from_buf(&msg->chn->buf);
6889 if (sz > htx_free_data_space(htx)) {
6890 lua_pushinteger(L, -1);
6891 return 1;
6892 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006893
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006894 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6895 if (ret > 0) {
6896 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6897
6898 FLT_OFF(filter, msg->chn) += ret;
6899 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6900 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6901 }
6902
6903 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006904 return 1;
6905}
6906
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006907/* Forwards a given amount of bytes. It return -1 if the channel's output is
6908 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6909 * channel function used to forward data, this one can only be called inside a
6910 * filter, from http_payload callback. So it cannot yield. An exception is
6911 * returned if it is called from another callback. All other functions deal with
6912 * DATA block, this one not.
6913*/
6914__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006915{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006916 struct http_msg *msg;
6917 struct filter *filter;
6918 size_t offset, len;
6919 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006920
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006921 MAY_LJMP(check_args(L, 2, "forward"));
6922 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6923
6924 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006925 WILL_LJMP(lua_error(L));
6926
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006927 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6928 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6929 if (!filter || !hlua_filter_from_payload(filter))
6930 WILL_LJMP(lua_error(L));
6931
6932 /* Nothing to do, just return */
6933 if (!fwd)
6934 goto end;
6935
6936 /* Return an error if the channel's output is closed */
6937 if (unlikely(channel_output_closed(msg->chn))) {
6938 ret = -1;
6939 goto end;
6940 }
6941
6942 ret = fwd;
6943 if (ret > len)
6944 ret = len;
6945
6946 if (ret) {
6947 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6948
6949 FLT_OFF(filter, msg->chn) += ret;
6950 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6951 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6952 }
6953
6954 end:
6955 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006956 return 1;
6957}
6958
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006959/* Set EOM flag on the HTX message.
6960 *
6961 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6962 * really know how to do without this feature.
6963 */
6964__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006965{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006966 struct http_msg *msg;
6967 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006968
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006969 MAY_LJMP(check_args(L, 1, "set_eom"));
6970 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6971 htx = htxbuf(&msg->chn->buf);
6972 htx->flags |= HTX_FL_EOM;
6973 return 0;
6974}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006975
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006976/* Unset EOM flag on the HTX message.
6977 *
6978 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6979 * really know how to do without this feature.
6980 */
6981__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6982{
6983 struct http_msg *msg;
6984 struct htx *htx;
6985
6986 MAY_LJMP(check_args(L, 1, "set_eom"));
6987 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6988 htx = htxbuf(&msg->chn->buf);
6989 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006990 return 0;
6991}
6992
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006993/*
6994 *
6995 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006996 * Class HTTPClient
6997 *
6998 *
6999 */
7000__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7001{
7002 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7003}
7004
William Lallemandf77f1de2021-09-28 19:10:38 +02007005
7006/* stops the httpclient and ask it to kill itself */
7007__LJMP static int hlua_httpclient_gc(lua_State *L)
7008{
7009 struct hlua_httpclient *hlua_hc;
7010
7011 MAY_LJMP(check_args(L, 1, "__gc"));
7012
7013 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7014
7015 httpclient_stop_and_destroy(hlua_hc->hc);
7016
7017 hlua_hc->hc = NULL;
7018
7019
7020 return 0;
7021}
7022
7023
William Lallemand3956c4e2021-09-21 16:25:15 +02007024__LJMP static int hlua_httpclient_new(lua_State *L)
7025{
7026 struct hlua_httpclient *hlua_hc;
7027 struct hlua *hlua;
7028
7029 /* Get hlua struct, or NULL if we execute from main lua state */
7030 hlua = hlua_gethlua(L);
7031 if (!hlua)
7032 return 0;
7033
7034 /* Check stack size. */
7035 if (!lua_checkstack(L, 3)) {
7036 hlua_pusherror(L, "httpclient: full stack");
7037 goto err;
7038 }
7039 /* Create the object: obj[0] = userdata. */
7040 lua_newtable(L);
7041 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7042 lua_rawseti(L, -2, 0);
7043 memset(hlua_hc, 0, sizeof(*hlua_hc));
7044
7045 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7046 if (!hlua_hc->hc)
7047 goto err;
7048
7049 /* Pop a class stream metatable and affect it to the userdata. */
7050 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7051 lua_setmetatable(L, -2);
7052
7053 return 1;
7054
7055 err:
7056 WILL_LJMP(lua_error(L));
7057 return 0;
7058}
7059
7060
7061/*
7062 * Callback of the httpclient, this callback wakes the lua task up, once the
7063 * httpclient receives some data
7064 *
7065 */
7066
William Lallemandbd5739e2021-10-28 15:41:38 +02007067static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007068{
7069 struct hlua *hlua = hc->caller;
7070
7071 if (!hlua || !hlua->task)
7072 return;
7073
7074 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7075}
7076
7077/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007078 * Fill the lua stack with headers from the httpclient response
7079 * This works the same way as the hlua_http_get_headers() function
7080 */
7081__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7082{
7083 struct http_hdr *hdr;
7084
7085 lua_newtable(L);
7086
William Lallemandef574b22021-10-05 16:19:31 +02007087 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007088 struct ist n, v;
7089 int len;
7090
7091 n = hdr->n;
7092 v = hdr->v;
7093
7094 /* Check for existing entry:
7095 * assume that the table is on the top of the stack, and
7096 * push the key in the stack, the function lua_gettable()
7097 * perform the lookup.
7098 */
7099
7100 lua_pushlstring(L, n.ptr, n.len);
7101 lua_gettable(L, -2);
7102
7103 switch (lua_type(L, -1)) {
7104 case LUA_TNIL:
7105 /* Table not found, create it. */
7106 lua_pop(L, 1); /* remove the nil value. */
7107 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7108 lua_newtable(L); /* create and push empty table. */
7109 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7110 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7111 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7112 break;
7113
7114 case LUA_TTABLE:
7115 /* Entry found: push the value in the table. */
7116 len = lua_rawlen(L, -1);
7117 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7118 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7119 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7120 break;
7121
7122 default:
7123 /* Other cases are errors. */
7124 hlua_pusherror(L, "internal error during the parsing of headers.");
7125 WILL_LJMP(lua_error(L));
7126 }
7127 }
7128 return 1;
7129}
7130
7131/*
William Lallemand746e6f32021-10-06 10:57:44 +02007132 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7133 *
7134 * Caller must free the result
7135 */
7136struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7137{
7138 struct http_hdr hdrs[global.tune.max_http_hdr];
7139 struct http_hdr *result = NULL;
7140 uint32_t hdr_num = 0;
7141
7142 lua_pushnil(L);
7143 while (lua_next(L, -2) != 0) {
7144 struct ist name, value;
7145 const char *n, *v;
7146 size_t nlen, vlen;
7147
7148 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7149 /* Skip element if the key is not a string or if the value is not a table */
7150 goto next_hdr;
7151 }
7152
7153 n = lua_tolstring(L, -2, &nlen);
7154 name = ist2(n, nlen);
7155
7156 /* Loop on header's values */
7157 lua_pushnil(L);
7158 while (lua_next(L, -2)) {
7159 if (!lua_isstring(L, -1)) {
7160 /* Skip the value if it is not a string */
7161 goto next_value;
7162 }
7163
7164 v = lua_tolstring(L, -1, &vlen);
7165 value = ist2(v, vlen);
7166 name = ist2(n, nlen);
7167
7168 hdrs[hdr_num].n = istdup(name);
7169 hdrs[hdr_num].v = istdup(value);
7170
7171 hdr_num++;
7172
7173 next_value:
7174 lua_pop(L, 1);
7175 }
7176
7177 next_hdr:
7178 lua_pop(L, 1);
7179
7180 }
7181
7182 if (hdr_num) {
7183 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007184 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007185 if (!result)
7186 goto skip_headers;
7187 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7188
7189 result[hdr_num].n = IST_NULL;
7190 result[hdr_num].v = IST_NULL;
7191 }
7192
7193skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007194
7195 return result;
7196}
7197
7198
William Lallemandbd5739e2021-10-28 15:41:38 +02007199/*
7200 * For each yield, checks if there is some data in the httpclient and push them
7201 * in the lua buffer, once the httpclient finished its job, push the result on
7202 * the stack
7203 */
7204__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7205{
7206 struct buffer *tr;
7207 int res;
7208 struct hlua *hlua = hlua_gethlua(L);
7209 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7210
7211
7212 tr = get_trash_chunk();
7213
7214 res = httpclient_res_xfer(hlua_hc->hc, tr);
7215 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7216
7217 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7218
7219 luaL_pushresult(&hlua_hc->b);
7220 lua_settable(L, -3);
7221
7222 lua_pushstring(L, "status");
7223 lua_pushinteger(L, hlua_hc->hc->res.status);
7224 lua_settable(L, -3);
7225
7226
7227 lua_pushstring(L, "reason");
7228 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7229 lua_settable(L, -3);
7230
7231 lua_pushstring(L, "headers");
7232 hlua_httpclient_get_headers(L, hlua_hc);
7233 lua_settable(L, -3);
7234
7235 return 1;
7236 }
7237
7238 if (httpclient_data(hlua_hc->hc))
7239 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7240
7241 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7242
7243 return 0;
7244}
7245
7246/*
7247 * Call this when trying to stream a body during a request
7248 */
7249__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7250{
7251 struct hlua *hlua;
7252 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7253 const char *body_str = NULL;
7254 int ret;
7255 int end = 0;
7256 size_t buf_len;
7257 size_t to_send = 0;
7258
7259 hlua = hlua_gethlua(L);
7260
7261 if (!hlua || !hlua->task)
7262 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7263 "'frontend', 'backend' or 'task'"));
7264
7265 ret = lua_getfield(L, -1, "body");
7266 if (ret != LUA_TSTRING)
7267 goto rcv;
7268
7269 body_str = lua_tolstring(L, -1, &buf_len);
7270 lua_pop(L, 1);
7271
Christopher Fauletfc591292022-01-12 14:46:03 +01007272 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007273
7274 if ((hlua_hc->sent + to_send) >= buf_len)
7275 end = 1;
7276
7277 /* the end flag is always set since we are using the whole remaining size */
7278 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7279
7280 if (buf_len > hlua_hc->sent) {
7281 /* still need to process the buffer */
7282 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7283 } else {
7284 goto rcv;
7285 /* we sent the whole request buffer we can recv */
7286 }
7287 return 0;
7288
7289rcv:
7290
7291 /* we return a "res" object */
7292 lua_newtable(L);
7293
William Lallemandbd5739e2021-10-28 15:41:38 +02007294 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007295 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007296
William Lallemand933fe392021-11-04 09:45:58 +01007297 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007298 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7299
7300 return 1;
7301}
William Lallemand746e6f32021-10-06 10:57:44 +02007302
William Lallemand3956c4e2021-09-21 16:25:15 +02007303/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007304 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007305 */
7306
William Lallemanddc2cc902021-10-26 11:43:26 +02007307__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007308{
7309 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007310 struct http_hdr *hdrs = NULL;
7311 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007312 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007313 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007314 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007315 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007316 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007317
7318 hlua = hlua_gethlua(L);
7319
7320 if (!hlua || !hlua->task)
7321 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7322 "'frontend', 'backend' or 'task'"));
7323
William Lallemand746e6f32021-10-06 10:57:44 +02007324 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7325 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7326
William Lallemand4f4f2b72022-02-17 20:00:23 +01007327 hlua_hc = hlua_checkhttpclient(L, 1);
7328
William Lallemand7177a952022-03-03 15:33:12 +01007329 lua_pushnil(L); /* first key */
7330 while (lua_next(L, 2)) {
7331 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7332 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7333 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007334
William Lallemand7177a952022-03-03 15:33:12 +01007335 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7336 if (lua_type(L, -1) != LUA_TSTRING)
7337 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7338 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007339
William Lallemand7177a952022-03-03 15:33:12 +01007340 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7341 if (lua_type(L, -1) != LUA_TNUMBER)
7342 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7343 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007344
William Lallemand7177a952022-03-03 15:33:12 +01007345 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7346 if (lua_type(L, -1) != LUA_TTABLE)
7347 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7348 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007349
William Lallemand7177a952022-03-03 15:33:12 +01007350 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7351 if (lua_type(L, -1) != LUA_TSTRING)
7352 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7353 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007354
William Lallemand7177a952022-03-03 15:33:12 +01007355 } else {
7356 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7357 }
7358 /* removes 'value'; keeps 'key' for next iteration */
7359 lua_pop(L, 1);
7360 }
William Lallemanddec25c32021-10-25 19:48:37 +02007361
William Lallemand746e6f32021-10-06 10:57:44 +02007362 if (!url_str) {
7363 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7364 return 0;
7365 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007366
William Lallemand10a37362022-03-02 16:18:26 +01007367 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007368
7369 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007370 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007371
7372 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007373 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7374 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7375 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007376 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007377
William Lallemandbd5739e2021-10-28 15:41:38 +02007378 /* a body is available, it will use the request callback */
7379 if (body_str) {
7380 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7381 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007382
William Lallemandbd5739e2021-10-28 15:41:38 +02007383 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007384
William Lallemand746e6f32021-10-06 10:57:44 +02007385 /* free the temporary headers array */
7386 hdrs_i = hdrs;
7387 while (hdrs_i && isttest(hdrs_i->n)) {
7388 istfree(&hdrs_i->n);
7389 istfree(&hdrs_i->v);
7390 hdrs_i++;
7391 }
7392 ha_free(&hdrs);
7393
7394
William Lallemand6137a9e2021-10-26 15:01:53 +02007395 if (ret != ERR_NONE) {
7396 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7397 return 0;
7398 }
7399
William Lallemandc2d3db42022-04-26 11:46:13 +02007400 if (!httpclient_start(hlua_hc->hc))
7401 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007402
William Lallemandbd5739e2021-10-28 15:41:38 +02007403 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007404
William Lallemand3956c4e2021-09-21 16:25:15 +02007405 return 0;
7406}
7407
7408/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007409 * Sends an HTTP HEAD request and wait for a response
7410 *
7411 * httpclient:head(url, headers, payload)
7412 */
7413__LJMP static int hlua_httpclient_head(lua_State *L)
7414{
7415 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7416}
7417
7418/*
7419 * Send an HTTP GET request and wait for a response
7420 *
7421 * httpclient:get(url, headers, payload)
7422 */
7423__LJMP static int hlua_httpclient_get(lua_State *L)
7424{
7425 return hlua_httpclient_send(L, HTTP_METH_GET);
7426
7427}
7428
7429/*
7430 * Sends an HTTP PUT request and wait for a response
7431 *
7432 * httpclient:put(url, headers, payload)
7433 */
7434__LJMP static int hlua_httpclient_put(lua_State *L)
7435{
7436 return hlua_httpclient_send(L, HTTP_METH_PUT);
7437}
7438
7439/*
7440 * Send an HTTP POST request and wait for a response
7441 *
7442 * httpclient:post(url, headers, payload)
7443 */
7444__LJMP static int hlua_httpclient_post(lua_State *L)
7445{
7446 return hlua_httpclient_send(L, HTTP_METH_POST);
7447}
7448
7449
7450/*
7451 * Sends an HTTP DELETE request and wait for a response
7452 *
7453 * httpclient:delete(url, headers, payload)
7454 */
7455__LJMP static int hlua_httpclient_delete(lua_State *L)
7456{
7457 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7458}
7459
7460/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007461 *
7462 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007463 * Class TXN
7464 *
7465 *
7466 */
7467
7468/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007469 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007470 */
7471__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7472{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007473 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007474}
7475
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007476__LJMP static int hlua_set_var(lua_State *L)
7477{
7478 struct hlua_txn *htxn;
7479 const char *name;
7480 size_t len;
7481 struct sample smp;
7482
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007483 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7484 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007485
7486 /* It is useles to retrieve the stream, but this function
7487 * runs only in a stream context.
7488 */
7489 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7490 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7491
7492 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007493 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007494 hlua_lua2smp(L, 3, &smp);
7495
7496 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007497 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007498
7499 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7500 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7501 else
7502 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7503
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007504 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007505}
7506
Christopher Faulet85d79c92016-11-09 16:54:56 +01007507__LJMP static int hlua_unset_var(lua_State *L)
7508{
7509 struct hlua_txn *htxn;
7510 const char *name;
7511 size_t len;
7512 struct sample smp;
7513
7514 MAY_LJMP(check_args(L, 2, "unset_var"));
7515
7516 /* It is useles to retrieve the stream, but this function
7517 * runs only in a stream context.
7518 */
7519 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7520 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7521
7522 /* Unset the variable. */
7523 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007524 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7525 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007526}
7527
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007528__LJMP static int hlua_get_var(lua_State *L)
7529{
7530 struct hlua_txn *htxn;
7531 const char *name;
7532 size_t len;
7533 struct sample smp;
7534
7535 MAY_LJMP(check_args(L, 2, "get_var"));
7536
7537 /* It is useles to retrieve the stream, but this function
7538 * runs only in a stream context.
7539 */
7540 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7541 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7542
Willy Tarreau7560dd42016-03-10 16:28:58 +01007543 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007544 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007545 lua_pushnil(L);
7546 return 1;
7547 }
7548
7549 return hlua_smp2lua(L, &smp);
7550}
7551
Willy Tarreau59551662015-03-10 14:23:13 +01007552__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007553{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007554 struct hlua *hlua;
7555
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007556 MAY_LJMP(check_args(L, 2, "set_priv"));
7557
Willy Tarreau87b09662015-04-03 00:22:06 +02007558 /* It is useles to retrieve the stream, but this function
7559 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007560 */
7561 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007562
7563 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007564 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007565 if (!hlua)
7566 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007567
7568 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007569 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007570
7571 /* Get and store new value. */
7572 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7573 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7574
7575 return 0;
7576}
7577
Willy Tarreau59551662015-03-10 14:23:13 +01007578__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007579{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007580 struct hlua *hlua;
7581
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007582 MAY_LJMP(check_args(L, 1, "get_priv"));
7583
Willy Tarreau87b09662015-04-03 00:22:06 +02007584 /* It is useles to retrieve the stream, but this function
7585 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007586 */
7587 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007588
7589 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007590 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007591 if (!hlua) {
7592 lua_pushnil(L);
7593 return 1;
7594 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007595
7596 /* Push configuration index in the stack. */
7597 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7598
7599 return 1;
7600}
7601
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007602/* Create stack entry containing a class TXN. This function
7603 * return 0 if the stack does not contains free slots,
7604 * otherwise it returns 1.
7605 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007606static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007607{
Willy Tarreaude491382015-04-06 11:04:28 +02007608 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007609
7610 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007611 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007612 return 0;
7613
7614 /* NOTE: The allocation never fails. The failure
7615 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007616 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007617 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007618 /* Create the object: obj[0] = userdata. */
7619 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007620 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007621 lua_rawseti(L, -2, 0);
7622
Willy Tarreaude491382015-04-06 11:04:28 +02007623 htxn->s = s;
7624 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007625 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007626 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007627
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007628 /* Create the "f" field that contains a list of fetches. */
7629 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007630 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007631 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007632 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007633
7634 /* Create the "sf" field that contains a list of stringsafe fetches. */
7635 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007636 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007637 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007638 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007639
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007640 /* Create the "c" field that contains a list of converters. */
7641 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007642 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007643 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007644 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007645
7646 /* Create the "sc" field that contains a list of stringsafe converters. */
7647 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007648 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007649 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007650 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007651
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007652 /* Create the "req" field that contains the request channel object. */
7653 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007654 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007655 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007656 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007657
7658 /* Create the "res" field that contains the response channel object. */
7659 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007660 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007661 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007662 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007663
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007664 /* Creates the HTTP object is the current proxy allows http. */
7665 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007666 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007667 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007668 return 0;
7669 }
7670 else
7671 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007672 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007673
Christopher Faulet78c35472020-02-26 17:14:08 +01007674 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7675 /* HTTPMessage object are created when a lua TXN is created from
7676 * a filter context only
7677 */
7678
7679 /* Creates the HTTP-Request object is the current proxy allows http. */
7680 lua_pushstring(L, "http_req");
7681 if (p->mode == PR_MODE_HTTP) {
7682 if (!hlua_http_msg_new(L, &s->txn->req))
7683 return 0;
7684 }
7685 else
7686 lua_pushnil(L);
7687 lua_rawset(L, -3);
7688
7689 /* Creates the HTTP-Response object is the current proxy allows http. */
7690 lua_pushstring(L, "http_res");
7691 if (p->mode == PR_MODE_HTTP) {
7692 if (!hlua_http_msg_new(L, &s->txn->rsp))
7693 return 0;
7694 }
7695 else
7696 lua_pushnil(L);
7697 lua_rawset(L, -3);
7698 }
7699
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007700 /* Pop a class sesison metatable and affect it to the userdata. */
7701 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7702 lua_setmetatable(L, -2);
7703
7704 return 1;
7705}
7706
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007707__LJMP static int hlua_txn_deflog(lua_State *L)
7708{
7709 const char *msg;
7710 struct hlua_txn *htxn;
7711
7712 MAY_LJMP(check_args(L, 2, "deflog"));
7713 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7714 msg = MAY_LJMP(luaL_checkstring(L, 2));
7715
7716 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7717 return 0;
7718}
7719
7720__LJMP static int hlua_txn_log(lua_State *L)
7721{
7722 int level;
7723 const char *msg;
7724 struct hlua_txn *htxn;
7725
7726 MAY_LJMP(check_args(L, 3, "log"));
7727 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7728 level = MAY_LJMP(luaL_checkinteger(L, 2));
7729 msg = MAY_LJMP(luaL_checkstring(L, 3));
7730
7731 if (level < 0 || level >= NB_LOG_LEVELS)
7732 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7733
7734 hlua_sendlog(htxn->s->be, level, msg);
7735 return 0;
7736}
7737
7738__LJMP static int hlua_txn_log_debug(lua_State *L)
7739{
7740 const char *msg;
7741 struct hlua_txn *htxn;
7742
7743 MAY_LJMP(check_args(L, 2, "Debug"));
7744 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7745 msg = MAY_LJMP(luaL_checkstring(L, 2));
7746 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7747 return 0;
7748}
7749
7750__LJMP static int hlua_txn_log_info(lua_State *L)
7751{
7752 const char *msg;
7753 struct hlua_txn *htxn;
7754
7755 MAY_LJMP(check_args(L, 2, "Info"));
7756 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7757 msg = MAY_LJMP(luaL_checkstring(L, 2));
7758 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7759 return 0;
7760}
7761
7762__LJMP static int hlua_txn_log_warning(lua_State *L)
7763{
7764 const char *msg;
7765 struct hlua_txn *htxn;
7766
7767 MAY_LJMP(check_args(L, 2, "Warning"));
7768 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7769 msg = MAY_LJMP(luaL_checkstring(L, 2));
7770 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7771 return 0;
7772}
7773
7774__LJMP static int hlua_txn_log_alert(lua_State *L)
7775{
7776 const char *msg;
7777 struct hlua_txn *htxn;
7778
7779 MAY_LJMP(check_args(L, 2, "Alert"));
7780 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7781 msg = MAY_LJMP(luaL_checkstring(L, 2));
7782 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7783 return 0;
7784}
7785
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007786__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7787{
7788 struct hlua_txn *htxn;
7789 int ll;
7790
7791 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7792 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7793 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7794
7795 if (ll < 0 || ll > 7)
7796 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7797
7798 htxn->s->logs.level = ll;
7799 return 0;
7800}
7801
7802__LJMP static int hlua_txn_set_tos(lua_State *L)
7803{
7804 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007805 int tos;
7806
7807 MAY_LJMP(check_args(L, 2, "set_tos"));
7808 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7809 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7810
Willy Tarreau1a18b542018-12-11 16:37:42 +01007811 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007812 return 0;
7813}
7814
7815__LJMP static int hlua_txn_set_mark(lua_State *L)
7816{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007817 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007818 int mark;
7819
7820 MAY_LJMP(check_args(L, 2, "set_mark"));
7821 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7822 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7823
Lukas Tribus579e3e32019-08-11 18:03:45 +02007824 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007825 return 0;
7826}
7827
Patrick Hemmer268a7072018-05-11 12:52:31 -04007828__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7829{
7830 struct hlua_txn *htxn;
7831
7832 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7833 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7834 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7835 return 0;
7836}
7837
7838__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7839{
7840 struct hlua_txn *htxn;
7841
7842 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7843 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7844 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7845 return 0;
7846}
7847
Christopher Faulet700d9e82020-01-31 12:21:52 +01007848/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007849 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007850 * message and terminate the transaction. It returns 1 on success and 0 on
7851 * error. The Reply must be on top of the stack.
7852 */
7853__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7854{
7855 struct htx *htx;
7856 struct htx_sl *sl;
7857 struct h1m h1m;
7858 const char *status, *reason, *body;
7859 size_t status_len, reason_len, body_len;
7860 int ret, code, flags;
7861
7862 code = 200;
7863 status = "200";
7864 status_len = 3;
7865 ret = lua_getfield(L, -1, "status");
7866 if (ret == LUA_TNUMBER) {
7867 code = lua_tointeger(L, -1);
7868 status = lua_tolstring(L, -1, &status_len);
7869 }
7870 lua_pop(L, 1);
7871
7872 reason = http_get_reason(code);
7873 reason_len = strlen(reason);
7874 ret = lua_getfield(L, -1, "reason");
7875 if (ret == LUA_TSTRING)
7876 reason = lua_tolstring(L, -1, &reason_len);
7877 lua_pop(L, 1);
7878
7879 body = NULL;
7880 body_len = 0;
7881 ret = lua_getfield(L, -1, "body");
7882 if (ret == LUA_TSTRING)
7883 body = lua_tolstring(L, -1, &body_len);
7884 lua_pop(L, 1);
7885
7886 /* Prepare the response before inserting the headers */
7887 h1m_init_res(&h1m);
7888 htx = htx_from_buf(&s->res.buf);
7889 channel_htx_truncate(&s->res, htx);
7890 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7891 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7892 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7893 ist2(status, status_len), ist2(reason, reason_len));
7894 }
7895 else {
7896 flags = HTX_SL_F_IS_RESP;
7897 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7898 ist2(status, status_len), ist2(reason, reason_len));
7899 }
7900 if (!sl)
7901 goto fail;
7902 sl->info.res.status = code;
7903
7904 /* Push in the stack the "headers" entry. */
7905 ret = lua_getfield(L, -1, "headers");
7906 if (ret != LUA_TTABLE)
7907 goto skip_headers;
7908
7909 lua_pushnil(L);
7910 while (lua_next(L, -2) != 0) {
7911 struct ist name, value;
7912 const char *n, *v;
7913 size_t nlen, vlen;
7914
7915 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7916 /* Skip element if the key is not a string or if the value is not a table */
7917 goto next_hdr;
7918 }
7919
7920 n = lua_tolstring(L, -2, &nlen);
7921 name = ist2(n, nlen);
7922 if (isteqi(name, ist("content-length"))) {
7923 /* Always skip content-length header. It will be added
7924 * later with the correct len
7925 */
7926 goto next_hdr;
7927 }
7928
7929 /* Loop on header's values */
7930 lua_pushnil(L);
7931 while (lua_next(L, -2)) {
7932 if (!lua_isstring(L, -1)) {
7933 /* Skip the value if it is not a string */
7934 goto next_value;
7935 }
7936
7937 v = lua_tolstring(L, -1, &vlen);
7938 value = ist2(v, vlen);
7939
7940 if (isteqi(name, ist("transfer-encoding")))
7941 h1_parse_xfer_enc_header(&h1m, value);
7942 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7943 goto fail;
7944
7945 next_value:
7946 lua_pop(L, 1);
7947 }
7948
7949 next_hdr:
7950 lua_pop(L, 1);
7951 }
7952 skip_headers:
7953 lua_pop(L, 1);
7954
7955 /* Update h1m flags: CLEN is set if CHNK is not present */
7956 if (!(h1m.flags & H1_MF_CHNK)) {
7957 const char *clen = ultoa(body_len);
7958
7959 h1m.flags |= H1_MF_CLEN;
7960 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7961 goto fail;
7962 }
7963 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7964 h1m.flags |= H1_MF_XFER_LEN;
7965
7966 /* Update HTX start-line flags */
7967 if (h1m.flags & H1_MF_XFER_ENC)
7968 flags |= HTX_SL_F_XFER_ENC;
7969 if (h1m.flags & H1_MF_XFER_LEN) {
7970 flags |= HTX_SL_F_XFER_LEN;
7971 if (h1m.flags & H1_MF_CHNK)
7972 flags |= HTX_SL_F_CHNK;
7973 else if (h1m.flags & H1_MF_CLEN)
7974 flags |= HTX_SL_F_CLEN;
7975 if (h1m.body_len == 0)
7976 flags |= HTX_SL_F_BODYLESS;
7977 }
7978 sl->flags |= flags;
7979
7980
7981 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007982 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007983 goto fail;
7984
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007985 htx->flags |= HTX_FL_EOM;
7986
Christopher Faulet700d9e82020-01-31 12:21:52 +01007987 /* Now, forward the response and terminate the transaction */
7988 s->txn->status = code;
7989 htx_to_buf(htx, &s->res.buf);
7990 if (!http_forward_proxy_resp(s, 1))
7991 goto fail;
7992
7993 return 1;
7994
7995 fail:
7996 channel_htx_truncate(&s->res, htx);
7997 return 0;
7998}
7999
8000/* Terminate a transaction if called from a lua action. For TCP streams,
8001 * processing is just aborted. Nothing is returned to the client and all
8002 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8003 * is forwarded to the client before terminating the transaction. On success,
8004 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8005 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8006 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008007 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008008__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008009{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008010 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008011 struct stream *s;
8012 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008013
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008014 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008015
Christopher Faulet700d9e82020-01-31 12:21:52 +01008016 /* If the flags NOTERM is set, we cannot terminate the session, so we
8017 * just end the execution of the current lua code. */
8018 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008019 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008020
Christopher Faulet700d9e82020-01-31 12:21:52 +01008021 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008022 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008023 struct channel *req = &s->req;
8024 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008025
Christopher Faulet700d9e82020-01-31 12:21:52 +01008026 channel_auto_read(req);
8027 channel_abort(req);
8028 channel_auto_close(req);
8029 channel_erase(req);
8030
8031 res->wex = tick_add_ifset(now_ms, res->wto);
8032 channel_auto_read(res);
8033 channel_auto_close(res);
8034 channel_shutr_now(res);
8035
8036 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8037 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008038 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008039
Christopher Faulet700d9e82020-01-31 12:21:52 +01008040 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8041 /* No reply or invalid reply */
8042 s->txn->status = 0;
8043 http_reply_and_close(s, 0, NULL);
8044 }
8045 else {
8046 /* Remove extra args to have the reply on top of the stack */
8047 if (lua_gettop(L) > 2)
8048 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008049
Christopher Faulet700d9e82020-01-31 12:21:52 +01008050 if (!hlua_txn_forward_reply(L, s)) {
8051 if (!(s->flags & SF_ERR_MASK))
8052 s->flags |= SF_ERR_PRXCOND;
8053 lua_pushinteger(L, ACT_RET_ERR);
8054 WILL_LJMP(hlua_done(L));
8055 return 0; /* Never reached */
8056 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008057 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008058
Christopher Faulet700d9e82020-01-31 12:21:52 +01008059 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8060 if (htxn->dir == SMP_OPT_DIR_REQ) {
8061 /* let's log the request time */
8062 s->logs.tv_request = now;
8063 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008064 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008065 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008066
Christopher Faulet700d9e82020-01-31 12:21:52 +01008067 done:
8068 if (!(s->flags & SF_ERR_MASK))
8069 s->flags |= SF_ERR_LOCAL;
8070 if (!(s->flags & SF_FINST_MASK))
8071 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008072
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008073 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8074 lua_pushinteger(L, -1);
8075 else
8076 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008077 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008078 return 0;
8079}
8080
Christopher Faulet700d9e82020-01-31 12:21:52 +01008081/*
8082 *
8083 *
8084 * Class REPLY
8085 *
8086 *
8087 */
8088
8089/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8090 * free slots, the function fails and returns 0;
8091 */
8092static int hlua_txn_reply_new(lua_State *L)
8093{
8094 struct hlua_txn *htxn;
8095 const char *reason, *body = NULL;
8096 int ret, status;
8097
8098 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008099 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008100 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8101 WILL_LJMP(lua_error(L));
8102 }
8103
8104 /* Default value */
8105 status = 200;
8106 reason = http_get_reason(status);
8107
8108 if (lua_istable(L, 2)) {
8109 /* load status and reason from the table argument at index 2 */
8110 ret = lua_getfield(L, 2, "status");
8111 if (ret == LUA_TNIL)
8112 goto reason;
8113 else if (ret != LUA_TNUMBER) {
8114 /* invalid status: ignore the reason */
8115 goto body;
8116 }
8117 status = lua_tointeger(L, -1);
8118
8119 reason:
8120 lua_pop(L, 1); /* restore the stack: remove status */
8121 ret = lua_getfield(L, 2, "reason");
8122 if (ret == LUA_TSTRING)
8123 reason = lua_tostring(L, -1);
8124
8125 body:
8126 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8127 ret = lua_getfield(L, 2, "body");
8128 if (ret == LUA_TSTRING)
8129 body = lua_tostring(L, -1);
8130 lua_pop(L, 1); /* restore the stack: remove body */
8131 }
8132
8133 /* Create the Reply table */
8134 lua_newtable(L);
8135
8136 /* Add status element */
8137 lua_pushstring(L, "status");
8138 lua_pushinteger(L, status);
8139 lua_settable(L, -3);
8140
8141 /* Add reason element */
8142 reason = http_get_reason(status);
8143 lua_pushstring(L, "reason");
8144 lua_pushstring(L, reason);
8145 lua_settable(L, -3);
8146
8147 /* Add body element, nil if undefined */
8148 lua_pushstring(L, "body");
8149 if (body)
8150 lua_pushstring(L, body);
8151 else
8152 lua_pushnil(L);
8153 lua_settable(L, -3);
8154
8155 /* Add headers element */
8156 lua_pushstring(L, "headers");
8157 lua_newtable(L);
8158
8159 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8160 if (lua_istable(L, 2)) {
8161 /* load headers from the table argument at index 2. If it is a table, copy it. */
8162 ret = lua_getfield(L, 2, "headers");
8163 if (ret == LUA_TTABLE) {
8164 /* stack: [ ... <headers:table>, <table> ] */
8165 lua_pushnil(L);
8166 while (lua_next(L, -2) != 0) {
8167 /* stack: [ ... <headers:table>, <table>, k, v] */
8168 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8169 /* invalid value type, skip it */
8170 lua_pop(L, 1);
8171 continue;
8172 }
8173
8174
8175 /* Duplicate the key and swap it with the value. */
8176 lua_pushvalue(L, -2);
8177 lua_insert(L, -2);
8178 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8179
8180 lua_newtable(L);
8181 lua_insert(L, -2);
8182 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8183
8184 if (lua_isstring(L, -1)) {
8185 /* push the value in the inner table */
8186 lua_rawseti(L, -2, 1);
8187 }
8188 else { /* table */
8189 lua_pushnil(L);
8190 while (lua_next(L, -2) != 0) {
8191 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8192 if (!lua_isstring(L, -1)) {
8193 /* invalid value type, skip it*/
8194 lua_pop(L, 1);
8195 continue;
8196 }
8197 /* push the value in the inner table */
8198 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8199 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8200 }
8201 lua_pop(L, 1);
8202 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8203 }
8204
8205 /* push (k,v) on the stack in the headers table:
8206 * stack: [ ... <headers:table>, <table>, k, k, v ]
8207 */
8208 lua_settable(L, -5);
8209 /* stack: [ ... <headers:table>, <table>, k ] */
8210 }
8211 }
8212 lua_pop(L, 1);
8213 }
8214 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8215 lua_settable(L, -3);
8216 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8217
8218 /* Pop a class sesison metatable and affect it to the userdata. */
8219 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8220 lua_setmetatable(L, -2);
8221 return 1;
8222}
8223
8224/* Set the reply status code, and optionally the reason. If no reason is
8225 * provided, the default one corresponding to the status code is used.
8226 */
8227__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8228{
8229 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8230 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8231
8232 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008233 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008234
8235 if (status < 100 || status > 599) {
8236 lua_pushboolean(L, 0);
8237 return 1;
8238 }
8239 if (!reason)
8240 reason = http_get_reason(status);
8241
8242 lua_pushinteger(L, status);
8243 lua_setfield(L, 1, "status");
8244
8245 lua_pushstring(L, reason);
8246 lua_setfield(L, 1, "reason");
8247
8248 lua_pushboolean(L, 1);
8249 return 1;
8250}
8251
8252/* Add a header into the reply object. Each header name is associated to an
8253 * array of values in the "headers" table. If the header name is not found, a
8254 * new entry is created.
8255 */
8256__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8257{
8258 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8259 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8260 int ret;
8261
8262 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008263 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008264
8265 /* Push in the stack the "headers" entry. */
8266 ret = lua_getfield(L, 1, "headers");
8267 if (ret != LUA_TTABLE) {
8268 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8269 WILL_LJMP(lua_error(L));
8270 }
8271
8272 /* check if the header is already registered. If not, register it. */
8273 ret = lua_getfield(L, -1, name);
8274 if (ret == LUA_TNIL) {
8275 /* Entry not found. */
8276 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8277
8278 /* Insert the new header name in the array in the top of the stack.
8279 * It left the new array in the top of the stack.
8280 */
8281 lua_newtable(L);
8282 lua_pushstring(L, name);
8283 lua_pushvalue(L, -2);
8284 lua_settable(L, -4);
8285 }
8286 else if (ret != LUA_TTABLE) {
8287 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8288 WILL_LJMP(lua_error(L));
8289 }
8290
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008291 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008292 * the header value as new entry.
8293 */
8294 lua_pushstring(L, value);
8295 ret = lua_rawlen(L, -2);
8296 lua_rawseti(L, -2, ret + 1);
8297
8298 lua_pushboolean(L, 1);
8299 return 1;
8300}
8301
8302/* Remove all occurrences of a given header name. */
8303__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8304{
8305 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8306 int ret;
8307
8308 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008309 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008310
8311 /* Push in the stack the "headers" entry. */
8312 ret = lua_getfield(L, 1, "headers");
8313 if (ret != LUA_TTABLE) {
8314 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8315 WILL_LJMP(lua_error(L));
8316 }
8317
8318 lua_pushstring(L, name);
8319 lua_pushnil(L);
8320 lua_settable(L, -3);
8321
8322 lua_pushboolean(L, 1);
8323 return 1;
8324}
8325
8326/* Set the reply's body. Overwrite any existing entry. */
8327__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8328{
8329 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
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 lua_pushstring(L, payload);
8335 lua_setfield(L, 1, "body");
8336
8337 lua_pushboolean(L, 1);
8338 return 1;
8339}
8340
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008341__LJMP static int hlua_log(lua_State *L)
8342{
8343 int level;
8344 const char *msg;
8345
8346 MAY_LJMP(check_args(L, 2, "log"));
8347 level = MAY_LJMP(luaL_checkinteger(L, 1));
8348 msg = MAY_LJMP(luaL_checkstring(L, 2));
8349
8350 if (level < 0 || level >= NB_LOG_LEVELS)
8351 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8352
8353 hlua_sendlog(NULL, level, msg);
8354 return 0;
8355}
8356
8357__LJMP static int hlua_log_debug(lua_State *L)
8358{
8359 const char *msg;
8360
8361 MAY_LJMP(check_args(L, 1, "debug"));
8362 msg = MAY_LJMP(luaL_checkstring(L, 1));
8363 hlua_sendlog(NULL, LOG_DEBUG, msg);
8364 return 0;
8365}
8366
8367__LJMP static int hlua_log_info(lua_State *L)
8368{
8369 const char *msg;
8370
8371 MAY_LJMP(check_args(L, 1, "info"));
8372 msg = MAY_LJMP(luaL_checkstring(L, 1));
8373 hlua_sendlog(NULL, LOG_INFO, msg);
8374 return 0;
8375}
8376
8377__LJMP static int hlua_log_warning(lua_State *L)
8378{
8379 const char *msg;
8380
8381 MAY_LJMP(check_args(L, 1, "warning"));
8382 msg = MAY_LJMP(luaL_checkstring(L, 1));
8383 hlua_sendlog(NULL, LOG_WARNING, msg);
8384 return 0;
8385}
8386
8387__LJMP static int hlua_log_alert(lua_State *L)
8388{
8389 const char *msg;
8390
8391 MAY_LJMP(check_args(L, 1, "alert"));
8392 msg = MAY_LJMP(luaL_checkstring(L, 1));
8393 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008394 return 0;
8395}
8396
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008397__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008398{
8399 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008400 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008401 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008402 return 0;
8403}
8404
8405__LJMP static int hlua_sleep(lua_State *L)
8406{
8407 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008408 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008409
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008410 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008411
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008412 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008413 wakeup_ms = tick_add(now_ms, delay);
8414 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008415
Willy Tarreau9635e032018-10-16 17:52:55 +02008416 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008417 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008418}
8419
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008420__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008421{
8422 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008423 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008424
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008425 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008426
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008427 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008428 wakeup_ms = tick_add(now_ms, delay);
8429 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008430
Willy Tarreau9635e032018-10-16 17:52:55 +02008431 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008432 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008433}
8434
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008435/* This functionis an LUA binding. it permits to give back
8436 * the hand at the HAProxy scheduler. It is used when the
8437 * LUA processing consumes a lot of time.
8438 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008439__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008440{
8441 return 0;
8442}
8443
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008444__LJMP static int hlua_yield(lua_State *L)
8445{
Willy Tarreau9635e032018-10-16 17:52:55 +02008446 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008447 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008448}
8449
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008450/* This function change the nice of the currently executed
8451 * task. It is used set low or high priority at the current
8452 * task.
8453 */
Willy Tarreau59551662015-03-10 14:23:13 +01008454__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008455{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008456 struct hlua *hlua;
8457 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008458
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008459 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008460 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008461
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008462 /* Get hlua struct, or NULL if we execute from main lua state */
8463 hlua = hlua_gethlua(L);
8464
8465 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008466 if (!hlua || !hlua->task)
8467 return 0;
8468
8469 if (nice < -1024)
8470 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008471 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008472 nice = 1024;
8473
8474 hlua->task->nice = nice;
8475 return 0;
8476}
8477
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008478/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008479 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8480 * return an E_AGAIN signal, the emmiter of this signal must set a
8481 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008482 *
8483 * Task wrapper are longjmp safe because the only one Lua code
8484 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008485 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008486struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008487{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008488 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008489 enum hlua_exec status;
8490
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008491 if (task->tid < 0)
8492 task->tid = tid;
8493
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008494 /* If it is the first call to the task, we must initialize the
8495 * execution timeouts.
8496 */
8497 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008498 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008499
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008500 /* Execute the Lua code. */
8501 status = hlua_ctx_resume(hlua, 1);
8502
8503 switch (status) {
8504 /* finished or yield */
8505 case HLUA_E_OK:
8506 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008507 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008508 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008509 break;
8510
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008511 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008512 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008513 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008514 break;
8515
8516 /* finished with error. */
8517 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008518 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008519 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008520 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008521 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008522 break;
8523
8524 case HLUA_E_ERR:
8525 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008526 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008527 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008528 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008529 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530 break;
8531 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008532 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008533}
8534
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008535/* This function is an LUA binding that register LUA function to be
8536 * executed after the HAProxy configuration parsing and before the
8537 * HAProxy scheduler starts. This function expect only one LUA
8538 * argument that is a function. This function returns nothing, but
8539 * throws if an error is encountered.
8540 */
8541__LJMP static int hlua_register_init(lua_State *L)
8542{
8543 struct hlua_init_function *init;
8544 int ref;
8545
8546 MAY_LJMP(check_args(L, 1, "register_init"));
8547
8548 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8549
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008550 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008551 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008552 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008553
8554 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008555 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008556 return 0;
8557}
8558
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008559/* This functio is an LUA binding. It permits to register a task
8560 * executed in parallel of the main HAroxy activity. The task is
8561 * created and it is set in the HAProxy scheduler. It can be called
8562 * from the "init" section, "post init" or during the runtime.
8563 *
8564 * Lua prototype:
8565 *
8566 * <none> core.register_task(<function>)
8567 */
8568static int hlua_register_task(lua_State *L)
8569{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008570 struct hlua *hlua = NULL;
8571 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008572 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008573 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008574
8575 MAY_LJMP(check_args(L, 1, "register_task"));
8576
8577 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8578
Thierry Fournier75fc0292020-11-28 13:18:56 +01008579 /* Get the reference state. If the reference is NULL, L is the master
8580 * state, otherwise hlua->T is.
8581 */
8582 hlua = hlua_gethlua(L);
8583 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008584 /* we are in runtime processing */
8585 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008586 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008587 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008588 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008589
Willy Tarreaubafbe012017-11-24 17:34:44 +01008590 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008591 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008592 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008593 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008594
Thierry Fournier59f11be2020-11-29 00:37:41 +01008595 /* We are in the common lua state, execute the task anywhere,
8596 * otherwise, inherit the current thread identifier
8597 */
8598 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008599 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008600 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008601 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008602 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008603 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008604
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008605 task->context = hlua;
8606 task->process = hlua_process_task;
8607
Thierry Fournier021d9862020-11-28 23:42:03 +01008608 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008609 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008610
8611 /* Restore the function in the stack. */
8612 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8613 hlua->nargs = 0;
8614
8615 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008616 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008617
8618 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008619
8620 alloc_error:
8621 task_destroy(task);
8622 hlua_ctx_destroy(hlua);
8623 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8624 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008625}
8626
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008627/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8628 * doesn't allow "yield" functions because the HAProxy engine cannot
8629 * resume converters.
8630 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008631static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008632{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008633 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008634 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008635 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008636
Willy Tarreaube508f12016-03-10 11:47:01 +01008637 if (!stream)
8638 return 0;
8639
Willy Tarreau87b09662015-04-03 00:22:06 +02008640 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008641 * Lua context can be not initialized. This behavior
8642 * permits to save performances because a systematic
8643 * Lua initialization cause 5% performances loss.
8644 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008645 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008646 struct hlua *hlua;
8647
8648 hlua = pool_alloc(pool_head_hlua);
8649 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008650 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8651 return 0;
8652 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008653 HLUA_INIT(hlua);
8654 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008655 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008656 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8657 return 0;
8658 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008659 }
8660
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008661 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008662 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008663
8664 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008665 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008666 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8667 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008668 else
8669 error = "critical error";
8670 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008671 return 0;
8672 }
8673
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008674 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008675 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008676 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008677 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008678 return 0;
8679 }
8680
8681 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008682 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008683
8684 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008685 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008686 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008687 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008688 return 0;
8689 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008690 hlua_smp2lua(stream->hlua->T, smp);
8691 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008692
8693 /* push keywords in the stack. */
8694 if (arg_p) {
8695 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008696 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008697 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008698 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008699 return 0;
8700 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008701 hlua_arg2lua(stream->hlua->T, arg_p);
8702 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008703 }
8704 }
8705
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008706 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008707 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008708
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008709 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008710 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008711 }
8712
8713 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008714 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008715 /* finished. */
8716 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008717 /* If the stack is empty, the function fails. */
8718 if (lua_gettop(stream->hlua->T) <= 0)
8719 return 0;
8720
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008721 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008722 hlua_lua2smp(stream->hlua->T, -1, smp);
8723 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008724 return 1;
8725
8726 /* yield. */
8727 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008728 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008729 return 0;
8730
8731 /* finished with error. */
8732 case HLUA_E_ERRMSG:
8733 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008734 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008735 fcn->name, lua_tostring(stream->hlua->T, -1));
8736 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008737 return 0;
8738
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008739 case HLUA_E_ETMOUT:
8740 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8741 return 0;
8742
8743 case HLUA_E_NOMEM:
8744 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8745 return 0;
8746
8747 case HLUA_E_YIELD:
8748 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8749 return 0;
8750
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008751 case HLUA_E_ERR:
8752 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008753 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008754 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008755
8756 default:
8757 return 0;
8758 }
8759}
8760
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008761/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8762 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008763 * resume sample-fetches. This function will be called by the sample
8764 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008765 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008766static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8767 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008768{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008769 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008770 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008771 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008772 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008773
Willy Tarreaube508f12016-03-10 11:47:01 +01008774 if (!stream)
8775 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008776
Willy Tarreau87b09662015-04-03 00:22:06 +02008777 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008778 * Lua context can be not initialized. This behavior
8779 * permits to save performances because a systematic
8780 * Lua initialization cause 5% performances loss.
8781 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008782 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008783 struct hlua *hlua;
8784
8785 hlua = pool_alloc(pool_head_hlua);
8786 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008787 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8788 return 0;
8789 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008790 hlua->T = NULL;
8791 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008792 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008793 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8794 return 0;
8795 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008796 }
8797
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008798 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008799 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008800
8801 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008802 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008803 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8804 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008805 else
8806 error = "critical error";
8807 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008808 return 0;
8809 }
8810
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008811 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008812 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008813 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008814 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008815 return 0;
8816 }
8817
8818 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008819 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008820
8821 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008822 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008823 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008824 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008825 return 0;
8826 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008827 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008828
8829 /* push keywords in the stack. */
8830 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8831 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008832 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008833 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008834 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008835 return 0;
8836 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008837 hlua_arg2lua(stream->hlua->T, arg_p);
8838 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008839 }
8840
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008841 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008842 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008843
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008844 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008845 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008846 }
8847
8848 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008849 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008850 /* finished. */
8851 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008852 /* If the stack is empty, the function fails. */
8853 if (lua_gettop(stream->hlua->T) <= 0)
8854 return 0;
8855
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008856 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008857 hlua_lua2smp(stream->hlua->T, -1, smp);
8858 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008859
8860 /* Set the end of execution flag. */
8861 smp->flags &= ~SMP_F_MAY_CHANGE;
8862 return 1;
8863
8864 /* yield. */
8865 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008866 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008867 return 0;
8868
8869 /* finished with error. */
8870 case HLUA_E_ERRMSG:
8871 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008872 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008873 fcn->name, lua_tostring(stream->hlua->T, -1));
8874 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008875 return 0;
8876
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008877 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008878 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8879 return 0;
8880
8881 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008882 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8883 return 0;
8884
8885 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008886 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8887 return 0;
8888
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008889 case HLUA_E_ERR:
8890 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008891 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008892 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008893
8894 default:
8895 return 0;
8896 }
8897}
8898
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008899/* This function is an LUA binding used for registering
8900 * "sample-conv" functions. It expects a converter name used
8901 * in the haproxy configuration file, and an LUA function.
8902 */
8903__LJMP static int hlua_register_converters(lua_State *L)
8904{
8905 struct sample_conv_kw_list *sck;
8906 const char *name;
8907 int ref;
8908 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008909 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008910 struct sample_conv *sc;
8911 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008912
8913 MAY_LJMP(check_args(L, 2, "register_converters"));
8914
8915 /* First argument : converter name. */
8916 name = MAY_LJMP(luaL_checkstring(L, 1));
8917
8918 /* Second argument : lua function. */
8919 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8920
Thierry Fournierf67442e2020-11-28 20:41:07 +01008921 /* Check if the converter is already registered */
8922 trash = get_trash_chunk();
8923 chunk_printf(trash, "lua.%s", name);
8924 sc = find_sample_conv(trash->area, trash->data);
8925 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008926 fcn = sc->private;
8927 if (fcn->function_ref[hlua_state_id] != -1) {
8928 ha_warning("Trying to register converter 'lua.%s' more than once. "
8929 "This will become a hard error in version 2.5.\n", name);
8930 }
8931 fcn->function_ref[hlua_state_id] = ref;
8932 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008933 }
8934
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008935 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008936 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008937 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008938 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008939 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008940 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008941 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008942
8943 /* Fill fcn. */
8944 fcn->name = strdup(name);
8945 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008946 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008947 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008948
8949 /* List head */
8950 sck->list.n = sck->list.p = NULL;
8951
8952 /* converter keyword. */
8953 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008954 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008955 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008956 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008957
8958 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8959 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008960 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 +01008961 sck->kw[0].val_args = NULL;
8962 sck->kw[0].in_type = SMP_T_STR;
8963 sck->kw[0].out_type = SMP_T_STR;
8964 sck->kw[0].private = fcn;
8965
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008966 /* Register this new converter */
8967 sample_register_convs(sck);
8968
8969 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008970
8971 alloc_error:
8972 release_hlua_function(fcn);
8973 ha_free(&sck);
8974 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8975 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008976}
8977
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008978/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008979 * "sample-fetch" functions. It expects a converter name used
8980 * in the haproxy configuration file, and an LUA function.
8981 */
8982__LJMP static int hlua_register_fetches(lua_State *L)
8983{
8984 const char *name;
8985 int ref;
8986 int len;
8987 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008988 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008989 struct sample_fetch *sf;
8990 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008991
8992 MAY_LJMP(check_args(L, 2, "register_fetches"));
8993
8994 /* First argument : sample-fetch name. */
8995 name = MAY_LJMP(luaL_checkstring(L, 1));
8996
8997 /* Second argument : lua function. */
8998 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8999
Thierry Fournierf67442e2020-11-28 20:41:07 +01009000 /* Check if the sample-fetch is already registered */
9001 trash = get_trash_chunk();
9002 chunk_printf(trash, "lua.%s", name);
9003 sf = find_sample_fetch(trash->area, trash->data);
9004 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009005 fcn = sf->private;
9006 if (fcn->function_ref[hlua_state_id] != -1) {
9007 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9008 "This will become a hard error in version 2.5.\n", name);
9009 }
9010 fcn->function_ref[hlua_state_id] = ref;
9011 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009012 }
9013
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009014 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009015 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009016 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009017 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009018 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009019 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009020 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009021
9022 /* Fill fcn. */
9023 fcn->name = strdup(name);
9024 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009025 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009026 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009027
9028 /* List head */
9029 sfk->list.n = sfk->list.p = NULL;
9030
9031 /* sample-fetch keyword. */
9032 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009033 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009034 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009035 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009036
9037 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9038 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009039 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 +01009040 sfk->kw[0].val_args = NULL;
9041 sfk->kw[0].out_type = SMP_T_STR;
9042 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9043 sfk->kw[0].val = 0;
9044 sfk->kw[0].private = fcn;
9045
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009046 /* Register this new fetch. */
9047 sample_register_fetches(sfk);
9048
9049 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009050
9051 alloc_error:
9052 release_hlua_function(fcn);
9053 ha_free(&sfk);
9054 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9055 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009056}
9057
Christopher Faulet501465d2020-02-26 14:54:16 +01009058/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009059 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009060__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009061{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009062 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009063 unsigned int delay;
9064 unsigned int wakeup_ms;
9065
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009066 /* Get hlua struct, or NULL if we execute from main lua state */
9067 hlua = hlua_gethlua(L);
9068 if (!hlua) {
9069 return 0;
9070 }
9071
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009072 MAY_LJMP(check_args(L, 1, "wake_time"));
9073
9074 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9075 wakeup_ms = tick_add(now_ms, delay);
9076 hlua->wake_time = wakeup_ms;
9077 return 0;
9078}
9079
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009080/* This function is a wrapper to execute each LUA function declared as an action
9081 * wrapper during the initialisation period. This function may return any
9082 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9083 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9084 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009085 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009086static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009087 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009088{
9089 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009090 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009091 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009092 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009093
9094 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009095 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9096 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9097 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9098 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009099 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009100 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009101 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009102 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009103
Willy Tarreau87b09662015-04-03 00:22:06 +02009104 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009105 * Lua context can be not initialized. This behavior
9106 * permits to save performances because a systematic
9107 * Lua initialization cause 5% performances loss.
9108 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009109 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009110 struct hlua *hlua;
9111
9112 hlua = pool_alloc(pool_head_hlua);
9113 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009114 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009115 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009116 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009117 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009118 HLUA_INIT(hlua);
9119 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009120 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 +01009121 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009122 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009123 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009124 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009125 }
9126
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009127 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009128 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009129
9130 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009131 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009132 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9133 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009134 else
9135 error = "critical error";
9136 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009137 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009138 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009139 }
9140
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009141 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009142 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009143 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009144 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009145 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009146 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009147 }
9148
9149 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009150 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 +01009151
Willy Tarreau87b09662015-04-03 00:22:06 +02009152 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009153 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009154 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009155 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009156 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009157 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009158 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009159 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009160
9161 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009162 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009163 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009164 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009165 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009166 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009167 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009168 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009169 lua_pushstring(s->hlua->T, *arg);
9170 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009171 }
9172
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009173 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009174 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009175
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009176 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009177 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009178 }
9179
9180 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009181 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009182 /* finished. */
9183 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009184 /* Catch the return value */
9185 if (lua_gettop(s->hlua->T) > 0)
9186 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009187
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009188 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009189 if (act_ret == ACT_RET_YIELD) {
9190 if (flags & ACT_OPT_FINAL)
9191 goto err_yield;
9192
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009193 if (dir == SMP_OPT_DIR_REQ)
9194 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9195 s->hlua->wake_time);
9196 else
9197 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9198 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009199 }
9200 goto end;
9201
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009202 /* yield. */
9203 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009204 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009205 if (dir == SMP_OPT_DIR_REQ)
9206 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9207 s->hlua->wake_time);
9208 else
9209 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9210 s->hlua->wake_time);
9211
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009212 /* Some actions can be wake up when a "write" event
9213 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009214 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009215 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009216 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009217 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009218 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009219 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009220 act_ret = ACT_RET_YIELD;
9221 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009222
9223 /* finished with error. */
9224 case HLUA_E_ERRMSG:
9225 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009226 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009227 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009228 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009229 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009230
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009231 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009232 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009233 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009234
9235 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009236 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009237 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009238
9239 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009240 err_yield:
9241 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009242 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009243 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009244 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009245
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009246 case HLUA_E_ERR:
9247 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009248 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009249 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009250
9251 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009252 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009253 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009254
9255 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009256 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009257 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009258 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009259}
9260
Willy Tarreau144f84a2021-03-02 16:09:26 +01009261struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009262{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009263 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009264
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009265 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009266 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009267 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009268}
9269
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009270static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009272 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009273 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009274 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009275 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009276 struct task *task;
9277 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009278 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009279
Willy Tarreaubafbe012017-11-24 17:34:44 +01009280 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009281 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009282 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009283 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009284 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009285 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009286 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009287 tcp_ctx->hlua = hlua;
9288 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009289
9290 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009291 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009292 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009293 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009294 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009295 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009296 }
9297 task->nice = 0;
9298 task->context = ctx;
9299 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009300 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009301
9302 /* In the execution wrappers linked with a stream, the
9303 * Lua context can be not initialized. This behavior
9304 * permits to save performances because a systematic
9305 * Lua initialization cause 5% performances loss.
9306 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009307 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 +01009308 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009309 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009310 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009311 }
9312
9313 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009314 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009315
9316 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009317 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009318 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9319 error = lua_tostring(hlua->T, -1);
9320 else
9321 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009322 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009323 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009324 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009325 }
9326
9327 /* Check stack available size. */
9328 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009329 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009330 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009331 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009332 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009333 }
9334
9335 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009336 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009337
9338 /* Create and and push object stream in the stack. */
9339 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009340 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009341 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009342 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009343 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009344 }
9345 hlua->nargs = 1;
9346
9347 /* push keywords in the stack. */
9348 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9349 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009350 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009351 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009352 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009353 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009354 }
9355 lua_pushstring(hlua->T, *arg);
9356 hlua->nargs++;
9357 }
9358
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009359 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009360
9361 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009362 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009363 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009364
Christopher Fauletc9929382022-05-12 11:52:27 +02009365 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009366}
9367
Willy Tarreau60409db2019-08-21 14:14:50 +02009368void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009369{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009370 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009371 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009372 struct stream *strm = __sc_strm(sc);
9373 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009374 struct act_rule *rule = ctx->rule;
9375 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009376 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009377
9378 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009379 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009380 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009381 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009382 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009383 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009384
9385 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009386 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387 return;
9388
9389 /* Execute the function. */
9390 switch (hlua_ctx_resume(hlua, 1)) {
9391 /* finished. */
9392 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009393 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009394
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009395 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009396 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009397 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009398 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009399 return;
9400
9401 /* yield. */
9402 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009403 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009404 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009405 return;
9406
9407 /* finished with error. */
9408 case HLUA_E_ERRMSG:
9409 /* Display log. */
9410 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009411 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009412 lua_pop(hlua->T, 1);
9413 goto error;
9414
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009415 case HLUA_E_ETMOUT:
9416 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009417 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009418 goto error;
9419
9420 case HLUA_E_NOMEM:
9421 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009422 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009423 goto error;
9424
9425 case HLUA_E_YIELD: /* unexpected */
9426 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009427 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009428 goto error;
9429
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009430 case HLUA_E_ERR:
9431 /* Display log. */
9432 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009433 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009434 goto error;
9435
9436 default:
9437 goto error;
9438 }
9439
9440error:
9441
9442 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009443 sc_shutw(sc);
9444 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009445 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009446}
9447
9448static void hlua_applet_tcp_release(struct appctx *ctx)
9449{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009450 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9451
9452 task_destroy(tcp_ctx->task);
9453 tcp_ctx->task = NULL;
9454 hlua_ctx_destroy(tcp_ctx->hlua);
9455 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009456}
9457
Christopher Fauletc9929382022-05-12 11:52:27 +02009458/* The function returns 0 if the initialisation is complete or -1 if
9459 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009460 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009461static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009462{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009463 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009464 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009465 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009466 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009467 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009468 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009469 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009470 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009471
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009472 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009473 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009474 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009475 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009476 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009477 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009478 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009479 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009480 http_ctx->hlua = hlua;
9481 http_ctx->left_bytes = -1;
9482 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009483
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009484 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009485 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009486
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009487 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009488 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009489 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009490 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009491 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009492 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009493 }
9494 task->nice = 0;
9495 task->context = ctx;
9496 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009497 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009498
9499 /* In the execution wrappers linked with a stream, the
9500 * Lua context can be not initialized. This behavior
9501 * permits to save performances because a systematic
9502 * Lua initialization cause 5% performances loss.
9503 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009504 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 +01009505 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009506 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009507 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009508 }
9509
9510 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009511 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009512
9513 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009514 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009515 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9516 error = lua_tostring(hlua->T, -1);
9517 else
9518 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009519 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009520 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009521 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009522 }
9523
9524 /* Check stack available size. */
9525 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009526 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009527 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009528 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009529 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009530 }
9531
9532 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009533 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009534
9535 /* Create and and push object stream in the stack. */
9536 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009537 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009538 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009539 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009540 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009541 }
9542 hlua->nargs = 1;
9543
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009544 /* push keywords in the stack. */
9545 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9546 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009547 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009548 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009549 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009550 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009551 }
9552 lua_pushstring(hlua->T, *arg);
9553 hlua->nargs++;
9554 }
9555
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009556 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009557
9558 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009559 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009560
Christopher Fauletc9929382022-05-12 11:52:27 +02009561 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009562}
9563
Willy Tarreau60409db2019-08-21 14:14:50 +02009564void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009565{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009566 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009567 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009568 struct stream *strm = __sc_strm(sc);
9569 struct channel *req = sc_oc(sc);
9570 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009571 struct act_rule *rule = ctx->rule;
9572 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009573 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009574 struct htx *req_htx, *res_htx;
9575
9576 res_htx = htx_from_buf(&res->buf);
9577
9578 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009579 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009580 goto out;
9581
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009582 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009583 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009584 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009585 goto out;
9586 }
9587 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009588 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009589 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009590
9591 /* Set the currently running flag. */
9592 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009593 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009594 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009595 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009596 goto out;
9597 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009598 }
9599
9600 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009601 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009602
9603 /* Execute the function. */
9604 switch (hlua_ctx_resume(hlua, 1)) {
9605 /* finished. */
9606 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009607 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009608 break;
9609
9610 /* yield. */
9611 case HLUA_E_AGAIN:
9612 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009613 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009614 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009615
9616 /* finished with error. */
9617 case HLUA_E_ERRMSG:
9618 /* Display log. */
9619 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009620 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009621 lua_pop(hlua->T, 1);
9622 goto error;
9623
9624 case HLUA_E_ETMOUT:
9625 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009626 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009627 goto error;
9628
9629 case HLUA_E_NOMEM:
9630 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009631 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009632 goto error;
9633
9634 case HLUA_E_YIELD: /* unexpected */
9635 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009636 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009637 goto error;
9638
9639 case HLUA_E_ERR:
9640 /* Display log. */
9641 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009642 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009643 goto error;
9644
9645 default:
9646 goto error;
9647 }
9648 }
9649
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009650 if (http_ctx->flags & APPLET_DONE) {
9651 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009652 goto done;
9653
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009654 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009655 goto error;
9656
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009657 /* no more data are expected. If the response buffer is empty
9658 * for a chunked message, be sure to add something (EOT block in
9659 * this case) to have something to send. It is important to be
9660 * sure the EOM flags will be handled by the endpoint.
9661 */
9662 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9663 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009664 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009665 goto out;
9666 }
9667 channel_add_input(res, 1);
9668 }
9669
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009670 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009671 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009672 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009673 strm->txn->status = http_ctx->status;
9674 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009675 }
9676
9677 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009678 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009679 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009680 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009681 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009682 }
9683
9684 /* eat the whole request */
9685 if (co_data(req)) {
9686 req_htx = htx_from_buf(&req->buf);
9687 co_htx_skip(req, req_htx, co_data(req));
9688 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009689 }
9690 }
9691
9692 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009693 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009694 return;
9695
9696 error:
9697
9698 /* If we are in HTTP mode, and we are not send any
9699 * data, return a 500 server error in best effort:
9700 * if there is no room available in the buffer,
9701 * just close the connection.
9702 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009703 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009704 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009705
9706 channel_erase(res);
9707 res->buf.data = b_data(err);
9708 memcpy(res->buf.area, b_head(err), b_data(err));
9709 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009710 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009711 }
9712 if (!(strm->flags & SF_ERR_MASK))
9713 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009714 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009715 goto done;
9716}
9717
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009718static void hlua_applet_http_release(struct appctx *ctx)
9719{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009720 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9721
9722 task_destroy(http_ctx->task);
9723 http_ctx->task = NULL;
9724 hlua_ctx_destroy(http_ctx->hlua);
9725 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009726}
9727
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009728/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009729 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009730 *
9731 * This function can fail with an abort() due to an Lua critical error.
9732 * We are in the configuration parsing process of HAProxy, this abort() is
9733 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009734 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009735static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9736 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009737{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009738 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009739 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009740
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009741 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009742 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009743 if (!rule->arg.hlua_rule) {
9744 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009745 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009746 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009747
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009748 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009749 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9750 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009751 if (!rule->arg.hlua_rule->args) {
9752 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009753 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009754 }
9755
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009756 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009757 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009758
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009759 /* Expect some arguments */
9760 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009761 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009762 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009763 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009764 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009765 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009766 if (!rule->arg.hlua_rule->args[i]) {
9767 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009768 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009769 }
9770 (*cur_arg)++;
9771 }
9772 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009773
Thierry FOURNIER42148732015-09-02 17:17:33 +02009774 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009775 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009776 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009777
9778 error:
9779 if (rule->arg.hlua_rule) {
9780 if (rule->arg.hlua_rule->args) {
9781 for (i = 0; i < fcn->nargs; i++)
9782 ha_free(&rule->arg.hlua_rule->args[i]);
9783 ha_free(&rule->arg.hlua_rule->args);
9784 }
9785 ha_free(&rule->arg.hlua_rule);
9786 }
9787 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009788}
9789
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009790static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9791 struct act_rule *rule, char **err)
9792{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009793 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009794
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009795 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009796 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009797 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009798 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009799 * the call of this analyzer.
9800 */
9801 if (rule->from != ACT_F_HTTP_REQ) {
9802 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9803 return ACT_RET_PRS_ERR;
9804 }
9805
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009806 /* Memory for the rule. */
9807 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9808 if (!rule->arg.hlua_rule) {
9809 memprintf(err, "out of memory error");
9810 return ACT_RET_PRS_ERR;
9811 }
9812
9813 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009814 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009815
9816 /* TODO: later accept arguments. */
9817 rule->arg.hlua_rule->args = NULL;
9818
9819 /* Add applet pointer in the rule. */
9820 rule->applet.obj_type = OBJ_TYPE_APPLET;
9821 rule->applet.name = fcn->name;
9822 rule->applet.init = hlua_applet_http_init;
9823 rule->applet.fct = hlua_applet_http_fct;
9824 rule->applet.release = hlua_applet_http_release;
9825 rule->applet.timeout = hlua_timeout_applet;
9826
9827 return ACT_RET_PRS_OK;
9828}
9829
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009830/* This function is an LUA binding used for registering
9831 * "sample-conv" functions. It expects a converter name used
9832 * in the haproxy configuration file, and an LUA function.
9833 */
9834__LJMP static int hlua_register_action(lua_State *L)
9835{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009836 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009837 const char *name;
9838 int ref;
9839 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009840 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009841 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009842 struct buffer *trash;
9843 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009844
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009845 /* Initialise the number of expected arguments at 0. */
9846 nargs = 0;
9847
9848 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9849 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009850
9851 /* First argument : converter name. */
9852 name = MAY_LJMP(luaL_checkstring(L, 1));
9853
9854 /* Second argument : environment. */
9855 if (lua_type(L, 2) != LUA_TTABLE)
9856 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9857
9858 /* Third argument : lua function. */
9859 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9860
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009861 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009862 if (lua_gettop(L) >= 4)
9863 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9864
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009865 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009866 lua_pushnil(L);
9867 while (lua_next(L, 2) != 0) {
9868 if (lua_type(L, -1) != LUA_TSTRING)
9869 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9870
Thierry Fournierf67442e2020-11-28 20:41:07 +01009871 /* Check if action exists */
9872 trash = get_trash_chunk();
9873 chunk_printf(trash, "lua.%s", name);
9874 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9875 akw = tcp_req_cont_action(trash->area);
9876 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9877 akw = tcp_res_cont_action(trash->area);
9878 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9879 akw = action_http_req_custom(trash->area);
9880 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9881 akw = action_http_res_custom(trash->area);
9882 } else {
9883 akw = NULL;
9884 }
9885 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009886 fcn = akw->private;
9887 if (fcn->function_ref[hlua_state_id] != -1) {
9888 ha_warning("Trying to register action 'lua.%s' more than once. "
9889 "This will become a hard error in version 2.5.\n", name);
9890 }
9891 fcn->function_ref[hlua_state_id] = ref;
9892
9893 /* pop the environment string. */
9894 lua_pop(L, 1);
9895 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009896 }
9897
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009898 /* Check required environment. Only accepted "http" or "tcp". */
9899 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009900 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009901 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009902 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009903 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009904 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009905 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009906
9907 /* Fill fcn. */
9908 fcn->name = strdup(name);
9909 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009910 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009911 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009912
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009913 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009914 fcn->nargs = nargs;
9915
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009916 /* List head */
9917 akl->list.n = akl->list.p = NULL;
9918
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009919 /* action keyword. */
9920 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009921 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009922 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009923 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009924
9925 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9926
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009927 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009928 akl->kw[0].private = fcn;
9929 akl->kw[0].parse = action_register_lua;
9930
9931 /* select the action registering point. */
9932 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9933 tcp_req_cont_keywords_register(akl);
9934 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9935 tcp_res_cont_keywords_register(akl);
9936 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9937 http_req_keywords_register(akl);
9938 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9939 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009940 else {
9941 release_hlua_function(fcn);
9942 if (akl)
9943 ha_free((char **)&(akl->kw[0].kw));
9944 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009945 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009946 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9947 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009948 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009949
9950 /* pop the environment string. */
9951 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009952
9953 /* reset for next loop */
9954 akl = NULL;
9955 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009956 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009957 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009958
9959 alloc_error:
9960 release_hlua_function(fcn);
9961 ha_free(&akl);
9962 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9963 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009964}
9965
9966static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9967 struct act_rule *rule, char **err)
9968{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009969 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009970
Christopher Faulet280f85b2019-07-15 15:02:04 +02009971 if (px->mode == PR_MODE_HTTP) {
9972 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009973 return ACT_RET_PRS_ERR;
9974 }
9975
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009976 /* Memory for the rule. */
9977 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9978 if (!rule->arg.hlua_rule) {
9979 memprintf(err, "out of memory error");
9980 return ACT_RET_PRS_ERR;
9981 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009982
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009983 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009984 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009985
9986 /* TODO: later accept arguments. */
9987 rule->arg.hlua_rule->args = NULL;
9988
9989 /* Add applet pointer in the rule. */
9990 rule->applet.obj_type = OBJ_TYPE_APPLET;
9991 rule->applet.name = fcn->name;
9992 rule->applet.init = hlua_applet_tcp_init;
9993 rule->applet.fct = hlua_applet_tcp_fct;
9994 rule->applet.release = hlua_applet_tcp_release;
9995 rule->applet.timeout = hlua_timeout_applet;
9996
9997 return 0;
9998}
9999
10000/* This function is an LUA binding used for registering
10001 * "sample-conv" functions. It expects a converter name used
10002 * in the haproxy configuration file, and an LUA function.
10003 */
10004__LJMP static int hlua_register_service(lua_State *L)
10005{
10006 struct action_kw_list *akl;
10007 const char *name;
10008 const char *env;
10009 int ref;
10010 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010011 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010012 struct buffer *trash;
10013 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010014
10015 MAY_LJMP(check_args(L, 3, "register_service"));
10016
10017 /* First argument : converter name. */
10018 name = MAY_LJMP(luaL_checkstring(L, 1));
10019
10020 /* Second argument : environment. */
10021 env = MAY_LJMP(luaL_checkstring(L, 2));
10022
10023 /* Third argument : lua function. */
10024 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10025
Thierry Fournierf67442e2020-11-28 20:41:07 +010010026 /* Check for service already registered */
10027 trash = get_trash_chunk();
10028 chunk_printf(trash, "lua.%s", name);
10029 akw = service_find(trash->area);
10030 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010031 fcn = akw->private;
10032 if (fcn->function_ref[hlua_state_id] != -1) {
10033 ha_warning("Trying to register service 'lua.%s' more than once. "
10034 "This will become a hard error in version 2.5.\n", name);
10035 }
10036 fcn->function_ref[hlua_state_id] = ref;
10037 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010038 }
10039
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010040 /* Allocate and fill the sample fetch keyword struct. */
10041 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10042 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010043 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010044 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010045 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010046 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010047
10048 /* Fill fcn. */
10049 len = strlen("<lua.>") + strlen(name) + 1;
10050 fcn->name = calloc(1, len);
10051 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010052 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010053 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010054 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010055
10056 /* List head */
10057 akl->list.n = akl->list.p = NULL;
10058
10059 /* converter keyword. */
10060 len = strlen("lua.") + strlen(name) + 1;
10061 akl->kw[0].kw = calloc(1, len);
10062 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010063 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010064
10065 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10066
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010067 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010068 if (strcmp(env, "tcp") == 0)
10069 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010070 else if (strcmp(env, "http") == 0)
10071 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010072 else {
10073 release_hlua_function(fcn);
10074 if (akl)
10075 ha_free((char **)&(akl->kw[0].kw));
10076 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010077 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010078 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010079 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010080
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010081 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010082 akl->kw[0].private = fcn;
10083
10084 /* End of array. */
10085 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10086
10087 /* Register this new converter */
10088 service_keywords_register(akl);
10089
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010090 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010091
10092 alloc_error:
10093 release_hlua_function(fcn);
10094 ha_free(&akl);
10095 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10096 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010097}
10098
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010099/* This function initialises Lua cli handler. It copies the
10100 * arguments in the Lua stack and create channel IO objects.
10101 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010102static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010103{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010104 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010105 struct hlua *hlua;
10106 struct hlua_function *fcn;
10107 int i;
10108 const char *error;
10109
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010110 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010111 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010112
Willy Tarreaubafbe012017-11-24 17:34:44 +010010113 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010114 if (!hlua) {
10115 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010116 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010117 }
10118 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010119 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010120
10121 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010122 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010123 * applet_http. It is absolutely compatible.
10124 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010125 ctx->task = task_new_here();
10126 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010127 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010128 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010129 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010130 ctx->task->nice = 0;
10131 ctx->task->context = appctx;
10132 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010133
10134 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010135 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010136 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010137 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010138 }
10139
10140 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010141 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010142 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10143 error = lua_tostring(hlua->T, -1);
10144 else
10145 error = "critical error";
10146 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10147 goto error;
10148 }
10149
10150 /* Check stack available size. */
10151 if (!lua_checkstack(hlua->T, 2)) {
10152 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10153 goto error;
10154 }
10155
10156 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010157 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010158
10159 /* Once the arguments parsed, the CLI is like an AppletTCP,
10160 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010161 */
10162 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10163 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10164 goto error;
10165 }
10166 hlua->nargs = 1;
10167
10168 /* push keywords in the stack. */
10169 for (i = 0; *args[i]; i++) {
10170 /* Check stack available size. */
10171 if (!lua_checkstack(hlua->T, 1)) {
10172 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10173 goto error;
10174 }
10175 lua_pushstring(hlua->T, args[i]);
10176 hlua->nargs++;
10177 }
10178
10179 /* We must initialize the execution timeouts. */
10180 hlua->max_time = hlua_timeout_session;
10181
10182 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010183 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010184
10185 /* It's ok */
10186 return 0;
10187
10188 /* It's not ok. */
10189error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010190 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010191 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010192 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010193 return 1;
10194}
10195
10196static int hlua_cli_io_handler_fct(struct appctx *appctx)
10197{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010198 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010199 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010200 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010201 struct hlua_function *fcn;
10202
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010203 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010204 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010205 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010206
10207 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010208 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010209 return 1;
10210
10211 /* Execute the function. */
10212 switch (hlua_ctx_resume(hlua, 1)) {
10213
10214 /* finished. */
10215 case HLUA_E_OK:
10216 return 1;
10217
10218 /* yield. */
10219 case HLUA_E_AGAIN:
10220 /* We want write. */
10221 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010222 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010223 /* Set the timeout. */
10224 if (hlua->wake_time != TICK_ETERNITY)
10225 task_schedule(hlua->task, hlua->wake_time);
10226 return 0;
10227
10228 /* finished with error. */
10229 case HLUA_E_ERRMSG:
10230 /* Display log. */
10231 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10232 fcn->name, lua_tostring(hlua->T, -1));
10233 lua_pop(hlua->T, 1);
10234 return 1;
10235
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010236 case HLUA_E_ETMOUT:
10237 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10238 fcn->name);
10239 return 1;
10240
10241 case HLUA_E_NOMEM:
10242 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10243 fcn->name);
10244 return 1;
10245
10246 case HLUA_E_YIELD: /* unexpected */
10247 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10248 fcn->name);
10249 return 1;
10250
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010251 case HLUA_E_ERR:
10252 /* Display log. */
10253 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10254 fcn->name);
10255 return 1;
10256
10257 default:
10258 return 1;
10259 }
10260
10261 return 1;
10262}
10263
10264static void hlua_cli_io_release_fct(struct appctx *appctx)
10265{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010266 struct hlua_cli_ctx *ctx = appctx->svcctx;
10267
10268 hlua_ctx_destroy(ctx->hlua);
10269 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010270}
10271
10272/* This function is an LUA binding used for registering
10273 * new keywords in the cli. It expects a list of keywords
10274 * which are the "path". It is limited to 5 keywords. A
10275 * description of the command, a function to be executed
10276 * for the parsing and a function for io handlers.
10277 */
10278__LJMP static int hlua_register_cli(lua_State *L)
10279{
10280 struct cli_kw_list *cli_kws;
10281 const char *message;
10282 int ref_io;
10283 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010284 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010285 int index;
10286 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010287 struct buffer *trash;
10288 const char *kw[5];
10289 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010290 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010291
10292 MAY_LJMP(check_args(L, 3, "register_cli"));
10293
10294 /* First argument : an array of maximum 5 keywords. */
10295 if (!lua_istable(L, 1))
10296 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10297
10298 /* Second argument : string with contextual message. */
10299 message = MAY_LJMP(luaL_checkstring(L, 2));
10300
10301 /* Third and fourth argument : lua function. */
10302 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10303
Thierry Fournierf67442e2020-11-28 20:41:07 +010010304 /* Check for CLI service already registered */
10305 trash = get_trash_chunk();
10306 index = 0;
10307 lua_pushnil(L);
10308 memset(kw, 0, sizeof(kw));
10309 while (lua_next(L, 1) != 0) {
10310 if (index >= CLI_PREFIX_KW_NB)
10311 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10312 if (lua_type(L, -1) != LUA_TSTRING)
10313 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10314 kw[index] = lua_tostring(L, -1);
10315 if (index == 0)
10316 chunk_printf(trash, "%s", kw[index]);
10317 else
10318 chunk_appendf(trash, " %s", kw[index]);
10319 index++;
10320 lua_pop(L, 1);
10321 }
10322 cli_kw = cli_find_kw_exact((char **)kw);
10323 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010324 fcn = cli_kw->private;
10325 if (fcn->function_ref[hlua_state_id] != -1) {
10326 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10327 "This will become a hard error in version 2.5.\n", trash->area);
10328 }
10329 fcn->function_ref[hlua_state_id] = ref_io;
10330 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010331 }
10332
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010333 /* Allocate and fill the sample fetch keyword struct. */
10334 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010335 if (!cli_kws) {
10336 errmsg = "Lua out of memory error.";
10337 goto error;
10338 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010339 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010340 if (!fcn) {
10341 errmsg = "Lua out of memory error.";
10342 goto error;
10343 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010344
10345 /* Fill path. */
10346 index = 0;
10347 lua_pushnil(L);
10348 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010349 if (index >= 5) {
10350 errmsg = "1st argument must be a table with a maximum of 5 entries";
10351 goto error;
10352 }
10353 if (lua_type(L, -1) != LUA_TSTRING) {
10354 errmsg = "1st argument must be a table filled with strings";
10355 goto error;
10356 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010357 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010358 if (!cli_kws->kw[0].str_kw[index]) {
10359 errmsg = "Lua out of memory error.";
10360 goto error;
10361 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010362 index++;
10363 lua_pop(L, 1);
10364 }
10365
10366 /* Copy help message. */
10367 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010368 if (!cli_kws->kw[0].usage) {
10369 errmsg = "Lua out of memory error.";
10370 goto error;
10371 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010372
10373 /* Fill fcn io handler. */
10374 len = strlen("<lua.cli>") + 1;
10375 for (i = 0; i < index; i++)
10376 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10377 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010378 if (!fcn->name) {
10379 errmsg = "Lua out of memory error.";
10380 goto error;
10381 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010382 strncat((char *)fcn->name, "<lua.cli", len);
10383 for (i = 0; i < index; i++) {
10384 strncat((char *)fcn->name, ".", len);
10385 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10386 }
10387 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010388 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010389
10390 /* Fill last entries. */
10391 cli_kws->kw[0].private = fcn;
10392 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10393 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10394 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10395
10396 /* Register this new converter */
10397 cli_register_kw(cli_kws);
10398
10399 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010400
10401 error:
10402 release_hlua_function(fcn);
10403 if (cli_kws) {
10404 for (i = 0; i < index; i++)
10405 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10406 ha_free((char **)&(cli_kws->kw[0].usage));
10407 }
10408 ha_free(&cli_kws);
10409 WILL_LJMP(luaL_error(L, errmsg));
10410 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010411}
10412
Christopher Faulet69c581a2021-05-31 08:54:04 +020010413static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10414{
10415 struct hlua_flt_config *conf = fconf->conf;
10416 lua_State *L;
10417 int error, pos, state_id, flt_ref;
10418
10419 state_id = reg_flt_to_stack_id(conf->reg);
10420 L = hlua_states[state_id];
10421 pos = lua_gettop(L);
10422
10423 /* The filter parsing function */
10424 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10425
10426 /* Push the filter class on the stack and resolve all callbacks */
10427 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10428
10429 /* Duplicate the filter class so each filter will have its own copy */
10430 lua_newtable(L);
10431 lua_pushnil(L);
10432
10433 while (lua_next(L, pos+2)) {
10434 lua_pushvalue(L, -2);
10435 lua_insert(L, -2);
10436 lua_settable(L, -4);
10437 }
10438 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10439
10440 /* Remove the original lua filter class from the stack */
10441 lua_pop(L, 1);
10442
10443 /* Push the copy on the stack */
10444 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10445
10446 /* extra args are pushed in a table */
10447 lua_newtable(L);
10448 for (pos = 0; conf->args[pos]; pos++) {
10449 /* Check stack available size. */
10450 if (!lua_checkstack(L, 1)) {
10451 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10452 goto error;
10453 }
10454 lua_pushstring(L, conf->args[pos]);
10455 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10456 }
10457
10458 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10459 switch (error) {
10460 case LUA_OK:
10461 /* replace the filter ref */
10462 conf->ref[state_id] = flt_ref;
10463 break;
10464 case LUA_ERRRUN:
10465 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10466 goto error;
10467 case LUA_ERRMEM:
10468 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10469 goto error;
10470 case LUA_ERRERR:
10471 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10472 goto error;
10473#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10474 case LUA_ERRGCMM:
10475 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10476 goto error;
10477#endif
10478 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010479 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010480 goto error;
10481 }
10482
10483 lua_settop(L, 0);
10484 return 0;
10485
10486 error:
10487 lua_settop(L, 0);
10488 return -1;
10489}
10490
10491static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10492{
10493 struct hlua_flt_config *conf = fconf->conf;
10494 lua_State *L;
10495 int state_id;
10496
10497 if (!conf)
10498 return;
10499
10500 state_id = reg_flt_to_stack_id(conf->reg);
10501 L = hlua_states[state_id];
10502 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10503}
10504
10505static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10506{
10507 struct hlua_flt_config *conf = fconf->conf;
10508 int state_id = reg_flt_to_stack_id(conf->reg);
10509
10510 /* Rely on per-thread init for global scripts */
10511 if (!state_id)
10512 return hlua_filter_init_per_thread(px, fconf);
10513 return 0;
10514}
10515
10516static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10517{
10518
10519 if (fconf->conf) {
10520 struct hlua_flt_config *conf = fconf->conf;
10521 int state_id = reg_flt_to_stack_id(conf->reg);
10522 int pos;
10523
10524 /* Rely on per-thread deinit for global scripts */
10525 if (!state_id)
10526 hlua_filter_deinit_per_thread(px, fconf);
10527
10528 for (pos = 0; conf->args[pos]; pos++)
10529 free(conf->args[pos]);
10530 free(conf->args);
10531 }
10532 ha_free(&fconf->conf);
10533 ha_free((char **)&fconf->id);
10534 ha_free(&fconf->ops);
10535}
10536
10537static int hlua_filter_new(struct stream *s, struct filter *filter)
10538{
10539 struct hlua_flt_config *conf = FLT_CONF(filter);
10540 struct hlua_flt_ctx *flt_ctx = NULL;
10541 int ret = 1;
10542
10543 /* In the execution wrappers linked with a stream, the
10544 * Lua context can be not initialized. This behavior
10545 * permits to save performances because a systematic
10546 * Lua initialization cause 5% performances loss.
10547 */
10548 if (!s->hlua) {
10549 struct hlua *hlua;
10550
10551 hlua = pool_alloc(pool_head_hlua);
10552 if (!hlua) {
10553 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10554 conf->reg->name);
10555 ret = 0;
10556 goto end;
10557 }
10558 HLUA_INIT(hlua);
10559 s->hlua = hlua;
10560 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10561 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10562 conf->reg->name);
10563 ret = 0;
10564 goto end;
10565 }
10566 }
10567
10568 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10569 if (!flt_ctx) {
10570 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10571 conf->reg->name);
10572 ret = 0;
10573 goto end;
10574 }
10575 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10576 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10577 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10578 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10579 conf->reg->name);
10580 ret = 0;
10581 goto end;
10582 }
10583 HLUA_INIT(flt_ctx->hlua[0]);
10584 HLUA_INIT(flt_ctx->hlua[1]);
10585 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10586 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10587 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10588 conf->reg->name);
10589 ret = 0;
10590 goto end;
10591 }
10592
10593 if (!HLUA_IS_RUNNING(s->hlua)) {
10594 /* The following Lua calls can fail. */
10595 if (!SET_SAFE_LJMP(s->hlua)) {
10596 const char *error;
10597
10598 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10599 error = lua_tostring(s->hlua->T, -1);
10600 else
10601 error = "critical error";
10602 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10603 ret = 0;
10604 goto end;
10605 }
10606
10607 /* Check stack size. */
10608 if (!lua_checkstack(s->hlua->T, 1)) {
10609 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010610 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010611 ret = 0;
10612 goto end;
10613 }
10614
10615 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10616 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10617 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10618 conf->reg->name);
10619 RESET_SAFE_LJMP(s->hlua);
10620 ret = 0;
10621 goto end;
10622 }
10623 lua_insert(s->hlua->T, -2);
10624
10625 /* Push the copy on the stack */
10626 s->hlua->nargs = 1;
10627
10628 /* We must initialize the execution timeouts. */
10629 s->hlua->max_time = hlua_timeout_session;
10630
10631 /* At this point the execution is safe. */
10632 RESET_SAFE_LJMP(s->hlua);
10633 }
10634
10635 switch (hlua_ctx_resume(s->hlua, 0)) {
10636 case HLUA_E_OK:
10637 /* Nothing returned or not a table, ignore the filter for current stream */
10638 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10639 ret = 0;
10640 goto end;
10641 }
10642
10643 /* Attached the filter pointer to the ctx */
10644 lua_pushstring(s->hlua->T, "__filter");
10645 lua_pushlightuserdata(s->hlua->T, filter);
10646 lua_settable(s->hlua->T, -3);
10647
10648 /* Save a ref on the filter ctx */
10649 lua_pushvalue(s->hlua->T, 1);
10650 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10651 filter->ctx = flt_ctx;
10652 break;
10653 case HLUA_E_ERRMSG:
10654 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10655 ret = -1;
10656 goto end;
10657 case HLUA_E_ETMOUT:
10658 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10659 ret = 0;
10660 goto end;
10661 case HLUA_E_NOMEM:
10662 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10663 ret = 0;
10664 goto end;
10665 case HLUA_E_AGAIN:
10666 case HLUA_E_YIELD:
10667 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10668 " are not allowed from 'new' function.\n", conf->reg->name);
10669 ret = 0;
10670 goto end;
10671 case HLUA_E_ERR:
10672 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10673 ret = 0;
10674 goto end;
10675 default:
10676 ret = 0;
10677 goto end;
10678 }
10679
10680 end:
10681 if (s->hlua)
10682 lua_settop(s->hlua->T, 0);
10683 if (ret <= 0) {
10684 if (flt_ctx) {
10685 hlua_ctx_destroy(flt_ctx->hlua[0]);
10686 hlua_ctx_destroy(flt_ctx->hlua[1]);
10687 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10688 }
10689 }
10690 return ret;
10691}
10692
10693static void hlua_filter_delete(struct stream *s, struct filter *filter)
10694{
10695 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10696
10697 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10698 hlua_ctx_destroy(flt_ctx->hlua[0]);
10699 hlua_ctx_destroy(flt_ctx->hlua[1]);
10700 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10701 filter->ctx = NULL;
10702}
10703
Christopher Faulet9f55a502020-02-25 15:21:02 +010010704static int hlua_filter_from_payload(struct filter *filter)
10705{
10706 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10707
10708 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10709}
10710
Christopher Fauletc404f112020-02-26 15:03:09 +010010711static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10712 int dir, unsigned int flags)
10713{
10714 struct hlua *flt_hlua;
10715 struct hlua_flt_config *conf = FLT_CONF(filter);
10716 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10717 unsigned int hflags = HLUA_TXN_FLT_CTX;
10718 int ret = 1;
10719
10720 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10721 if (!flt_hlua)
10722 goto end;
10723
10724 if (!HLUA_IS_RUNNING(flt_hlua)) {
10725 int extra_idx = lua_gettop(flt_hlua->T);
10726
10727 /* The following Lua calls can fail. */
10728 if (!SET_SAFE_LJMP(flt_hlua)) {
10729 const char *error;
10730
10731 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10732 error = lua_tostring(flt_hlua->T, -1);
10733 else
10734 error = "critical error";
10735 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10736 goto end;
10737 }
10738
10739 /* Check stack size. */
10740 if (!lua_checkstack(flt_hlua->T, 3)) {
10741 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10742 RESET_SAFE_LJMP(flt_hlua);
10743 goto end;
10744 }
10745
10746 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10747 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10748 RESET_SAFE_LJMP(flt_hlua);
10749 goto end;
10750 }
10751 lua_insert(flt_hlua->T, -2);
10752
10753 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10754 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10755 RESET_SAFE_LJMP(flt_hlua);
10756 goto end;
10757 }
10758 flt_hlua->nargs = 2;
10759
10760 if (flags & HLUA_FLT_CB_ARG_CHN) {
10761 if (dir == SMP_OPT_DIR_REQ)
10762 lua_getfield(flt_hlua->T, -1, "req");
10763 else
10764 lua_getfield(flt_hlua->T, -1, "res");
10765 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10766 lua_pushstring(flt_hlua->T, "__filter");
10767 lua_pushlightuserdata(flt_hlua->T, filter);
10768 lua_settable(flt_hlua->T, -3);
10769 }
10770 flt_hlua->nargs++;
10771 }
10772 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010773 if (dir == SMP_OPT_DIR_REQ)
10774 lua_getfield(flt_hlua->T, -1, "http_req");
10775 else
10776 lua_getfield(flt_hlua->T, -1, "http_res");
10777 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10778 lua_pushstring(flt_hlua->T, "__filter");
10779 lua_pushlightuserdata(flt_hlua->T, filter);
10780 lua_settable(flt_hlua->T, -3);
10781 }
10782 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010783 }
10784
10785 /* Check stack size. */
10786 if (!lua_checkstack(flt_hlua->T, 1)) {
10787 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10788 RESET_SAFE_LJMP(flt_hlua);
10789 goto end;
10790 }
10791
10792 while (extra_idx--) {
10793 lua_pushvalue(flt_hlua->T, 1);
10794 lua_remove(flt_hlua->T, 1);
10795 flt_hlua->nargs++;
10796 }
10797
10798 /* We must initialize the execution timeouts. */
10799 flt_hlua->max_time = hlua_timeout_session;
10800
10801 /* At this point the execution is safe. */
10802 RESET_SAFE_LJMP(flt_hlua);
10803 }
10804
10805 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10806 case HLUA_E_OK:
10807 /* Catch the return value if it required */
10808 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10809 ret = lua_tointeger(flt_hlua->T, -1);
10810 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10811 }
10812
10813 /* Set timeout in the required channel. */
10814 if (flt_hlua->wake_time != TICK_ETERNITY) {
10815 if (dir == SMP_OPT_DIR_REQ)
10816 s->req.analyse_exp = flt_hlua->wake_time;
10817 else
10818 s->res.analyse_exp = flt_hlua->wake_time;
10819 }
10820 break;
10821 case HLUA_E_AGAIN:
10822 /* Set timeout in the required channel. */
10823 if (flt_hlua->wake_time != TICK_ETERNITY) {
10824 if (dir == SMP_OPT_DIR_REQ)
10825 s->req.analyse_exp = flt_hlua->wake_time;
10826 else
10827 s->res.analyse_exp = flt_hlua->wake_time;
10828 }
10829 /* Some actions can be wake up when a "write" event
10830 * is detected on a response channel. This is useful
10831 * only for actions targeted on the requests.
10832 */
10833 if (HLUA_IS_WAKERESWR(flt_hlua))
10834 s->res.flags |= CF_WAKE_WRITE;
10835 if (HLUA_IS_WAKEREQWR(flt_hlua))
10836 s->req.flags |= CF_WAKE_WRITE;
10837 ret = 0;
10838 goto end;
10839 case HLUA_E_ERRMSG:
10840 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10841 ret = -1;
10842 goto end;
10843 case HLUA_E_ETMOUT:
10844 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10845 goto end;
10846 case HLUA_E_NOMEM:
10847 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10848 goto end;
10849 case HLUA_E_YIELD:
10850 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10851 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10852 goto end;
10853 case HLUA_E_ERR:
10854 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10855 goto end;
10856 default:
10857 goto end;
10858 }
10859
10860
10861 end:
10862 return ret;
10863}
10864
10865static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10866{
10867 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10868
10869 flt_ctx->flags = 0;
10870 return hlua_filter_callback(s, filter, "start_analyze",
10871 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10872 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10873}
10874
10875static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10876{
10877 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10878
10879 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10880 return hlua_filter_callback(s, filter, "end_analyze",
10881 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10882 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10883}
10884
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010885static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10886{
10887 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10888
10889 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10890 return hlua_filter_callback(s, filter, "http_headers",
10891 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10892 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10893}
10894
10895static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10896 unsigned int offset, unsigned int len)
10897{
10898 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10899 struct hlua *flt_hlua;
10900 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10901 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10902 int ret;
10903
10904 flt_hlua = flt_ctx->hlua[idx];
10905 flt_ctx->cur_off[idx] = offset;
10906 flt_ctx->cur_len[idx] = len;
10907 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10908 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10909 if (ret != -1) {
10910 ret = flt_ctx->cur_len[idx];
10911 if (lua_gettop(flt_hlua->T) > 0) {
10912 ret = lua_tointeger(flt_hlua->T, -1);
10913 if (ret > flt_ctx->cur_len[idx])
10914 ret = flt_ctx->cur_len[idx];
10915 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10916 }
10917 }
10918 return ret;
10919}
10920
10921static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10922{
10923 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10924
10925 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10926 return hlua_filter_callback(s, filter, "http_end",
10927 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10928 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10929}
10930
Christopher Fauletc404f112020-02-26 15:03:09 +010010931static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10932 unsigned int offset, unsigned int len)
10933{
10934 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10935 struct hlua *flt_hlua;
10936 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10937 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10938 int ret;
10939
10940 flt_hlua = flt_ctx->hlua[idx];
10941 flt_ctx->cur_off[idx] = offset;
10942 flt_ctx->cur_len[idx] = len;
10943 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10944 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10945 if (ret != -1) {
10946 ret = flt_ctx->cur_len[idx];
10947 if (lua_gettop(flt_hlua->T) > 0) {
10948 ret = lua_tointeger(flt_hlua->T, -1);
10949 if (ret > flt_ctx->cur_len[idx])
10950 ret = flt_ctx->cur_len[idx];
10951 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10952 }
10953 }
10954 return ret;
10955}
10956
Christopher Faulet69c581a2021-05-31 08:54:04 +020010957static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10958 struct flt_conf *fconf, char **err, void *private)
10959{
10960 struct hlua_reg_filter *reg_flt = private;
10961 lua_State *L;
10962 struct hlua_flt_config *conf = NULL;
10963 const char *flt_id = NULL;
10964 int state_id, pos, flt_flags = 0;
10965 struct flt_ops *hlua_flt_ops = NULL;
10966
10967 state_id = reg_flt_to_stack_id(reg_flt);
10968 L = hlua_states[state_id];
10969
10970 /* Initialize the filter ops with default callbacks */
10971 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010972 if (!hlua_flt_ops)
10973 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010974 hlua_flt_ops->init = hlua_filter_init;
10975 hlua_flt_ops->deinit = hlua_filter_deinit;
10976 if (state_id) {
10977 /* Set per-thread callback if script is loaded per-thread */
10978 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10979 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10980 }
10981 hlua_flt_ops->attach = hlua_filter_new;
10982 hlua_flt_ops->detach = hlua_filter_delete;
10983
10984 /* Push the filter class on the stack and resolve all callbacks */
10985 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10986
Christopher Fauletc404f112020-02-26 15:03:09 +010010987 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10988 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10989 lua_pop(L, 1);
10990 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10991 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10992 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010993 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10994 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10995 lua_pop(L, 1);
10996 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10997 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10998 lua_pop(L, 1);
10999 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11000 hlua_flt_ops->http_end = hlua_filter_http_end;
11001 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011002 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11003 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11004 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011005
11006 /* Get id and flags of the filter class */
11007 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11008 flt_id = lua_tostring(L, -1);
11009 lua_pop(L, 1);
11010 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11011 flt_flags = lua_tointeger(L, -1);
11012 lua_pop(L, 1);
11013
11014 /* Create the filter config */
11015 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011016 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011017 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011018 conf->reg = reg_flt;
11019
11020 /* duplicate args */
11021 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11022 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011023 if (!conf->args)
11024 goto error;
11025 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011026 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011027 if (!conf->args[pos])
11028 goto error;
11029 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011030 conf->args[pos] = NULL;
11031 *cur_arg += pos + 1;
11032
Christopher Fauletc86bb872021-08-13 08:33:57 +020011033 if (flt_id) {
11034 fconf->id = strdup(flt_id);
11035 if (!fconf->id)
11036 goto error;
11037 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011038 fconf->flags = flt_flags;
11039 fconf->conf = conf;
11040 fconf->ops = hlua_flt_ops;
11041
11042 lua_settop(L, 0);
11043 return 0;
11044
11045 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011046 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011047 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011048 if (conf && conf->args) {
11049 for (pos = 0; conf->args[pos]; pos++)
11050 free(conf->args[pos]);
11051 free(conf->args);
11052 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011053 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011054 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011055 lua_settop(L, 0);
11056 return -1;
11057}
11058
Christopher Fauletc404f112020-02-26 15:03:09 +010011059__LJMP static int hlua_register_data_filter(lua_State *L)
11060{
11061 struct filter *filter;
11062 struct channel *chn;
11063
11064 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11065 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11066 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11067
11068 lua_getfield(L, 1, "__filter");
11069 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11070 filter = lua_touserdata (L, -1);
11071 lua_pop(L, 1);
11072
11073 register_data_filter(chn_strm(chn), chn, filter);
11074 return 1;
11075}
11076
11077__LJMP static int hlua_unregister_data_filter(lua_State *L)
11078{
11079 struct filter *filter;
11080 struct channel *chn;
11081
11082 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11083 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11084 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11085
11086 lua_getfield(L, 1, "__filter");
11087 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11088 filter = lua_touserdata (L, -1);
11089 lua_pop(L, 1);
11090
11091 unregister_data_filter(chn_strm(chn), chn, filter);
11092 return 1;
11093}
11094
Christopher Faulet69c581a2021-05-31 08:54:04 +020011095/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011096 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011097 * parse configuration arguments.
11098 */
11099__LJMP static int hlua_register_filter(lua_State *L)
11100{
11101 struct buffer *trash;
11102 struct flt_kw_list *fkl;
11103 struct flt_kw *fkw;
11104 const char *name;
11105 struct hlua_reg_filter *reg_flt= NULL;
11106 int flt_ref, fun_ref;
11107 int len;
11108
11109 MAY_LJMP(check_args(L, 3, "register_filter"));
11110
11111 /* First argument : filter name. */
11112 name = MAY_LJMP(luaL_checkstring(L, 1));
11113
11114 /* Second argument : The filter class */
11115 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11116
11117 /* Third argument : lua function. */
11118 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11119
11120 trash = get_trash_chunk();
11121 chunk_printf(trash, "lua.%s", name);
11122 fkw = flt_find_kw(trash->area);
11123 if (fkw != NULL) {
11124 reg_flt = fkw->private;
11125 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11126 ha_warning("Trying to register filter 'lua.%s' more than once. "
11127 "This will become a hard error in version 2.5.\n", name);
11128 }
11129 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11130 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11131 return 0;
11132 }
11133
11134 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11135 if (!fkl)
11136 goto alloc_error;
11137 fkl->scope = "HLUA";
11138
11139 reg_flt = new_hlua_reg_filter(name);
11140 if (!reg_flt)
11141 goto alloc_error;
11142
11143 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11144 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11145
11146 /* The filter keyword */
11147 len = strlen("lua.") + strlen(name) + 1;
11148 fkl->kw[0].kw = calloc(1, len);
11149 if (!fkl->kw[0].kw)
11150 goto alloc_error;
11151
11152 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11153
11154 fkl->kw[0].parse = hlua_filter_parse_fct;
11155 fkl->kw[0].private = reg_flt;
11156 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11157
11158 /* Register this new filter */
11159 flt_register_keywords(fkl);
11160
11161 return 0;
11162
11163 alloc_error:
11164 release_hlua_reg_filter(reg_flt);
11165 ha_free(&fkl);
11166 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11167 return 0; /* Never reached */
11168}
11169
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011170static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011171 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011172 char **err, unsigned int *timeout)
11173{
11174 const char *error;
11175
11176 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011177 if (error == PARSE_TIME_OVER) {
11178 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11179 args[1], args[0]);
11180 return -1;
11181 }
11182 else if (error == PARSE_TIME_UNDER) {
11183 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11184 args[1], args[0]);
11185 return -1;
11186 }
11187 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011188 memprintf(err, "%s: invalid timeout", args[0]);
11189 return -1;
11190 }
11191 return 0;
11192}
11193
11194static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011195 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011196 char **err)
11197{
11198 return hlua_read_timeout(args, section_type, curpx, defpx,
11199 file, line, err, &hlua_timeout_session);
11200}
11201
11202static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011203 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011204 char **err)
11205{
11206 return hlua_read_timeout(args, section_type, curpx, defpx,
11207 file, line, err, &hlua_timeout_task);
11208}
11209
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011210static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011211 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011212 char **err)
11213{
11214 return hlua_read_timeout(args, section_type, curpx, defpx,
11215 file, line, err, &hlua_timeout_applet);
11216}
11217
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011218static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011219 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011220 char **err)
11221{
11222 char *error;
11223
11224 hlua_nb_instruction = strtoll(args[1], &error, 10);
11225 if (*error != '\0') {
11226 memprintf(err, "%s: invalid number", args[0]);
11227 return -1;
11228 }
11229 return 0;
11230}
11231
Willy Tarreau32f61e22015-03-18 17:54:59 +010011232static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011233 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011234 char **err)
11235{
11236 char *error;
11237
11238 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011239 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011240 return -1;
11241 }
11242 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11243 if (*error != '\0') {
11244 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11245 return -1;
11246 }
11247 return 0;
11248}
11249
11250
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011251/* This function is called by the main configuration key "lua-load". It loads and
11252 * execute an lua file during the parsing of the HAProxy configuration file. It is
11253 * the main lua entry point.
11254 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011255 * This function runs with the HAProxy keywords API. It returns -1 if an error
11256 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011257 *
11258 * In some error case, LUA set an error message in top of the stack. This function
11259 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011260 *
11261 * This function can fail with an abort() due to an Lua critical error.
11262 * We are in the configuration parsing process of HAProxy, this abort() is
11263 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011264 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011265static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011266{
11267 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011268 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011269
11270 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011271 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011272 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011273 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011274 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011275 return -1;
11276 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011277
11278 /* Push args in the Lua stack, except the first one which is the filename */
11279 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011280 /* Check stack size. */
11281 if (!lua_checkstack(L, 1)) {
11282 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11283 return -1;
11284 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011285 lua_pushstring(L, args[nargs]);
11286 }
11287 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011288
11289 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011290 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011291 switch (error) {
11292 case LUA_OK:
11293 break;
11294 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011295 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011296 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011297 return -1;
11298 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011299 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011300 return -1;
11301 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011302 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011303 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011304 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011305#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011306 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011307 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011308 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011309 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011310#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011311 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011312 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011313 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011314 return -1;
11315 }
11316
11317 return 0;
11318}
11319
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011320static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011321 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011322 char **err)
11323{
11324 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011325 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011326 return -1;
11327 }
11328
Thierry Fournier59f11be2020-11-29 00:37:41 +010011329 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011330 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011331 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011332 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011333}
11334
Thierry Fournier59f11be2020-11-29 00:37:41 +010011335static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011336 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011337 char **err)
11338{
11339 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011340 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011341
11342 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011343 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011344 return -1;
11345 }
11346
11347 if (per_thread_load == NULL) {
11348 /* allocate the first entry large enough to store the final NULL */
11349 per_thread_load = calloc(1, sizeof(*per_thread_load));
11350 if (per_thread_load == NULL) {
11351 memprintf(err, "out of memory error");
11352 return -1;
11353 }
11354 }
11355
11356 /* count used entries */
11357 for (len = 0; per_thread_load[len] != NULL; len++)
11358 ;
11359
11360 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11361 if (per_thread_load == NULL) {
11362 memprintf(err, "out of memory error");
11363 return -1;
11364 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011365 per_thread_load[len + 1] = NULL;
11366
Thierry Fournierae6b5682022-09-19 09:04:16 +020011367 /* count args excepting the first, allocate array and copy args */
11368 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011369 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011370 if (per_thread_load[len] == NULL) {
11371 memprintf(err, "out of memory error");
11372 return -1;
11373 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011374 for (i = 1; *(args[i]) != 0; i++) {
11375 per_thread_load[len][i - 1] = strdup(args[i]);
11376 if (per_thread_load[len][i - 1] == NULL) {
11377 memprintf(err, "out of memory error");
11378 return -1;
11379 }
11380 }
11381 per_thread_load[len][i - 1] = strdup("");
11382 if (per_thread_load[len][i - 1] == NULL) {
11383 memprintf(err, "out of memory error");
11384 return -1;
11385 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011386
11387 /* loading for thread 1 only */
11388 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011389 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011390 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011391}
11392
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011393/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11394 * in the given <ctx>.
11395 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011396static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011397{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011398 lua_getglobal(L, "package"); /* push package variable */
11399 lua_pushstring(L, path); /* push given path */
11400 lua_pushstring(L, ";"); /* push semicolon */
11401 lua_getfield(L, -3, type); /* push old path */
11402 lua_concat(L, 3); /* concatenate to new path */
11403 lua_setfield(L, -2, type); /* store new path */
11404 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011405
11406 return 0;
11407}
11408
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011409static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011410 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011411 char **err)
11412{
11413 char *path;
11414 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011415 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011416 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011417
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011418 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011419 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011420 }
11421
11422 if (!(*args[1])) {
11423 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011424 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011425 }
11426 path = args[1];
11427
11428 if (*args[2]) {
11429 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11430 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011431 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011432 }
11433 type = args[2];
11434 }
11435
Thierry Fournier59f11be2020-11-29 00:37:41 +010011436 p = calloc(1, sizeof(*p));
11437 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011438 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011439 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011440 }
11441 p->path = strdup(path);
11442 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011443 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011444 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011445 }
11446 p->type = strdup(type);
11447 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011448 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011449 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011450 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011451 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011452
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011453 /* Handle the global state and the per-thread state for the first
11454 * thread. The remaining threads will be initialized based on
11455 * prepend_path_list.
11456 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011457 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011458 lua_State *L = hlua_states[i];
11459 const char *error;
11460
11461 if (setjmp(safe_ljmp_env) != 0) {
11462 lua_atpanic(L, hlua_panic_safe);
11463 if (lua_type(L, -1) == LUA_TSTRING)
11464 error = lua_tostring(L, -1);
11465 else
11466 error = "critical error";
11467 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11468 exit(1);
11469 } else {
11470 lua_atpanic(L, hlua_panic_ljmp);
11471 }
11472
11473 hlua_prepend_path(L, type, path);
11474
11475 lua_atpanic(L, hlua_panic_safe);
11476 }
11477
Thierry Fournier59f11be2020-11-29 00:37:41 +010011478 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011479
11480err2:
11481 free(p->type);
11482 free(p->path);
11483err:
11484 free(p);
11485 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011486}
11487
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011488/* configuration keywords declaration */
11489static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011490 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011491 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011492 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011493 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11494 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011495 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011496 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011497 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011498 { 0, NULL, NULL },
11499}};
11500
Willy Tarreau0108d902018-11-25 19:14:37 +010011501INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11502
William Lallemand52139182022-03-30 15:05:42 +020011503#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011504
William Lallemand30fcca12022-03-30 12:03:12 +020011505/*
11506 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11507 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11508 * difference is that the yield in lua and for the CLI is not handled the same
11509 * way.
11510 */
11511__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11512{
11513 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11514 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11515 struct ckch_inst *ckchi = *lua_ckchi;
11516 struct ckch_store *old_ckchs = lua_ckchs[0];
11517 struct ckch_store *new_ckchs = lua_ckchs[1];
11518 struct hlua *hlua;
11519 char *err = NULL;
11520 int y = 1;
11521
11522 hlua = hlua_gethlua(L);
11523
11524 /* get the first ckchi to copy */
11525 if (ckchi == NULL)
11526 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11527
11528 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11529 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11530 struct ckch_inst *new_inst;
11531
11532 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11533 if (y % 10 == 0) {
11534
11535 *lua_ckchi = ckchi;
11536
11537 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11538 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11539 }
11540
11541 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11542 goto error;
11543
11544 /* link the new ckch_inst to the duplicate */
11545 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11546 y++;
11547 }
11548
11549 /* The generation is finished, we can insert everything */
11550 ckch_store_replace(old_ckchs, new_ckchs);
11551
11552 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11553
11554 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11555
11556 return 0;
11557
11558error:
11559 ckch_store_free(new_ckchs);
11560 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11561 WILL_LJMP(luaL_error(L, "%s", err));
11562 free(err);
11563
11564 return 0;
11565}
11566
11567/*
11568 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11569 * from the table in parameter.
11570 *
11571 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11572 * means it does not need to have a transaction since everything is done in the
11573 * same function.
11574 *
11575 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11576 *
11577 */
11578__LJMP static int hlua_ckch_set(lua_State *L)
11579{
11580 struct hlua *hlua;
11581 struct ckch_inst **lua_ckchi;
11582 struct ckch_store **lua_ckchs;
11583 struct ckch_store *old_ckchs = NULL;
11584 struct ckch_store *new_ckchs = NULL;
11585 int errcode = 0;
11586 char *err = NULL;
11587 struct cert_exts *cert_ext = NULL;
11588 char *filename;
11589 struct cert_key_and_chain *ckch;
11590 int ret;
11591
11592 if (lua_type(L, -1) != LUA_TTABLE)
11593 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11594
11595 hlua = hlua_gethlua(L);
11596
11597 /* FIXME: this should not return an error but should come back later */
11598 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11599 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11600
11601 ret = lua_getfield(L, -1, "filename");
11602 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011603 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011604 errcode |= ERR_ALERT | ERR_FATAL;
11605 goto end;
11606 }
11607 filename = (char *)lua_tostring(L, -1);
11608
11609
11610 /* look for the filename in the tree */
11611 old_ckchs = ckchs_lookup(filename);
11612 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011613 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011614 errcode |= ERR_ALERT | ERR_FATAL;
11615 goto end;
11616 }
11617 /* TODO: handle extra_files_noext */
11618
11619 new_ckchs = ckchs_dup(old_ckchs);
11620 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011621 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011622 errcode |= ERR_ALERT | ERR_FATAL;
11623 goto end;
11624 }
11625
11626 ckch = new_ckchs->ckch;
11627
11628 /* loop on the field in the table, which have the same name as the
11629 * possible extensions of files */
11630 lua_pushnil(L);
11631 while (lua_next(L, 1)) {
11632 int i;
11633 const char *field = lua_tostring(L, -2);
11634 char *payload = (char *)lua_tostring(L, -1);
11635
11636 if (!field || strcmp(field, "filename") == 0) {
11637 lua_pop(L, 1);
11638 continue;
11639 }
11640
11641 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11642 if (strcmp(field, cert_exts[i].ext) == 0) {
11643 cert_ext = &cert_exts[i];
11644 break;
11645 }
11646 }
11647
11648 /* this is the default type, the field is not supported */
11649 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011650 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011651 errcode |= ERR_ALERT | ERR_FATAL;
11652 goto end;
11653 }
11654
11655 /* appply the change on the duplicate */
William Lallemandd8c195a2022-05-26 11:20:13 +020011656 if (cert_ext->load(filename, payload, ckch, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011657 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011658 errcode |= ERR_ALERT | ERR_FATAL;
11659 goto end;
11660 }
11661 lua_pop(L, 1);
11662 }
11663
11664 /* store the pointers on the lua stack */
11665 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11666 lua_ckchs[0] = old_ckchs;
11667 lua_ckchs[1] = new_ckchs;
11668 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11669 *lua_ckchi = NULL;
11670
11671 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11672 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11673
11674end:
11675 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11676
11677 if (errcode & ERR_CODE) {
11678 ckch_store_free(new_ckchs);
11679 WILL_LJMP(luaL_error(L, "%s", err));
11680 }
11681 free(err);
11682
11683 return 0;
11684}
11685
William Lallemand52139182022-03-30 15:05:42 +020011686#else
11687
11688__LJMP static int hlua_ckch_set(lua_State *L)
11689{
11690 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11691
11692 return 0;
11693}
11694#endif /* ! USE_OPENSSL */
11695
11696
11697
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011698/* This function can fail with an abort() due to an Lua critical error.
11699 * We are in the initialisation process of HAProxy, this abort() is
11700 * tolerated.
11701 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011702int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011703{
11704 struct hlua_init_function *init;
11705 const char *msg;
11706 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011707 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011708 const char *kind;
11709 const char *trace;
11710 int return_status = 1;
11711#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11712 int nres;
11713#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011714
Willy Tarreaucdb53462020-12-02 12:12:00 +010011715 /* disable memory limit checks if limit is not set */
11716 if (!hlua_global_allocator.limit)
11717 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11718
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011719 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011720 if (setjmp(safe_ljmp_env) != 0) {
11721 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011722 if (lua_type(L, -1) == LUA_TSTRING)
11723 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011724 else
11725 error = "critical error";
11726 fprintf(stderr, "Lua post-init: %s.\n", error);
11727 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011728 } else {
11729 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011730 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011731
Thierry Fournierb8cef172020-11-28 15:37:17 +010011732 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011733
Thierry Fournierc7492592020-11-28 23:57:24 +010011734 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011735 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011736
11737#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011738 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011739#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011740 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011741#endif
11742 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011743 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011744
11745 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011746 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011747 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011748
11749 case LUA_ERRERR:
11750 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011751 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011752 case LUA_ERRRUN:
11753 if (!kind)
11754 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011755 msg = lua_tostring(L, -1);
11756 lua_settop(L, 0); /* Empty the stack. */
11757 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011758 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011759 if (msg)
11760 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11761 else
11762 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11763 return_status = 0;
11764 break;
11765
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011766 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011767 /* Unknown error */
11768 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011769 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011770 case LUA_YIELD:
11771 /* yield is not configured at this step, this state doesn't happen */
11772 if (!kind)
11773 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011774 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011775 case LUA_ERRMEM:
11776 if (!kind)
11777 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011778 lua_settop(L, 0);
11779 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011780 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011781 ha_alert("Lua init: %s: %s\n", kind, trace);
11782 return_status = 0;
11783 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011784 }
Thierry Fournier670db242020-11-28 10:49:59 +010011785 if (!return_status)
11786 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011787 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011788
11789 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011790 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011791}
11792
Thierry Fournierb8cef172020-11-28 15:37:17 +010011793int hlua_post_init()
11794{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011795 int ret;
11796 int i;
11797 int errors;
11798 char *err = NULL;
11799 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011800 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011801
Willy Tarreaub1310492021-08-30 09:35:18 +020011802#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011803 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011804 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011805 int saved_used_backed = global.ssl_used_backend;
11806 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011807 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011808 global.ssl_used_backend = saved_used_backed;
11809 }
11810#endif
11811
Thierry Fournierc7492592020-11-28 23:57:24 +010011812 /* Perform post init of common thread */
11813 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011814 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011815 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11816 if (ret == 0)
11817 return 0;
11818
11819 /* init remaining lua states and load files */
11820 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11821
11822 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011823 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011824
11825 /* Init lua state */
11826 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11827
11828 /* Load lua files */
11829 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11830 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11831 if (ret != 0) {
11832 ha_alert("Lua init: %s\n", err);
11833 return 0;
11834 }
11835 }
11836 }
11837
11838 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011839 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011840
11841 /* Execute post init for all states */
11842 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11843
11844 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011845 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011846
11847 /* run post init */
11848 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11849 if (ret == 0)
11850 return 0;
11851 }
11852
11853 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011854 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011855
11856 /* control functions registering. Each function must have:
11857 * - only the function_ref[0] set positive and all other to -1
11858 * - only the function_ref[0] set to -1 and all other positive
11859 * This ensure a same reference is not used both in shared
11860 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011861 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011862 * complicated to found for the end user.
11863 */
11864 errors = 0;
11865 list_for_each_entry(fcn, &referenced_functions, l) {
11866 ret = 0;
11867 for (i = 1; i < global.nbthread + 1; i++) {
11868 if (fcn->function_ref[i] == -1)
11869 ret--;
11870 else
11871 ret++;
11872 }
11873 if (abs(ret) != global.nbthread) {
11874 ha_alert("Lua function '%s' is not referenced in all thread. "
11875 "Expect function in all thread or in none thread.\n", fcn->name);
11876 errors++;
11877 continue;
11878 }
11879
11880 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011881 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11882 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011883 "exclusive.\n", fcn->name);
11884 errors++;
11885 }
11886 }
11887
Christopher Faulet69c581a2021-05-31 08:54:04 +020011888 /* Do the same with registered filters */
11889 list_for_each_entry(reg_flt, &referenced_filters, l) {
11890 ret = 0;
11891 for (i = 1; i < global.nbthread + 1; i++) {
11892 if (reg_flt->flt_ref[i] == -1)
11893 ret--;
11894 else
11895 ret++;
11896 }
11897 if (abs(ret) != global.nbthread) {
11898 ha_alert("Lua filter '%s' is not referenced in all thread. "
11899 "Expect function in all thread or in none thread.\n", reg_flt->name);
11900 errors++;
11901 continue;
11902 }
11903
11904 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11905 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11906 "and per-thread Lua context (through lua-load-per-thread). these two context "
11907 "exclusive.\n", fcn->name);
11908 errors++;
11909 }
11910 }
11911
11912
Thierry Fournier59f11be2020-11-29 00:37:41 +010011913 if (errors > 0)
11914 return 0;
11915
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011916 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011917 * -1 in order to have probably a segfault if someone use it
11918 */
11919 hlua_state_id = -1;
11920
11921 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011922}
11923
Willy Tarreau32f61e22015-03-18 17:54:59 +010011924/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11925 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11926 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011927 * allocation. <nsize> is the requested new size. A new allocation is
11928 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011929 * zero. This one verifies that the limits are respected but is optimized
11930 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011931 *
11932 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11933 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11934 * that and will simply allocate zero as if it were the result of malloc(0),
11935 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11936 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011937 */
11938static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11939{
11940 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011941 size_t limit, old, new;
11942
11943 /* a limit of ~0 means unlimited and boot complete, so there's no need
11944 * for accounting anymore.
11945 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011946 if (likely(~zone->limit == 0)) {
11947 if (!nsize)
11948 ha_free(&ptr);
11949 else
11950 ptr = realloc(ptr, nsize);
11951 return ptr;
11952 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011953
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011954 if (!ptr)
11955 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011956
Willy Tarreaucdb53462020-12-02 12:12:00 +010011957 /* enforce strict limits across all threads */
11958 limit = zone->limit;
11959 old = _HA_ATOMIC_LOAD(&zone->allocated);
11960 do {
11961 new = old + nsize - osize;
11962 if (unlikely(nsize && limit && new > limit))
11963 return NULL;
11964 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011965
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011966 if (!nsize)
11967 ha_free(&ptr);
11968 else
11969 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011970
11971 if (unlikely(!ptr && nsize)) // failed
11972 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11973
11974 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011975 return ptr;
11976}
11977
Thierry Fournierecb83c22020-11-28 15:49:44 +010011978/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011979 * We are in the initialisation process of HAProxy, this abort() is
11980 * tolerated.
11981 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011982lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011983{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011984 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011985 int idx;
11986 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011987 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011988 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011989 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011990 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011991 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011992 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011993
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011994 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011995 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011996
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011997 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011998 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011999 *context = NULL;
12000
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012001 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012002 * the Lua function can fail with an abort. We are in the initialisation
12003 * process of HAProxy, this abort() is tolerated.
12004 */
12005
Thierry Fournier3c539322020-11-28 16:05:05 +010012006 /* Call post initialisation function in safe environment. */
12007 if (setjmp(safe_ljmp_env) != 0) {
12008 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012009 if (lua_type(L, -1) == LUA_TSTRING)
12010 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012011 else
12012 error_msg = "critical error";
12013 fprintf(stderr, "Lua init: %s.\n", error_msg);
12014 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012015 } else {
12016 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012017 }
12018
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012019 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012020 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012021#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12022#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12023#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012024 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012025#endif
12026#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012027 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012028#endif
12029#undef HLUA_PREPEND_PATH_TOSTRING
12030#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012031
Thierry Fournier59f11be2020-11-29 00:37:41 +010012032 /* Apply configured prepend path */
12033 list_for_each_entry(pp, &prepend_path_list, l)
12034 hlua_prepend_path(L, pp->type, pp->path);
12035
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012036 /*
12037 *
12038 * Create "core" object.
12039 *
12040 */
12041
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012042 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012043 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012044
Thierry Fournierecb83c22020-11-28 15:49:44 +010012045 /* set the thread id */
12046 hlua_class_const_int(L, "thread", thread_num);
12047
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012048 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012049 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012050 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012051
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012052 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012053 hlua_class_function(L, "register_init", hlua_register_init);
12054 hlua_class_function(L, "register_task", hlua_register_task);
12055 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12056 hlua_class_function(L, "register_converters", hlua_register_converters);
12057 hlua_class_function(L, "register_action", hlua_register_action);
12058 hlua_class_function(L, "register_service", hlua_register_service);
12059 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012060 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012061 hlua_class_function(L, "yield", hlua_yield);
12062 hlua_class_function(L, "set_nice", hlua_set_nice);
12063 hlua_class_function(L, "sleep", hlua_sleep);
12064 hlua_class_function(L, "msleep", hlua_msleep);
12065 hlua_class_function(L, "add_acl", hlua_add_acl);
12066 hlua_class_function(L, "del_acl", hlua_del_acl);
12067 hlua_class_function(L, "set_map", hlua_set_map);
12068 hlua_class_function(L, "del_map", hlua_del_map);
12069 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012070 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012071 hlua_class_function(L, "log", hlua_log);
12072 hlua_class_function(L, "Debug", hlua_log_debug);
12073 hlua_class_function(L, "Info", hlua_log_info);
12074 hlua_class_function(L, "Warning", hlua_log_warning);
12075 hlua_class_function(L, "Alert", hlua_log_alert);
12076 hlua_class_function(L, "done", hlua_done);
12077 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012078
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012079 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012080
12081 /*
12082 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012083 * Create "act" object.
12084 *
12085 */
12086
12087 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012088 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012089
12090 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012091 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12092 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12093 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12094 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12095 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12096 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12097 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12098 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012099
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012100 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012101
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012102 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012103
12104 /*
12105 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012106 * Create "Filter" object.
12107 *
12108 */
12109
12110 /* This table entry is the object "filter" base. */
12111 lua_newtable(L);
12112
12113 /* push flags and constants */
12114 hlua_class_const_int(L, "CONTINUE", 1);
12115 hlua_class_const_int(L, "WAIT", 0);
12116 hlua_class_const_int(L, "ERROR", -1);
12117
12118 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12119
Christopher Fauletc404f112020-02-26 15:03:09 +010012120 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12121 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12122 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12123
Christopher Faulet69c581a2021-05-31 08:54:04 +020012124 lua_setglobal(L, "filter");
12125
12126 /*
12127 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012128 * Register class Map
12129 *
12130 */
12131
12132 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012133 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012134
12135 /* register pattern types. */
12136 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012137 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012138 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012139 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012140 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012141 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012142
12143 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012144 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012145
12146 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012147 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012148
Ilya Shipitsind4259502020-04-08 01:07:56 +050012149 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012150 lua_pushstring(L, "__index");
12151 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012152
12153 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012154 hlua_class_function(L, "lookup", hlua_map_lookup);
12155 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012156
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012157 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012158
Thierry Fournier45e78d72016-02-19 18:34:46 +010012159 /* Register previous table in the registry with reference and named entry.
12160 * The function hlua_register_metatable() pops the stack, so we
12161 * previously create a copy of the table.
12162 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012163 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12164 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012165
12166 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012167 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012168
12169 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012170 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012171
12172 /*
12173 *
William Lallemand30fcca12022-03-30 12:03:12 +020012174 * Register "CertCache" class
12175 *
12176 */
12177
12178 /* Create and fill the metatable. */
12179 lua_newtable(L);
12180 /* Register */
12181 hlua_class_function(L, "set", hlua_ckch_set);
12182 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12183
12184 /*
12185 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012186 * Register class Channel
12187 *
12188 */
12189
12190 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012191 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012192
Ilya Shipitsind4259502020-04-08 01:07:56 +050012193 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012194 lua_pushstring(L, "__index");
12195 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012196
12197 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012198 hlua_class_function(L, "data", hlua_channel_get_data);
12199 hlua_class_function(L, "line", hlua_channel_get_line);
12200 hlua_class_function(L, "set", hlua_channel_set_data);
12201 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012202 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012203 hlua_class_function(L, "prepend", hlua_channel_prepend);
12204 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012205 hlua_class_function(L, "send", hlua_channel_send);
12206 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012207 hlua_class_function(L, "input", hlua_channel_get_in_len);
12208 hlua_class_function(L, "output", hlua_channel_get_out_len);
12209 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012210 hlua_class_function(L, "is_full", hlua_channel_is_full);
12211 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012212
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012213 /* Deprecated API */
12214 hlua_class_function(L, "get", hlua_channel_get);
12215 hlua_class_function(L, "dup", hlua_channel_dup);
12216 hlua_class_function(L, "getline", hlua_channel_getline);
12217 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12218 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12219
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012220 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012221
12222 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012223 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012224
12225 /*
12226 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012227 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012228 *
12229 */
12230
12231 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012232 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012233
Ilya Shipitsind4259502020-04-08 01:07:56 +050012234 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012235 lua_pushstring(L, "__index");
12236 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012237
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012238 /* Browse existing fetches and create the associated
12239 * object method.
12240 */
12241 sf = NULL;
12242 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012243 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12244 * by an underscore.
12245 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012246 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012247 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012248 if (*p == '.' || *p == '-' || *p == '+')
12249 *p = '_';
12250
12251 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012252 lua_pushstring(L, trash.area);
12253 lua_pushlightuserdata(L, sf);
12254 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12255 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012256 }
12257
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012258 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012259
12260 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012261 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012262
12263 /*
12264 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012265 * Register class Converters
12266 *
12267 */
12268
12269 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012270 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012271
12272 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012273 lua_pushstring(L, "__index");
12274 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012275
12276 /* Browse existing converters and create the associated
12277 * object method.
12278 */
12279 sc = NULL;
12280 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012281 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12282 * by an underscore.
12283 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012284 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012285 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012286 if (*p == '.' || *p == '-' || *p == '+')
12287 *p = '_';
12288
12289 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012290 lua_pushstring(L, trash.area);
12291 lua_pushlightuserdata(L, sc);
12292 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12293 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012294 }
12295
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012296 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012297
12298 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012299 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012300
12301 /*
12302 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012303 * Register class HTTP
12304 *
12305 */
12306
12307 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012308 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012309
Ilya Shipitsind4259502020-04-08 01:07:56 +050012310 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012311 lua_pushstring(L, "__index");
12312 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012313
12314 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012315 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12316 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12317 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12318 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12319 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12320 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12321 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12322 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12323 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12324 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012325
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012326 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12327 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12328 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12329 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12330 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12331 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12332 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012333
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012334 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012335
12336 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012337 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012338
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012339 /*
12340 *
12341 * Register class HTTPMessage
12342 *
12343 */
12344
12345 /* Create and fill the metatable. */
12346 lua_newtable(L);
12347
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012348 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012349 lua_pushstring(L, "__index");
12350 lua_newtable(L);
12351
12352 /* Register Lua functions. */
12353 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12354 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12355 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12356 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12357 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12358 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12359 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12360 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12361 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12362 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12363 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12364 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12365 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12366 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12367 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12368 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12369 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12370 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12371
12372 hlua_class_function(L, "body", hlua_http_msg_get_body);
12373 hlua_class_function(L, "set", hlua_http_msg_set_data);
12374 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12375 hlua_class_function(L, "append", hlua_http_msg_append);
12376 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12377 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12378 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12379 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12380
12381 hlua_class_function(L, "send", hlua_http_msg_send);
12382 hlua_class_function(L, "forward", hlua_http_msg_forward);
12383
12384 lua_rawset(L, -3);
12385
12386 /* Register previous table in the registry with reference and named entry. */
12387 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012388
12389 /*
12390 *
12391 * Register class HTTPClient
12392 *
12393 */
12394
12395 /* Create and fill the metatable. */
12396 lua_newtable(L);
12397 lua_pushstring(L, "__index");
12398 lua_newtable(L);
12399 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012400 hlua_class_function(L, "head", hlua_httpclient_head);
12401 hlua_class_function(L, "put", hlua_httpclient_put);
12402 hlua_class_function(L, "post", hlua_httpclient_post);
12403 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012404 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012405 /* Register the garbage collector entry. */
12406 lua_pushstring(L, "__gc");
12407 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12408 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12409
William Lallemand3956c4e2021-09-21 16:25:15 +020012410
12411
12412 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012413 /*
12414 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012415 * Register class AppletTCP
12416 *
12417 */
12418
12419 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012420 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012421
Ilya Shipitsind4259502020-04-08 01:07:56 +050012422 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012423 lua_pushstring(L, "__index");
12424 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012425
12426 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012427 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12428 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12429 hlua_class_function(L, "send", hlua_applet_tcp_send);
12430 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12431 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12432 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12433 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12434 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012435
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012436 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012437
12438 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012439 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012440
12441 /*
12442 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012443 * Register class AppletHTTP
12444 *
12445 */
12446
12447 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012448 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012449
Ilya Shipitsind4259502020-04-08 01:07:56 +050012450 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012451 lua_pushstring(L, "__index");
12452 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012453
12454 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012455 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12456 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12457 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12458 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12459 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12460 hlua_class_function(L, "getline", hlua_applet_http_getline);
12461 hlua_class_function(L, "receive", hlua_applet_http_recv);
12462 hlua_class_function(L, "send", hlua_applet_http_send);
12463 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12464 hlua_class_function(L, "set_status", hlua_applet_http_status);
12465 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012466
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012467 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012468
12469 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012470 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012471
12472 /*
12473 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012474 * Register class TXN
12475 *
12476 */
12477
12478 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012479 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012480
Ilya Shipitsind4259502020-04-08 01:07:56 +050012481 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012482 lua_pushstring(L, "__index");
12483 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012484
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012485 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012486 hlua_class_function(L, "set_priv", hlua_set_priv);
12487 hlua_class_function(L, "get_priv", hlua_get_priv);
12488 hlua_class_function(L, "set_var", hlua_set_var);
12489 hlua_class_function(L, "unset_var", hlua_unset_var);
12490 hlua_class_function(L, "get_var", hlua_get_var);
12491 hlua_class_function(L, "done", hlua_txn_done);
12492 hlua_class_function(L, "reply", hlua_txn_reply_new);
12493 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12494 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12495 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12496 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12497 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12498 hlua_class_function(L, "deflog", hlua_txn_deflog);
12499 hlua_class_function(L, "log", hlua_txn_log);
12500 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12501 hlua_class_function(L, "Info", hlua_txn_log_info);
12502 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12503 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012504
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012505 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012506
12507 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012508 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012509
12510 /*
12511 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012512 * Register class reply
12513 *
12514 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012515 lua_newtable(L);
12516 lua_pushstring(L, "__index");
12517 lua_newtable(L);
12518 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12519 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12520 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12521 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12522 lua_settable(L, -3); /* Sets the __index entry. */
12523 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012524
12525
12526 /*
12527 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012528 * Register class Socket
12529 *
12530 */
12531
12532 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012533 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012534
Ilya Shipitsind4259502020-04-08 01:07:56 +050012535 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012536 lua_pushstring(L, "__index");
12537 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012538
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012539#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012540 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012541#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012542 hlua_class_function(L, "connect", hlua_socket_connect);
12543 hlua_class_function(L, "send", hlua_socket_send);
12544 hlua_class_function(L, "receive", hlua_socket_receive);
12545 hlua_class_function(L, "close", hlua_socket_close);
12546 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12547 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12548 hlua_class_function(L, "setoption", hlua_socket_setoption);
12549 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012550
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012551 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012552
12553 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012554 lua_pushstring(L, "__gc");
12555 lua_pushcclosure(L, hlua_socket_gc, 0);
12556 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012557
12558 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012559 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012560
Thierry Fournieraafc7772020-12-04 11:47:47 +010012561 lua_atpanic(L, hlua_panic_safe);
12562
12563 return L;
12564}
12565
12566void hlua_init(void) {
12567 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012568 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012569#ifdef USE_OPENSSL
12570 struct srv_kw *kw;
12571 int tmp_error;
12572 char *error;
12573 char *args[] = { /* SSL client configuration. */
12574 "ssl",
12575 "verify",
12576 "none",
12577 NULL
12578 };
12579#endif
12580
12581 /* Init post init function list head */
12582 for (i = 0; i < MAX_THREADS + 1; i++)
12583 LIST_INIT(&hlua_init_functions[i]);
12584
12585 /* Init state for common/shared lua parts */
12586 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012587 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012588 hlua_states[0] = hlua_init_state(0);
12589
12590 /* Init state 1 for thread 0. We have at least one thread. */
12591 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012592 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012593 hlua_states[1] = hlua_init_state(1);
12594
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012595 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012596 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012597 if (!socket_proxy) {
12598 fprintf(stderr, "Lua init: %s\n", errmsg);
12599 exit(1);
12600 }
12601 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012602
12603 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012604 socket_tcp = new_server(socket_proxy);
12605 if (!socket_tcp) {
12606 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12607 exit(1);
12608 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012609
12610#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012611 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012612 socket_ssl = new_server(socket_proxy);
12613 if (!socket_ssl) {
12614 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12615 exit(1);
12616 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012617
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012618 socket_ssl->use_ssl = 1;
12619 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012620
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012621 for (i = 0; args[i] != NULL; i++) {
12622 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012623 /*
12624 *
12625 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012626 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012627 * features like client certificates and ssl_verify.
12628 *
12629 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012630 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012631 if (tmp_error != 0) {
12632 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12633 abort(); /* This must be never arrives because the command line
12634 not editable by the user. */
12635 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012636 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012637 }
12638 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012639#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012640
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012641}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012642
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012643static void hlua_deinit()
12644{
Willy Tarreau186f3762020-12-04 11:48:12 +010012645 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012646 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12647
12648 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12649 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012650
12651 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12652 if (hlua_states[thr])
12653 lua_close(hlua_states[thr]);
12654 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012655
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012656 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012657
Willy Tarreau0f143af2021-03-05 10:41:48 +010012658#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012659 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012660#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012661
12662 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012663}
12664
12665REGISTER_POST_DEINIT(hlua_deinit);
12666
Willy Tarreau80713382018-11-26 10:19:54 +010012667static void hlua_register_build_options(void)
12668{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012669 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012670
Willy Tarreaubb57d942016-12-21 19:04:56 +010012671 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12672 hap_register_build_opts(ptr, 1);
12673}
Willy Tarreau80713382018-11-26 10:19:54 +010012674
12675INITCALL0(STG_REGISTER, hlua_register_build_options);