blob: aff2099cf52ccfe425b3ffa62818b304e7037075 [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:
863 argp[idx].data.prx = p;
864 argp[idx].type = ARGT_TAB;
865 argp[idx+1].type = ARGT_STOP;
866 break;
867
868 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200869 msg = "Mandatory argument expected";
870 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100871 break;
872 }
873 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200874 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100875 }
876
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500877 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100878 if ((mask & ARGT_MASK) == ARGT_STOP &&
879 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200880 msg = "Last argument expected";
881 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 }
883
884 if ((mask & ARGT_MASK) == ARGT_STOP &&
885 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200886 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100887 }
888
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200889 /* Convert some argument types. All string in argp[] are for not
890 * duplicated yet.
891 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100892 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100893 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200894 if (argp[idx].type != ARGT_SINT) {
895 msg = "integer expected";
896 goto error;
897 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100898 argp[idx].type = ARGT_SINT;
899 break;
900
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100901 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200902 if (argp[idx].type != ARGT_SINT) {
903 msg = "integer expected";
904 goto error;
905 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200906 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100907 break;
908
909 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200910 if (argp[idx].type != ARGT_SINT) {
911 msg = "integer expected";
912 goto error;
913 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200914 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100915 break;
916
917 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200918 if (argp[idx].type != ARGT_STR) {
919 msg = "string expected";
920 goto error;
921 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200922 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200923 if (!argp[idx].data.prx) {
924 msg = "frontend doesn't exist";
925 goto error;
926 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100927 argp[idx].type = ARGT_FE;
928 break;
929
930 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200931 if (argp[idx].type != ARGT_STR) {
932 msg = "string expected";
933 goto error;
934 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200935 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200936 if (!argp[idx].data.prx) {
937 msg = "backend doesn't exist";
938 goto error;
939 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100940 argp[idx].type = ARGT_BE;
941 break;
942
943 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200944 if (argp[idx].type != ARGT_STR) {
945 msg = "string expected";
946 goto error;
947 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200948 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200949 if (!argp[idx].data.t) {
950 msg = "table doesn't exist";
951 goto error;
952 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100953 argp[idx].type = ARGT_TAB;
954 break;
955
956 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200957 if (argp[idx].type != ARGT_STR) {
958 msg = "string expected";
959 goto error;
960 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200961 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100962 if (sname) {
963 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200964 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200965 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200966 if (!px) {
967 msg = "backend doesn't exist";
968 goto error;
969 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100970 }
971 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200972 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100973 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100974 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100975 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200976 if (!argp[idx].data.srv) {
977 msg = "server doesn't exist";
978 goto error;
979 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100980 argp[idx].type = ARGT_SRV;
981 break;
982
983 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200984 if (argp[idx].type != ARGT_STR) {
985 msg = "string expected";
986 goto error;
987 }
988 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
989 msg = "invalid IPv4 address";
990 goto error;
991 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100992 argp[idx].type = ARGT_IPV4;
993 break;
994
995 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200996 if (argp[idx].type == ARGT_SINT)
997 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
998 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1000 msg = "invalid IPv4 mask";
1001 goto error;
1002 }
1003 }
1004 else {
1005 msg = "integer or string expected";
1006 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001007 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001008 argp[idx].type = ARGT_MSK4;
1009 break;
1010
1011 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001012 if (argp[idx].type != ARGT_STR) {
1013 msg = "string expected";
1014 goto error;
1015 }
1016 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1017 msg = "invalid IPv6 address";
1018 goto error;
1019 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001020 argp[idx].type = ARGT_IPV6;
1021 break;
1022
1023 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001024 if (argp[idx].type == ARGT_SINT)
1025 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1026 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001027 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1028 msg = "invalid IPv6 mask";
1029 goto error;
1030 }
1031 }
1032 else {
1033 msg = "integer or string expected";
1034 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001035 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001036 argp[idx].type = ARGT_MSK6;
1037 break;
1038
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001039 case ARGT_REG:
1040 if (argp[idx].type != ARGT_STR) {
1041 msg = "string expected";
1042 goto error;
1043 }
1044 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1045 if (!reg) {
1046 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1047 argp[idx].data.str.area, err);
1048 free(err);
1049 goto error;
1050 }
1051 argp[idx].type = ARGT_REG;
1052 argp[idx].data.reg = reg;
1053 break;
1054
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001055 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001056 if (argp[idx].type != ARGT_STR) {
1057 msg = "string expected";
1058 goto error;
1059 }
1060 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001061 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001062 ul = p->uri_auth->userlist;
1063 else
1064 ul = auth_find_userlist(argp[idx].data.str.area);
1065
1066 if (!ul) {
1067 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1068 goto error;
1069 }
1070 argp[idx].type = ARGT_USR;
1071 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001072 break;
1073
1074 case ARGT_STR:
1075 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1076 msg = "unable to duplicate string arg";
1077 goto error;
1078 }
1079 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001080 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001081
Christopher Fauletd25d9262020-08-06 11:04:46 +02001082 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001083 msg = "type not yet supported";
1084 goto error;
1085 break;
1086
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001087 }
1088
1089 /* Check for type of argument. */
1090 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001091 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1092 arg_type_names[(mask & ARGT_MASK)],
1093 arg_type_names[argp[idx].type & ARGT_MASK]);
1094 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001095 }
1096
1097 /* Next argument. */
1098 mask >>= ARGT_BITS;
1099 idx++;
1100 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001101 return 0;
1102
1103 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001104 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1106 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001107}
1108
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001109/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001110 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001111 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001112 *
1113 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114 * - hlua_sethlua : create the association between hlua context and lua_state.
1115 */
1116static inline struct hlua *hlua_gethlua(lua_State *L)
1117{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001118 struct hlua **hlua = lua_getextraspace(L);
1119 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001120}
1121static inline void hlua_sethlua(struct hlua *hlua)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1124 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001127/* Will return a non-NULL string indicating the Lua call trace if the caller
1128 * currently is executing from within a Lua function. One line per entry will
1129 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1130 * Lua function is not detected, NULL is returned.
1131 */
1132const char *hlua_show_current_location(const char *pfx)
1133{
1134 lua_State *L;
1135 lua_Debug ar;
1136
1137 /* global or per-thread stack initializing ? */
1138 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1139 return hlua_traceback(L, pfx);
1140
1141 /* per-thread stack running ? */
1142 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1143 return hlua_traceback(L, pfx);
1144
1145 /* global stack running ? */
1146 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1147 return hlua_traceback(L, pfx);
1148
1149 return NULL;
1150}
1151
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001152/* This function is used to send logs. It try to send on screen (stderr)
1153 * and on the default syslog server.
1154 */
1155static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1156{
1157 struct tm tm;
1158 char *p;
1159
1160 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001161 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001162 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001163 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001164 /* Break the message if exceed the buffer size. */
1165 *(p-4) = ' ';
1166 *(p-3) = '.';
1167 *(p-2) = '.';
1168 *(p-1) = '.';
1169 break;
1170 }
Willy Tarreau90807112020-02-25 08:16:33 +01001171 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001172 *p = *msg;
1173 else
1174 *p = '.';
1175 }
1176 *p = '\0';
1177
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001178 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001179 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001180 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1181 return;
1182
Willy Tarreaua678b432015-08-28 10:14:59 +02001183 get_localtime(date.tv_sec, &tm);
1184 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001185 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001186 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001187 fflush(stderr);
1188 }
1189}
1190
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001191/* This function just ensure that the yield will be always
1192 * returned with a timeout and permit to set some flags
1193 */
1194__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001195 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001197 struct hlua *hlua;
1198
1199 /* Get hlua struct, or NULL if we execute from main lua state */
1200 hlua = hlua_gethlua(L);
1201 if (!hlua) {
1202 return;
1203 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001204
1205 /* Set the wake timeout. If timeout is required, we set
1206 * the expiration time.
1207 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001208 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001210 hlua->flags |= flags;
1211
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001212 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001213 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214}
1215
Willy Tarreau87b09662015-04-03 00:22:06 +02001216/* This function initialises the Lua environment stored in the stream.
1217 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001218 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001219 *
1220 * This function is particular. it initialises a new Lua thread. If the
1221 * initialisation fails (example: out of memory error), the lua function
1222 * throws an error (longjmp).
1223 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001224 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001225 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001226 * threads appear, the safe environment set a lock to ensure only one
1227 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001228 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 *
1230 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001231 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001232 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001233 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001234 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001235 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001237 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001238int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001239{
1240 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001241 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001242 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001243 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001244 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001245 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001246 if (!already_safe) {
1247 if (!SET_SAFE_LJMP_PARENT(lua)) {
1248 lua->Tref = LUA_REFNIL;
1249 return 0;
1250 }
1251 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001252 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001253 if (!lua->T) {
1254 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001255 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001256 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001257 return 0;
1258 }
1259 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001260 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001261 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001262 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001263 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001264 return 1;
1265}
1266
Willy Tarreau87b09662015-04-03 00:22:06 +02001267/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001268 * is destroyed. The destroy also the memory context. The struct "lua"
1269 * is not freed.
1270 */
1271void hlua_ctx_destroy(struct hlua *lua)
1272{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001273 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001274 return;
1275
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001276 if (!lua->T)
1277 goto end;
1278
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001279 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001280 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001281
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001282 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001283 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001284 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001285 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001286
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001287 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001288 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001289 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001290 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001291 /* Forces a garbage collecting process. If the Lua program is finished
1292 * without error, we run the GC on the thread pointer. Its freed all
1293 * the unused memory.
1294 * If the thread is finnish with an error or is currently yielded,
1295 * it seems that the GC applied on the thread doesn't clean anything,
1296 * so e run the GC on the main thread.
1297 * NOTE: maybe this action locks all the Lua threads untiml the en of
1298 * the garbage collection.
1299 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001300 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001301 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001302 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001303 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001304 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001305 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001306
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001307 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001308
1309end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001310 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001311}
1312
1313/* This function is used to restore the Lua context when a coroutine
1314 * fails. This function copy the common memory between old coroutine
1315 * and the new coroutine. The old coroutine is destroyed, and its
1316 * replaced by the new coroutine.
1317 * If the flag "keep_msg" is set, the last entry of the old is assumed
1318 * as string error message and it is copied in the new stack.
1319 */
1320static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1321{
1322 lua_State *T;
1323 int new_ref;
1324
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001325 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001326 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001327 if (!T)
1328 return 0;
1329
1330 /* Copy last error message. */
1331 if (keep_msg)
1332 lua_xmove(lua->T, T, 1);
1333
1334 /* Copy data between the coroutines. */
1335 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1336 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001337 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001338
1339 /* Destroy old data. */
1340 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1341
1342 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001343 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001344
1345 /* Fill the struct with the new coroutine values. */
1346 lua->Mref = new_ref;
1347 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001348 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001349
1350 /* Set context. */
1351 hlua_sethlua(lua);
1352
1353 return 1;
1354}
1355
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001356void hlua_hook(lua_State *L, lua_Debug *ar)
1357{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001358 struct hlua *hlua;
1359
1360 /* Get hlua struct, or NULL if we execute from main lua state */
1361 hlua = hlua_gethlua(L);
1362 if (!hlua)
1363 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001364
1365 /* Lua cannot yield when its returning from a function,
1366 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001367 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001368 */
1369 if (lua_gethookmask(L) & LUA_MASKRET) {
1370 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1371 return;
1372 }
1373
1374 /* restore the interrupt condition. */
1375 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1376
1377 /* If we interrupt the Lua processing in yieldable state, we yield.
1378 * If the state is not yieldable, trying yield causes an error.
1379 */
1380 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001381 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001382
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001383 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001384 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001385 hlua->run_time += now_ms - hlua->start_time;
1386 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001387 lua_pushfstring(L, "execution timeout");
1388 WILL_LJMP(lua_error(L));
1389 }
1390
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001391 /* Update the start time. */
1392 hlua->start_time = now_ms;
1393
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001394 /* Try to interrupt the process at the end of the current
1395 * unyieldable function.
1396 */
1397 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001398}
1399
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001400/* This function start or resumes the Lua stack execution. If the flag
1401 * "yield_allowed" if no set and the LUA stack execution returns a yield
1402 * The function return an error.
1403 *
1404 * The function can returns 4 values:
1405 * - HLUA_E_OK : The execution is terminated without any errors.
1406 * - HLUA_E_AGAIN : The execution must continue at the next associated
1407 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001408 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001409 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001410 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001411 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001412 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001413 * LUA code.
1414 */
1415static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1416{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001417#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1418 int nres;
1419#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001420 int ret;
1421 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001422 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001424 /* Initialise run time counter. */
1425 if (!HLUA_IS_RUNNING(lua))
1426 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001427
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001428 /* Lock the whole Lua execution. This lock must be before the
1429 * label "resume_execution".
1430 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001431 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001432 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001433
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001434resume_execution:
1435
1436 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1437 * instructions. it is used for preventing infinite loops.
1438 */
1439 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1440
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001441 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001442 HLUA_SET_RUN(lua);
1443 HLUA_CLR_CTRLYIELD(lua);
1444 HLUA_CLR_WAKERESWR(lua);
1445 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001446 HLUA_CLR_NOYIELD(lua);
1447 if (!yield_allowed)
1448 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001449
Christopher Fauletbc275a92020-02-26 14:55:16 +01001450 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001451 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001452 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001453
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001454 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001455#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001456 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001457#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001458 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001459#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001460 switch (ret) {
1461
1462 case LUA_OK:
1463 ret = HLUA_E_OK;
1464 break;
1465
1466 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001467 /* Check if the execution timeout is expired. It it is the case, we
1468 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001469 */
Willy Tarreau55542642021-10-08 09:33:24 +02001470 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001471 lua->run_time += now_ms - lua->start_time;
1472 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001473 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001474 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001475 break;
1476 }
1477 /* Process the forced yield. if the general yield is not allowed or
1478 * if no task were associated this the current Lua execution
1479 * coroutine, we resume the execution. Else we want to return in the
1480 * scheduler and we want to be waked up again, to continue the
1481 * current Lua execution. So we schedule our own task.
1482 */
1483 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001484 if (!yield_allowed || !lua->task)
1485 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001486 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001487 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 if (!yield_allowed) {
1489 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001490 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 break;
1492 }
1493 ret = HLUA_E_AGAIN;
1494 break;
1495
1496 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001497
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001498 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001499 * because the errors ares the only one mean to return immediately
1500 * from and lua execution.
1501 */
1502 if (lua->flags & HLUA_EXIT) {
1503 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001504 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001505 break;
1506 }
1507
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001508 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001509 if (!lua_checkstack(lua->T, 1)) {
1510 ret = HLUA_E_ERR;
1511 break;
1512 }
1513 msg = lua_tostring(lua->T, -1);
1514 lua_settop(lua->T, 0); /* Empty the stack. */
1515 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001516 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001517 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001518 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001519 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001520 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001521 ret = HLUA_E_ERRMSG;
1522 break;
1523
1524 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001525 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001527 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001528 break;
1529
1530 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001531 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001532 if (!lua_checkstack(lua->T, 1)) {
1533 ret = HLUA_E_ERR;
1534 break;
1535 }
1536 msg = lua_tostring(lua->T, -1);
1537 lua_settop(lua->T, 0); /* Empty the stack. */
1538 lua_pop(lua->T, 1);
1539 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001540 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001542 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001543 ret = HLUA_E_ERRMSG;
1544 break;
1545
1546 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001547 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001549 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001550 break;
1551 }
1552
1553 switch (ret) {
1554 case HLUA_E_AGAIN:
1555 break;
1556
1557 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001558 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001559 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001560 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001561 break;
1562
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001563 case HLUA_E_ETMOUT:
1564 case HLUA_E_NOMEM:
1565 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001566 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001567 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001568 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001569 hlua_ctx_renew(lua, 0);
1570 break;
1571
1572 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001573 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001574 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001575 break;
1576 }
1577
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001578 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001579 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001580 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001581
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001582 return ret;
1583}
1584
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001585/* This function exit the current code. */
1586__LJMP static int hlua_done(lua_State *L)
1587{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001588 struct hlua *hlua;
1589
1590 /* Get hlua struct, or NULL if we execute from main lua state */
1591 hlua = hlua_gethlua(L);
1592 if (!hlua)
1593 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001594
1595 hlua->flags |= HLUA_EXIT;
1596 WILL_LJMP(lua_error(L));
1597
1598 return 0;
1599}
1600
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001601/* This function is an LUA binding. It provides a function
1602 * for deleting ACL from a referenced ACL file.
1603 */
1604__LJMP static int hlua_del_acl(lua_State *L)
1605{
1606 const char *name;
1607 const char *key;
1608 struct pat_ref *ref;
1609
1610 MAY_LJMP(check_args(L, 2, "del_acl"));
1611
1612 name = MAY_LJMP(luaL_checkstring(L, 1));
1613 key = MAY_LJMP(luaL_checkstring(L, 2));
1614
1615 ref = pat_ref_lookup(name);
1616 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001617 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001618
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001619 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001620 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001621 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001622 return 0;
1623}
1624
1625/* This function is an LUA binding. It provides a function
1626 * for deleting map entry from a referenced map file.
1627 */
1628static int hlua_del_map(lua_State *L)
1629{
1630 const char *name;
1631 const char *key;
1632 struct pat_ref *ref;
1633
1634 MAY_LJMP(check_args(L, 2, "del_map"));
1635
1636 name = MAY_LJMP(luaL_checkstring(L, 1));
1637 key = MAY_LJMP(luaL_checkstring(L, 2));
1638
1639 ref = pat_ref_lookup(name);
1640 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001641 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001642
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001643 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001644 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001645 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001646 return 0;
1647}
1648
1649/* This function is an LUA binding. It provides a function
1650 * for adding ACL pattern from a referenced ACL file.
1651 */
1652static int hlua_add_acl(lua_State *L)
1653{
1654 const char *name;
1655 const char *key;
1656 struct pat_ref *ref;
1657
1658 MAY_LJMP(check_args(L, 2, "add_acl"));
1659
1660 name = MAY_LJMP(luaL_checkstring(L, 1));
1661 key = MAY_LJMP(luaL_checkstring(L, 2));
1662
1663 ref = pat_ref_lookup(name);
1664 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001665 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001666
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001667 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001668 if (pat_ref_find_elt(ref, key) == NULL)
1669 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001670 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001671 return 0;
1672}
1673
1674/* This function is an LUA binding. It provides a function
1675 * for setting map pattern and sample from a referenced map
1676 * file.
1677 */
1678static int hlua_set_map(lua_State *L)
1679{
1680 const char *name;
1681 const char *key;
1682 const char *value;
1683 struct pat_ref *ref;
1684
1685 MAY_LJMP(check_args(L, 3, "set_map"));
1686
1687 name = MAY_LJMP(luaL_checkstring(L, 1));
1688 key = MAY_LJMP(luaL_checkstring(L, 2));
1689 value = MAY_LJMP(luaL_checkstring(L, 3));
1690
1691 ref = pat_ref_lookup(name);
1692 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001693 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001694
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001695 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001696 if (pat_ref_find_elt(ref, key) != NULL)
1697 pat_ref_set(ref, key, value, NULL);
1698 else
1699 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001700 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001701 return 0;
1702}
1703
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001704/* A class is a lot of memory that contain data. This data can be a table,
1705 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001706 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001707 * the name of the object (_G[<name>] = <metable> ).
1708 *
1709 * A metable is a table that modify the standard behavior of a standard
1710 * access to the associated data. The entries of this new metatable are
1711 * defined as is:
1712 *
1713 * http://lua-users.org/wiki/MetatableEvents
1714 *
1715 * __index
1716 *
1717 * we access an absent field in a table, the result is nil. This is
1718 * true, but it is not the whole truth. Actually, such access triggers
1719 * the interpreter to look for an __index metamethod: If there is no
1720 * such method, as usually happens, then the access results in nil;
1721 * otherwise, the metamethod will provide the result.
1722 *
1723 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1724 * the key does not appear in the table, but the metatable has an __index
1725 * property:
1726 *
1727 * - if the value is a function, the function is called, passing in the
1728 * table and the key; the return value of that function is returned as
1729 * the result.
1730 *
1731 * - if the value is another table, the value of the key in that table is
1732 * asked for and returned (and if it doesn't exist in that table, but that
1733 * table's metatable has an __index property, then it continues on up)
1734 *
1735 * - Use "rawget(myTable,key)" to skip this metamethod.
1736 *
1737 * http://www.lua.org/pil/13.4.1.html
1738 *
1739 * __newindex
1740 *
1741 * Like __index, but control property assignment.
1742 *
1743 * __mode - Control weak references. A string value with one or both
1744 * of the characters 'k' and 'v' which specifies that the the
1745 * keys and/or values in the table are weak references.
1746 *
1747 * __call - Treat a table like a function. When a table is followed by
1748 * parenthesis such as "myTable( 'foo' )" and the metatable has
1749 * a __call key pointing to a function, that function is invoked
1750 * (passing any specified arguments) and the return value is
1751 * returned.
1752 *
1753 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1754 * called, if the metatable for myTable has a __metatable
1755 * key, the value of that key is returned instead of the
1756 * actual metatable.
1757 *
1758 * __tostring - Control string representation. When the builtin
1759 * "tostring( myTable )" function is called, if the metatable
1760 * for myTable has a __tostring property set to a function,
1761 * that function is invoked (passing myTable to it) and the
1762 * return value is used as the string representation.
1763 *
1764 * __len - Control table length. When the table length is requested using
1765 * the length operator ( '#' ), if the metatable for myTable has
1766 * a __len key pointing to a function, that function is invoked
1767 * (passing myTable to it) and the return value used as the value
1768 * of "#myTable".
1769 *
1770 * __gc - Userdata finalizer code. When userdata is set to be garbage
1771 * collected, if the metatable has a __gc field pointing to a
1772 * function, that function is first invoked, passing the userdata
1773 * to it. The __gc metamethod is not called for tables.
1774 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1775 *
1776 * Special metamethods for redefining standard operators:
1777 * http://www.lua.org/pil/13.1.html
1778 *
1779 * __add "+"
1780 * __sub "-"
1781 * __mul "*"
1782 * __div "/"
1783 * __unm "!"
1784 * __pow "^"
1785 * __concat ".."
1786 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001787 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001788 * http://www.lua.org/pil/13.2.html
1789 *
1790 * __eq "=="
1791 * __lt "<"
1792 * __le "<="
1793 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001794
1795/*
1796 *
1797 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001798 * Class Map
1799 *
1800 *
1801 */
1802
1803/* Returns a struct hlua_map if the stack entry "ud" is
1804 * a class session, otherwise it throws an error.
1805 */
1806__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1807{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001808 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001809}
1810
1811/* This function is the map constructor. It don't need
1812 * the class Map object. It creates and return a new Map
1813 * object. It must be called only during "body" or "init"
1814 * context because it process some filesystem accesses.
1815 */
1816__LJMP static int hlua_map_new(struct lua_State *L)
1817{
1818 const char *fn;
1819 int match = PAT_MATCH_STR;
1820 struct sample_conv conv;
1821 const char *file = "";
1822 int line = 0;
1823 lua_Debug ar;
1824 char *err = NULL;
1825 struct arg args[2];
1826
1827 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1828 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1829
1830 fn = MAY_LJMP(luaL_checkstring(L, 1));
1831
1832 if (lua_gettop(L) >= 2) {
1833 match = MAY_LJMP(luaL_checkinteger(L, 2));
1834 if (match < 0 || match >= PAT_MATCH_NUM)
1835 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1836 }
1837
1838 /* Get Lua filename and line number. */
1839 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1840 lua_getinfo(L, "Sl", &ar); /* get info about it */
1841 if (ar.currentline > 0) { /* is there info? */
1842 file = ar.short_src;
1843 line = ar.currentline;
1844 }
1845 }
1846
1847 /* fill fake sample_conv struct. */
1848 conv.kw = ""; /* unused. */
1849 conv.process = NULL; /* unused. */
1850 conv.arg_mask = 0; /* unused. */
1851 conv.val_args = NULL; /* unused. */
1852 conv.out_type = SMP_T_STR;
1853 conv.private = (void *)(long)match;
1854 switch (match) {
1855 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1856 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1857 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1858 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1859 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1860 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1861 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001862 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001863 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1864 default:
1865 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1866 }
1867
1868 /* fill fake args. */
1869 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001870 args[0].data.str.area = strdup(fn);
1871 args[0].data.str.data = strlen(fn);
1872 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001873 args[1].type = ARGT_STOP;
1874
1875 /* load the map. */
1876 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001877 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001878 * free the err variable.
1879 */
1880 luaL_where(L, 1);
1881 lua_pushfstring(L, "'new': %s.", err);
1882 lua_concat(L, 2);
1883 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001884 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001885 WILL_LJMP(lua_error(L));
1886 }
1887
1888 /* create the lua object. */
1889 lua_newtable(L);
1890 lua_pushlightuserdata(L, args[0].data.map);
1891 lua_rawseti(L, -2, 0);
1892
1893 /* Pop a class Map metatable and affect it to the userdata. */
1894 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1895 lua_setmetatable(L, -2);
1896
1897
1898 return 1;
1899}
1900
1901__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1902{
1903 struct map_descriptor *desc;
1904 struct pattern *pat;
1905 struct sample smp;
1906
1907 MAY_LJMP(check_args(L, 2, "lookup"));
1908 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001909 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001910 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001911 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001912 }
1913 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001914 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001915 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001916 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 +01001917 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001918 }
1919
1920 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001921 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001922 if (str)
1923 lua_pushstring(L, "");
1924 else
1925 lua_pushnil(L);
1926 return 1;
1927 }
1928
1929 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001930 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001931 return 1;
1932}
1933
1934__LJMP static int hlua_map_lookup(struct lua_State *L)
1935{
1936 return _hlua_map_lookup(L, 0);
1937}
1938
1939__LJMP static int hlua_map_slookup(struct lua_State *L)
1940{
1941 return _hlua_map_lookup(L, 1);
1942}
1943
1944/*
1945 *
1946 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947 * Class Socket
1948 *
1949 *
1950 */
1951
1952__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1953{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001954 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955}
1956
1957/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001958 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959 * received.
1960 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001961static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001962{
Willy Tarreau5321da92022-05-06 11:57:34 +02001963 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02001964 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965
Willy Tarreau5321da92022-05-06 11:57:34 +02001966 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02001967 sc_shutw(sc);
1968 sc_shutr(sc);
1969 sc_ic(sc)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001970 notification_wake(&ctx->wake_on_read);
1971 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02001972 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001973 }
1974
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001975 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001976 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001977 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001978
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001979 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001980 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001981 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001982
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001983 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001984 * to be notified whenever the connection completes.
1985 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001986 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02001987 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02001988 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02001989 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001990 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001991 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992
1993 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001994 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001996 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02001997 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001998 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999
2000 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002001 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002002 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002003
2004 /* Some data were injected in the buffer, notify the stream
2005 * interface.
2006 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002007 if (!channel_is_empty(sc_ic(sc)))
2008 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002009
2010 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002011 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002012 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002013 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002014 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015}
2016
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002017static int hlua_socket_init(struct appctx *appctx)
2018{
2019 struct hlua_csk_ctx *ctx = appctx->svcctx;
2020 struct stream *s;
2021
2022 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2023 goto error;
2024
2025 s = appctx_strm(appctx);
2026
Willy Tarreau4596fe22022-05-17 19:07:51 +02002027 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002028 * and retrieve data from the server. The connection is initialized
2029 * with the "struct server".
2030 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002031 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002032
2033 /* Force destination server. */
2034 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2035 s->target = &socket_tcp->obj_type;
2036
2037 ctx->appctx = appctx;
2038 return 0;
2039
2040 error:
2041 return -1;
2042}
2043
Willy Tarreau87b09662015-04-03 00:22:06 +02002044/* This function is called when the "struct stream" is destroyed.
2045 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046 * Wake all the pending signals.
2047 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002048static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002049{
Willy Tarreau5321da92022-05-06 11:57:34 +02002050 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002051 struct xref *peer;
2052
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002053 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002054 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002055 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002056 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057
2058 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002059 notification_wake(&ctx->wake_on_read);
2060 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061}
2062
2063/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002064 * uses this object. If the stream does not exists, just quit.
2065 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066 * pending signal can rest in the read and write lists. destroy
2067 * it.
2068 */
2069__LJMP static int hlua_socket_gc(lua_State *L)
2070{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002071 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002072 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002073 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002075 MAY_LJMP(check_args(L, 1, "__gc"));
2076
2077 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 peer = xref_get_peer_and_lock(&socket->xref);
2079 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002081
2082 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002084 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002085 ctx->die = 1;
2086 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002088 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002089 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090 return 0;
2091}
2092
2093/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002094 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 */
sada05ed3302018-05-11 11:48:18 -07002096__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002099 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002100 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002101 struct hlua *hlua;
2102
2103 /* Get hlua struct, or NULL if we execute from main lua state */
2104 hlua = hlua_gethlua(L);
2105 if (!hlua)
2106 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002108 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002109
2110 /* Check if we run on the same thread than the xreator thread.
2111 * We cannot access to the socket if the thread is different.
2112 */
2113 if (socket->tid != tid)
2114 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2115
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002116 peer = xref_get_peer_and_lock(&socket->xref);
2117 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002119
2120 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002121 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002123 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002124 ctx->die = 1;
2125 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002127 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002128 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002129 return 0;
2130}
2131
sada05ed3302018-05-11 11:48:18 -07002132/* The close function calls close_helper.
2133 */
2134__LJMP static int hlua_socket_close(lua_State *L)
2135{
2136 MAY_LJMP(check_args(L, 1, "close"));
2137 return hlua_socket_close_helper(L);
2138}
2139
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140/* This Lua function assumes that the stack contain three parameters.
2141 * 1 - USERDATA containing a struct socket
2142 * 2 - INTEGER with values of the macro defined below
2143 * If the integer is -1, we must read at most one line.
2144 * If the integer is -2, we ust read all the data until the
2145 * end of the stream.
2146 * If the integer is positive value, we must read a number of
2147 * bytes corresponding to this value.
2148 */
2149#define HLSR_READ_LINE (-1)
2150#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002151__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152{
2153 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2154 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002155 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002156 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002158 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002159 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002160 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002161 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002162 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002163 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002164 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002165 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002166 struct stream *s;
2167 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002168 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002170 /* Get hlua struct, or NULL if we execute from main lua state */
2171 hlua = hlua_gethlua(L);
2172
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 /* Check if this lua stack is schedulable. */
2174 if (!hlua || !hlua->task)
2175 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2176 "'frontend', 'backend' or 'task'"));
2177
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002178 /* Check if we run on the same thread than the xreator thread.
2179 * We cannot access to the socket if the thread is different.
2180 */
2181 if (socket->tid != tid)
2182 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2183
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002184 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002185 peer = xref_get_peer_and_lock(&socket->xref);
2186 if (!peer)
2187 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002188
2189 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2190 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002191 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002193 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002196 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 if (nblk < 0) /* Connection close. */
2198 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002199 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002201
2202 /* remove final \r\n. */
2203 if (nblk == 1) {
2204 if (blk1[len1-1] == '\n') {
2205 len1--;
2206 skip_at_end++;
2207 if (blk1[len1-1] == '\r') {
2208 len1--;
2209 skip_at_end++;
2210 }
2211 }
2212 }
2213 else {
2214 if (blk2[len2-1] == '\n') {
2215 len2--;
2216 skip_at_end++;
2217 if (blk2[len2-1] == '\r') {
2218 len2--;
2219 skip_at_end++;
2220 }
2221 }
2222 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223 }
2224
2225 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002227 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 if (nblk < 0) /* Connection close. */
2229 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002230 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 goto connection_empty;
2232 }
2233
2234 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002236 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237 if (nblk < 0) /* Connection close. */
2238 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002239 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 goto connection_empty;
2241
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002242 missing_bytes = wanted - socket->b.n;
2243 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002245 len1 = missing_bytes;
2246 } if (nblk == 2 && len1 + len2 > missing_bytes)
2247 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248 }
2249
2250 len = len1;
2251
2252 luaL_addlstring(&socket->b, blk1, len1);
2253 if (nblk == 2) {
2254 len += len2;
2255 luaL_addlstring(&socket->b, blk2, len2);
2256 }
2257
2258 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002259 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260
2261 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002262 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263
2264 /* If the pattern reclaim to read all the data
2265 * in the connection, got out.
2266 */
2267 if (wanted == HLSR_READ_ALL)
2268 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002269 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270 goto connection_empty;
2271
2272 /* Return result. */
2273 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002274 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 return 1;
2276
2277connection_closed:
2278
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 xref_unlock(&socket->xref, peer);
2280
2281no_peer:
2282
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283 /* If the buffer containds data. */
2284 if (socket->b.n > 0) {
2285 luaL_pushresult(&socket->b);
2286 return 1;
2287 }
2288 lua_pushnil(L);
2289 lua_pushstring(L, "connection closed.");
2290 return 2;
2291
2292connection_empty:
2293
Willy Tarreau5321da92022-05-06 11:57:34 +02002294 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002295 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002297 }
2298 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002299 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 return 0;
2301}
2302
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002303/* This Lua function gets two parameters. The first one can be string
2304 * or a number. If the string is "*l", the user requires one line. If
2305 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 * If the value is a number, the user require a number of bytes equal
2307 * to the value. The default value is "*l" (a line).
2308 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002309 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 * integer takes this values:
2311 * -1 : read a line
2312 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002313 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002315 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 * concatenated with the read data.
2317 */
2318__LJMP static int hlua_socket_receive(struct lua_State *L)
2319{
2320 int wanted = HLSR_READ_LINE;
2321 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002322 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 char *error;
2324 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002325 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326
2327 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2328 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2329
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002330 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002332 /* Check if we run on the same thread than the xreator thread.
2333 * We cannot access to the socket if the thread is different.
2334 */
2335 if (socket->tid != tid)
2336 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2337
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338 /* check for pattern. */
2339 if (lua_gettop(L) >= 2) {
2340 type = lua_type(L, 2);
2341 if (type == LUA_TSTRING) {
2342 pattern = lua_tostring(L, 2);
2343 if (strcmp(pattern, "*a") == 0)
2344 wanted = HLSR_READ_ALL;
2345 else if (strcmp(pattern, "*l") == 0)
2346 wanted = HLSR_READ_LINE;
2347 else {
2348 wanted = strtoll(pattern, &error, 10);
2349 if (*error != '\0')
2350 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2351 }
2352 }
2353 else if (type == LUA_TNUMBER) {
2354 wanted = lua_tointeger(L, 2);
2355 if (wanted < 0)
2356 WILL_LJMP(luaL_error(L, "Unsupported size."));
2357 }
2358 }
2359
2360 /* Set pattern. */
2361 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002362
2363 /* Check if we would replace the top by itself. */
2364 if (lua_gettop(L) != 2)
2365 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
Christopher Fauletc31b2002021-05-03 10:11:13 +02002367 /* Save index of the top of the stack because since buffers are used, it
2368 * may change
2369 */
2370 lastarg = lua_gettop(L);
2371
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002372 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 luaL_buffinit(L, &socket->b);
2374
2375 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002376 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377 if (lua_type(L, 3) != LUA_TSTRING)
2378 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2379 pattern = lua_tolstring(L, 3, &len);
2380 luaL_addlstring(&socket->b, pattern, len);
2381 }
2382
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002383 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384}
2385
2386/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002387 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002389static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390{
2391 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002392 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002393 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 struct appctx *appctx;
2395 size_t buf_len;
2396 const char *buf;
2397 int len;
2398 int send_len;
2399 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002400 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002401 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002402 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002403
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002404 /* Get hlua struct, or NULL if we execute from main lua state */
2405 hlua = hlua_gethlua(L);
2406
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 /* Check if this lua stack is schedulable. */
2408 if (!hlua || !hlua->task)
2409 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2410 "'frontend', 'backend' or 'task'"));
2411
2412 /* Get object */
2413 socket = MAY_LJMP(hlua_checksocket(L, 1));
2414 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002415 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002417 /* Check if we run on the same thread than the xreator thread.
2418 * We cannot access to the socket if the thread is different.
2419 */
2420 if (socket->tid != tid)
2421 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2422
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002423 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002424 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002425 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002426 lua_pushinteger(L, -1);
2427 return 1;
2428 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002429
2430 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2431 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002432 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002433 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002434
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002436 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002437 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438 lua_pushinteger(L, -1);
2439 return 1;
2440 }
2441
2442 /* Update the input buffer data. */
2443 buf += sent;
2444 send_len = buf_len - sent;
2445
2446 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002447 if (sent >= buf_len) {
2448 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002450 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002452 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002453 * the request buffer if its not required.
2454 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002455 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002456 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002457 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002458 }
2459
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002460 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002461 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002462 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002463 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002464 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465
2466 /* send data */
2467 if (len < send_len)
2468 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002469 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
2471 /* "Not enough space" (-1), "Buffer too little to contain
2472 * the data" (-2) are not expected because the available length
2473 * is tested.
2474 * Other unknown error are also not expected.
2475 */
2476 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002477 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002478 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002479
sada05ed3302018-05-11 11:48:18 -07002480 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002481 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002483 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002484 return 1;
2485 }
2486
2487 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002488 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002489
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002490 s->req.rex = TICK_ETERNITY;
2491 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002492
2493 /* Update length sent. */
2494 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002495 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002496
2497 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002498 if (sent + len >= buf_len) {
2499 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002501 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502
2503hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002504 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002505 xref_unlock(&socket->xref, peer);
2506 WILL_LJMP(luaL_error(L, "out of memory"));
2507 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002508 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002509 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002510 return 0;
2511}
2512
2513/* This function initiate the send of data. It just check the input
2514 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002515 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516 * "hlua_socket_write_yield" that can yield.
2517 *
2518 * The Lua function gets between 3 and 4 parameters. The first one is
2519 * the associated object. The second is a string buffer. The third is
2520 * a facultative integer that represents where is the buffer position
2521 * of the start of the data that can send. The first byte is the
2522 * position "1". The default value is "1". The fourth argument is a
2523 * facultative integer that represents where is the buffer position
2524 * of the end of the data that can send. The default is the last byte.
2525 */
2526static int hlua_socket_send(struct lua_State *L)
2527{
2528 int i;
2529 int j;
2530 const char *buf;
2531 size_t buf_len;
2532
2533 /* Check number of arguments. */
2534 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2535 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2536
2537 /* Get the string. */
2538 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2539
2540 /* Get and check j. */
2541 if (lua_gettop(L) == 4) {
2542 j = MAY_LJMP(luaL_checkinteger(L, 4));
2543 if (j < 0)
2544 j = buf_len + j + 1;
2545 if (j > buf_len)
2546 j = buf_len + 1;
2547 lua_pop(L, 1);
2548 }
2549 else
2550 j = buf_len;
2551
2552 /* Get and check i. */
2553 if (lua_gettop(L) == 3) {
2554 i = MAY_LJMP(luaL_checkinteger(L, 3));
2555 if (i < 0)
2556 i = buf_len + i + 1;
2557 if (i > buf_len)
2558 i = buf_len + 1;
2559 lua_pop(L, 1);
2560 } else
2561 i = 1;
2562
2563 /* Check bth i and j. */
2564 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002565 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002566 return 1;
2567 }
2568 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002569 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002570 return 1;
2571 }
2572 if (i == 0)
2573 i = 1;
2574 if (j == 0)
2575 j = 1;
2576
2577 /* Pop the string. */
2578 lua_pop(L, 1);
2579
2580 /* Update the buffer length. */
2581 buf += i - 1;
2582 buf_len = j - i + 1;
2583 lua_pushlstring(L, buf, buf_len);
2584
2585 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002586 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002587
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589}
2590
Willy Tarreau22b0a682015-06-17 19:43:49 +02002591#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002592__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593{
2594 static char buffer[SOCKET_INFO_MAX_LEN];
2595 int ret;
2596 int len;
2597 char *p;
2598
2599 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2600 if (ret <= 0) {
2601 lua_pushnil(L);
2602 return 1;
2603 }
2604
2605 if (ret == AF_UNIX) {
2606 lua_pushstring(L, buffer+1);
2607 return 1;
2608 }
2609 else if (ret == AF_INET6) {
2610 buffer[0] = '[';
2611 len = strlen(buffer);
2612 buffer[len] = ']';
2613 len++;
2614 buffer[len] = ':';
2615 len++;
2616 p = buffer;
2617 }
2618 else if (ret == AF_INET) {
2619 p = buffer + 1;
2620 len = strlen(p);
2621 p[len] = ':';
2622 len++;
2623 }
2624 else {
2625 lua_pushnil(L);
2626 return 1;
2627 }
2628
2629 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2630 lua_pushnil(L);
2631 return 1;
2632 }
2633
2634 lua_pushstring(L, p);
2635 return 1;
2636}
2637
2638/* Returns information about the peer of the connection. */
2639__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2640{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002641 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002642 struct xref *peer;
2643 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002644 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002645 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002646 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002647
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002648 MAY_LJMP(check_args(L, 1, "getpeername"));
2649
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002650 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002651
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002652 /* Check if we run on the same thread than the xreator thread.
2653 * We cannot access to the socket if the thread is different.
2654 */
2655 if (socket->tid != tid)
2656 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2657
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002658 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002659 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 lua_pushnil(L);
2662 return 1;
2663 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002664
2665 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002666 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002667 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002668 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002669 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002670 lua_pushnil(L);
2671 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002672 }
2673
Christopher Faulet16f16af2021-10-27 09:34:56 +02002674 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002675 xref_unlock(&socket->xref, peer);
2676 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677}
2678
2679/* Returns information about my connection side. */
2680static int hlua_socket_getsockname(struct lua_State *L)
2681{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002682 struct hlua_socket *socket;
2683 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002684 struct appctx *appctx;
2685 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002686 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002687 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002688
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689 MAY_LJMP(check_args(L, 1, "getsockname"));
2690
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002691 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002692
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002693 /* Check if we run on the same thread than the xreator thread.
2694 * We cannot access to the socket if the thread is different.
2695 */
2696 if (socket->tid != tid)
2697 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2698
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002699 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002700 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002701 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702 lua_pushnil(L);
2703 return 1;
2704 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002705
2706 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002707 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002708
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002709 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002710 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002711 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712 lua_pushnil(L);
2713 return 1;
2714 }
2715
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002716 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002717 xref_unlock(&socket->xref, peer);
2718 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719}
2720
2721/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002722static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723 .obj_type = OBJ_TYPE_APPLET,
2724 .name = "<LUA_TCP>",
2725 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002726 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 .release = hlua_socket_release,
2728};
2729
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002730__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002731{
2732 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002733 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002734 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002735 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002736 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002737 struct stream *s;
2738
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002739 /* Get hlua struct, or NULL if we execute from main lua state */
2740 hlua = hlua_gethlua(L);
2741 if (!hlua)
2742 return 0;
2743
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002744 /* Check if we run on the same thread than the xreator thread.
2745 * We cannot access to the socket if the thread is different.
2746 */
2747 if (socket->tid != tid)
2748 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2749
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002750 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002751 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002752 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002753 lua_pushnil(L);
2754 lua_pushstring(L, "Can't connect");
2755 return 2;
2756 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002757
2758 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2759 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002760 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002761
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002762 /* Check if we run on the same thread than the xreator thread.
2763 * We cannot access to the socket if the thread is different.
2764 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002765 if (socket->tid != tid) {
2766 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002767 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002768 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002769
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002770 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002771 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002772 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002773 lua_pushnil(L);
2774 lua_pushstring(L, "Can't connect");
2775 return 2;
2776 }
2777
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002778 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002779
2780 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002781 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002782 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002783 lua_pushinteger(L, 1);
2784 return 1;
2785 }
2786
Willy Tarreau5321da92022-05-06 11:57:34 +02002787 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002788 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002790 }
2791 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002792 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793 return 0;
2794}
2795
2796/* This function fail or initite the connection. */
2797__LJMP static int hlua_socket_connect(struct lua_State *L)
2798{
2799 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002800 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002801 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002802 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002803 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002804 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 int low, high;
2806 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002807 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002808 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002809 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002810
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002811 if (lua_gettop(L) < 2)
2812 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813
2814 /* Get args. */
2815 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002816
2817 /* Check if we run on the same thread than the xreator thread.
2818 * We cannot access to the socket if the thread is different.
2819 */
2820 if (socket->tid != tid)
2821 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2822
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002823 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002824 if (lua_gettop(L) >= 3) {
2825 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002826 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827
Tim Duesterhus6edab862018-01-06 19:04:45 +01002828 /* Force the ip to end with a colon, to support IPv6 addresses
2829 * that are not enclosed within square brackets.
2830 */
2831 if (port > 0) {
2832 luaL_buffinit(L, &b);
2833 luaL_addstring(&b, ip);
2834 luaL_addchar(&b, ':');
2835 luaL_pushresult(&b);
2836 ip = lua_tolstring(L, lua_gettop(L), NULL);
2837 }
2838 }
2839
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002840 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002841 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002842 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002843 lua_pushnil(L);
2844 return 1;
2845 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002846
2847 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002848 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 +02002849 if (!addr) {
2850 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002851 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002852 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002853
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002854 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002855 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002856 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002857 if (port == -1) {
2858 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002859 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002860 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002861 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2862 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002863 if (port == -1) {
2864 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002865 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002866 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002867 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002868 }
2869 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002870
Willy Tarreau5321da92022-05-06 11:57:34 +02002871 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2872 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002873 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002874 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002875
Willy Tarreau3e7be362022-05-27 10:35:27 +02002876 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002877 xref_unlock(&socket->xref, peer);
2878 WILL_LJMP(luaL_error(L, "connect: internal error"));
2879 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002880
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002881 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002882 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002883 if (!hlua)
2884 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002885
2886 /* inform the stream that we want to be notified whenever the
2887 * connection completes.
2888 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002889 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002890 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002891 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002892
Willy Tarreauf31af932020-01-14 09:59:38 +01002893 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002894
Willy Tarreau5321da92022-05-06 11:57:34 +02002895 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002896 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002897 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002898 }
2899 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002900
2901 task_wakeup(s->task, TASK_WOKEN_INIT);
2902 /* Return yield waiting for connection. */
2903
Willy Tarreau9635e032018-10-16 17:52:55 +02002904 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002905
2906 return 0;
2907}
2908
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002909#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2911{
2912 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002913 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002914 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002915
2916 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2917 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002918
2919 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002920 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002921 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002922 lua_pushnil(L);
2923 return 1;
2924 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002925
Willy Tarreau0698c802022-05-11 14:09:57 +02002926 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002928 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002929 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002930 return MAY_LJMP(hlua_socket_connect(L));
2931}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002932#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933
2934__LJMP static int hlua_socket_setoption(struct lua_State *L)
2935{
2936 return 0;
2937}
2938
2939__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2940{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002941 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002942 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002943 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002944 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002945 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002946
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002947 MAY_LJMP(check_args(L, 2, "settimeout"));
2948
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002949 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002950
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002951 /* convert the timeout to millis */
2952 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953
Thierry Fournier17a921b2018-03-08 09:59:02 +01002954 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002955 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002956 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2957
Mark Lakes56cc1252018-03-27 09:48:06 +02002958 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002959 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002960
2961 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002962 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002963 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002964
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002965 /* Check if we run on the same thread than the xreator thread.
2966 * We cannot access to the socket if the thread is different.
2967 */
2968 if (socket->tid != tid)
2969 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2970
Mark Lakes56cc1252018-03-27 09:48:06 +02002971 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002972 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002973 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002974 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2975 WILL_LJMP(lua_error(L));
2976 return 0;
2977 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002978
Willy Tarreau0698c802022-05-11 14:09:57 +02002979 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002980
Cyril Bonté7bb63452018-08-17 23:51:02 +02002981 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002982 s->req.rto = tmout;
2983 s->req.wto = tmout;
2984 s->res.rto = tmout;
2985 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002986 s->req.rex = tick_add_ifset(now_ms, tmout);
2987 s->req.wex = tick_add_ifset(now_ms, tmout);
2988 s->res.rex = tick_add_ifset(now_ms, tmout);
2989 s->res.wex = tick_add_ifset(now_ms, tmout);
2990
2991 s->task->expire = tick_add_ifset(now_ms, tmout);
2992 task_queue(s->task);
2993
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002994 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995
Thierry Fourniere9636f12018-03-08 09:54:32 +01002996 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002997 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998}
2999
3000__LJMP static int hlua_socket_new(lua_State *L)
3001{
3002 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003003 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003004 struct appctx *appctx;
3005
3006 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003007 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003008 hlua_pusherror(L, "socket: full stack");
3009 goto out_fail_conf;
3010 }
3011
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003012 /* Create the object: obj[0] = userdata. */
3013 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003014 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003015 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003016 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003017 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003018
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003019 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003020 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003021 hlua_pusherror(L, "socket: uninitialized pools.");
3022 goto out_fail_conf;
3023 }
3024
Willy Tarreau87b09662015-04-03 00:22:06 +02003025 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003026 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3027 lua_setmetatable(L, -2);
3028
Willy Tarreaud420a972015-04-06 00:39:18 +02003029 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003030 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003031 if (!appctx) {
3032 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003033 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003034 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003035 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3036 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003037 ctx->die = 0;
3038 LIST_INIT(&ctx->wake_on_write);
3039 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003040
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003041 if (appctx_init(appctx) == -1) {
3042 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003043 goto out_fail_appctx;
3044 }
3045
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003046 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003047 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003048 return 1;
3049
Christopher Faulet13a35e52021-12-20 15:34:16 +01003050 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003051 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003052 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003053 WILL_LJMP(lua_error(L));
3054 return 0;
3055}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003056
3057/*
3058 *
3059 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060 * Class Channel
3061 *
3062 *
3063 */
3064
3065/* Returns the struct hlua_channel join to the class channel in the
3066 * stack entry "ud" or throws an argument error.
3067 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003068__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003069{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003070 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003071}
3072
Willy Tarreau47860ed2015-03-10 14:07:50 +01003073/* Pushes the channel onto the top of the stack. If the stask does not have a
3074 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003075 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003076static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003077{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003078 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003079 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003080 return 0;
3081
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003082 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003083 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003084 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085
3086 /* Pop a class sesison metatable and affect it to the userdata. */
3087 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3088 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003089 return 1;
3090}
3091
Christopher Faulet9f55a502020-02-25 15:21:02 +01003092/* Helper function returning a filter attached to a channel at the position <ud>
3093 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003094 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003095 * initialized.
3096 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003097static 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 +01003098{
3099 struct filter *filter = NULL;
3100
3101 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3102 struct hlua_flt_ctx *flt_ctx;
3103
3104 filter = lua_touserdata (L, -1);
3105 flt_ctx = filter->ctx;
3106 if (hlua_filter_from_payload(filter)) {
3107 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3108 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3109 }
3110 }
3111
3112 lua_pop(L, 1);
3113 return filter;
3114}
3115
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003116/* Copies <len> bytes of data present in the channel's buffer, starting at the
3117* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003118* responsibility to ensure <len> and <offset> are valid. It always return the
3119* length of the built string. <len> may be 0, in this case, an empty string is
3120* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003121*/
3122static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003123{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003124 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003125 luaL_Buffer b;
3126
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003127 block1 = len;
3128 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3129 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3130 block2 = len - block1;
3131
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003132 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003133 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3134 if (block2)
3135 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003136 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003137 return len;
3138}
3139
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003140/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3141 * function returns -1 if data cannot be copied. Otherwise, it returns the
3142 * number of bytes copied.
3143 */
3144static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3145{
3146 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003147
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003148 /* Nothing to do, just return */
3149 if (unlikely(istlen(str) == 0))
3150 goto end;
3151
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003152 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003153 ret = -1;
3154 goto end;
3155 }
3156 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3157
3158 end:
3159 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003160}
3161
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003162/* Removes <len> bytes of data at the absolute position <offset>.
3163 */
3164static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3165{
3166 size_t end = offset + len;
3167
3168 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3169 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3170 b_data(&chn->buf) - end, -len);
3171 b_sub(&chn->buf, len);
3172}
3173
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003174/* Copies input data in the channel's buffer. It is possible to set a specific
3175 * offset (0 by default) and a length (all remaining input data starting for the
3176 * offset by default). If there is not enough input data and more data can be
3177 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003178 *
3179 * From an action, All input data are considered. For a filter, the offset and
3180 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003181 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003182__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003183{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003184 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003185 struct filter *filter;
3186 size_t input, output;
3187 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003188
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003189 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003190
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003191 output = co_data(chn);
3192 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003193
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003194 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3195 if (filter && !hlua_filter_from_payload(filter))
3196 WILL_LJMP(lua_error(L));
3197
3198 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003199 if (lua_gettop(L) > 1) {
3200 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3201 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003202 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003203 offset += output;
3204 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205 lua_pushfstring(L, "offset out of range.");
3206 WILL_LJMP(lua_error(L));
3207 }
3208 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003209 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 if (lua_gettop(L) == 3) {
3211 len = MAY_LJMP(luaL_checkinteger(L, 3));
3212 if (!len)
3213 goto dup;
3214 if (len == -1)
3215 len = global.tune.bufsize;
3216 if (len < 0) {
3217 lua_pushfstring(L, "length out of range.");
3218 WILL_LJMP(lua_error(L));
3219 }
3220 }
3221
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003222 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003223 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3224 /* Yield waiting for more data, as requested */
3225 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3226 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003227 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003228 }
3229
3230 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003231 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003232 return 1;
3233}
3234
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003235/* Copies the first line (including the trailing LF) of input data in the
3236 * channel's buffer. It is possible to set a specific offset (0 by default) and
3237 * a length (all remaining input data starting for the offset by default). If
3238 * there is not enough input data and more data can be received, the function
3239 * yields. If a length is explicitly specified, no more data are
3240 * copied. Otherwise, if no LF is found and more data can be received, this
3241 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003242 *
3243 * From an action, All input data are considered. For a filter, the offset and
3244 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003245 */
3246__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003247{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003248 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003249 struct filter *filter;
3250 size_t l, input, output;
3251 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003252
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003253 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 output = co_data(chn);
3255 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003256
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003257 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3258 if (filter && !hlua_filter_from_payload(filter))
3259 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003261 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003262 if (lua_gettop(L) > 1) {
3263 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3264 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003265 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003266 offset += output;
3267 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003268 lua_pushfstring(L, "offset out of range.");
3269 WILL_LJMP(lua_error(L));
3270 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003271 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003272
3273 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274 if (lua_gettop(L) == 3) {
3275 len = MAY_LJMP(luaL_checkinteger(L, 3));
3276 if (!len)
3277 goto dup;
3278 if (len == -1)
3279 len = global.tune.bufsize;
3280 if (len < 0) {
3281 lua_pushfstring(L, "length out of range.");
3282 WILL_LJMP(lua_error(L));
3283 }
3284 }
3285
3286 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003287 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003288 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003289 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003290 len = l+1;
3291 goto dup;
3292 }
3293 }
3294
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003296 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3297 /* Yield waiting for more data */
3298 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3299 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003301 }
3302
3303 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003304 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003305 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003306}
3307
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003308/* [ DEPRECATED ]
3309 *
3310 * Duplicate all input data foud in the channel's buffer. The data are not
3311 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003312 *
3313 * From an action, All input data are considered. For a filter, the offset and
3314 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003315 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003316__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003317{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003318 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003319 struct filter *filter;
3320 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003321
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003322 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003323 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003324 if (IS_HTX_STRM(chn_strm(chn))) {
3325 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3326 WILL_LJMP(lua_error(L));
3327 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003328
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003329 offset = co_data(chn);
3330 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003331
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003332 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3333 if (filter && !hlua_filter_from_payload(filter))
3334 WILL_LJMP(lua_error(L));
3335
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003336 if (!ci_data(chn) && channel_input_closed(chn)) {
3337 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003338 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003339 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003341 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003342 return 1;
3343}
3344
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345/* [ DEPRECATED ]
3346 *
3347 * Get all input data foud in the channel's buffer. The data are removed from
3348 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3349 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003350 *
3351 * From an action, All input data are considered. For a filter, the offset and
3352 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354__LJMP static int hlua_channel_get(lua_State *L)
3355{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003356 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003357 struct filter *filter;
3358 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003359 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003360
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003361 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003362 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3363 if (IS_HTX_STRM(chn_strm(chn))) {
3364 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3365 WILL_LJMP(lua_error(L));
3366 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003367
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368 offset = co_data(chn);
3369 len = ci_data(chn);
3370
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003371 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3372 if (filter && !hlua_filter_from_payload(filter))
3373 WILL_LJMP(lua_error(L));
3374
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003375 if (!ci_data(chn) && channel_input_closed(chn)) {
3376 lua_pushnil(L);
3377 return 1;
3378 }
3379
3380 ret = _hlua_channel_dup(chn, L, offset, len);
3381 _hlua_channel_delete(chn, offset, ret);
3382 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003383}
3384
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003385/* This functions consumes and returns one line. If the channel is closed,
3386 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003387 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003388 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003389 *
3390 * From an action, All input data are considered. For a filter, the offset and
3391 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003392 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003393__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003394{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003395 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003396 struct filter *filter;
3397 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003398 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003399
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003400 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003401
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003402 offset = co_data(chn);
3403 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003404
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003405 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3406 if (filter && !hlua_filter_from_payload(filter))
3407 WILL_LJMP(lua_error(L));
3408
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003409 if (!ci_data(chn) && channel_input_closed(chn)) {
3410 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003412 }
3413
3414 for (l = 0; l < len; l++) {
3415 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3416 len = l+1;
3417 goto dup;
3418 }
3419 }
3420
3421 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3422 /* Yield waiting for more data */
3423 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3424 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003425
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003426 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003427 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003428 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003429 return 1;
3430}
3431
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003432/* [ DEPRECATED ]
3433 *
3434 * Check arguments for the function "hlua_channel_getline_yield".
3435 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003436__LJMP static int hlua_channel_getline(lua_State *L)
3437{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003438 struct channel *chn;
3439
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003440 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003441 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3442 if (IS_HTX_STRM(chn_strm(chn))) {
3443 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3444 WILL_LJMP(lua_error(L));
3445 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003446 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3447}
3448
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003449/* Retrieves a given amount of input data at the given offset. By default all
3450 * available input data are returned. The offset may be negactive to start from
3451 * the end of input data. The length may be -1 to set it to the maximum buffer
3452 * size.
3453 */
3454__LJMP static int hlua_channel_get_data(lua_State *L)
3455{
3456 struct channel *chn;
3457
3458 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3459 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3460 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3461 if (IS_HTX_STRM(chn_strm(chn))) {
3462 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3463 WILL_LJMP(lua_error(L));
3464 }
3465 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3466}
3467
3468/* Retrieves a given amount of input data at the given offset. By default all
3469 * available input data are returned. The offset may be negactive to start from
3470 * the end of input data. The length may be -1 to set it to the maximum buffer
3471 * size.
3472 */
3473__LJMP static int hlua_channel_get_line(lua_State *L)
3474{
3475 struct channel *chn;
3476
3477 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3478 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3479 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3480 if (IS_HTX_STRM(chn_strm(chn))) {
3481 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3482 WILL_LJMP(lua_error(L));
3483 }
3484 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3485}
3486
3487/* Appends a string into the input side of channel. It returns the length of the
3488 * written string, or -1 if the channel is closed or if the buffer size is too
3489 * little for the data. 0 may be returned if nothing is copied. This function
3490 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003491 *
3492 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003493 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003494__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003495{
Christopher Faulet23976d92021-08-06 09:59:49 +02003496 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003497 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003498 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003499 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003500 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003501
3502 MAY_LJMP(check_args(L, 2, "append"));
3503 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003504 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003505 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003506 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003507 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003508 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003509
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510 offset = co_data(chn);
3511 len = ci_data(chn);
3512
3513 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3514 if (filter && !hlua_filter_from_payload(filter))
3515 WILL_LJMP(lua_error(L));
3516
3517 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3518 if (ret > 0 && filter) {
3519 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3520
3521 flt_update_offsets(filter, chn, ret);
3522 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3523 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003524 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003525 return 1;
3526}
3527
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003528/* Prepends a string into the input side of channel. It returns the length of the
3529 * written string, or -1 if the channel is closed or if the buffer size is too
3530 * little for the data. 0 may be returned if nothing is copied. This function
3531 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003532 *
3533 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003534 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003536{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003537 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003538 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003539 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003540 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003541 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003542
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003543 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003544 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003545 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3546 if (IS_HTX_STRM(chn_strm(chn))) {
3547 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3548 WILL_LJMP(lua_error(L));
3549 }
3550
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 offset = co_data(chn);
3552 len = ci_data(chn);
3553
3554 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3555 if (filter && !hlua_filter_from_payload(filter))
3556 WILL_LJMP(lua_error(L));
3557
3558 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3559 if (ret > 0 && filter) {
3560 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3561
3562 flt_update_offsets(filter, chn, ret);
3563 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3564 }
3565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 lua_pushinteger(L, ret);
3567 return 1;
3568}
3569
3570/* Inserts a given amount of input data at the given offset by a string
3571 * content. By default the string is appended at the end of input data. It
3572 * returns the length of the written string, or -1 if the channel is closed or
3573 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 *
3575 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003576 */
3577__LJMP static int hlua_channel_insert_data(lua_State *L)
3578{
3579 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003580 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003583 int ret, offset;
3584
3585 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3586 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3587 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3588 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589
3590 output = co_data(chn);
3591 input = ci_data(chn);
3592
3593 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3594 if (filter && !hlua_filter_from_payload(filter))
3595 WILL_LJMP(lua_error(L));
3596
3597 offset = input + output;
3598 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003600 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003601 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 if (offset < output || offset > output + input) {
3604 lua_pushfstring(L, "offset out of range.");
3605 WILL_LJMP(lua_error(L));
3606 }
3607 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003608 if (IS_HTX_STRM(chn_strm(chn))) {
3609 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3610 WILL_LJMP(lua_error(L));
3611 }
3612
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003613 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3614 if (ret > 0 && filter) {
3615 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003616
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003617 flt_update_offsets(filter, chn, ret);
3618 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003619 }
3620
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621 lua_pushinteger(L, ret);
3622 return 1;
3623}
3624/* Replaces a given amount of input data at the given offset by a string
3625 * content. By default all remaining data are removed (offset = 0 and len =
3626 * -1). It returns the length of the written string, or -1 if the channel is
3627 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003628 *
3629 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 */
3631__LJMP static int hlua_channel_set_data(lua_State *L)
3632{
3633 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003634 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003636 size_t sz, input, output;
3637 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003638
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3640 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3641 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3642 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003643
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003644 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003645 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003646 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003647 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003648
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003649 output = co_data(chn);
3650 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3653 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003655
3656 offset = output;
3657 if (lua_gettop(L) > 2) {
3658 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3659 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003660 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003661 offset += output;
3662 if (offset < output || offset > input + output) {
3663 lua_pushfstring(L, "offset out of range.");
3664 WILL_LJMP(lua_error(L));
3665 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666 }
3667
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003668 len = output + input - offset;
3669 if (lua_gettop(L) == 4) {
3670 len = MAY_LJMP(luaL_checkinteger(L, 4));
3671 if (!len)
3672 goto set;
3673 if (len == -1)
3674 len = output + input - offset;
3675 if (len < 0 || offset + len > output + input) {
3676 lua_pushfstring(L, "length out of range.");
3677 WILL_LJMP(lua_error(L));
3678 }
3679 }
3680
3681 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003682 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003683 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003684 lua_pushinteger(L, -1);
3685 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003686 _hlua_channel_delete(chn, offset, len);
3687 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3688 if (filter) {
3689 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3690
3691 len -= (ret > 0 ? ret : 0);
3692 flt_update_offsets(filter, chn, -len);
3693 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3694 }
3695
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003696 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003697 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003698 return 1;
3699}
3700
3701/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003702 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704 *
3705 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003706 */
3707__LJMP static int hlua_channel_del_data(lua_State *L)
3708{
3709 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003710 struct filter *filter;
3711 size_t input, output;
3712 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003713
3714 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3715 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3716 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003718 if (IS_HTX_STRM(chn_strm(chn))) {
3719 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3720 WILL_LJMP(lua_error(L));
3721 }
3722
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003723 output = co_data(chn);
3724 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003725
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003726 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3727 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003728 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729
3730 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003731 if (lua_gettop(L) > 1) {
3732 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003733 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003734 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003735 offset += output;
3736 if (offset < output || offset > input + output) {
3737 lua_pushfstring(L, "offset out of range.");
3738 WILL_LJMP(lua_error(L));
3739 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003740 }
3741
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003742 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003743 if (lua_gettop(L) == 3) {
3744 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003745 if (!len)
3746 goto end;
3747 if (len == -1)
3748 len = output + input - offset;
3749 if (len < 0 || offset + len > output + input) {
3750 lua_pushfstring(L, "length out of range.");
3751 WILL_LJMP(lua_error(L));
3752 }
3753 }
3754
3755 _hlua_channel_delete(chn, offset, len);
3756 if (filter) {
3757 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3758
3759 flt_update_offsets(filter, chn, -len);
3760 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3761 }
3762
3763 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003764 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003765 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003766}
3767
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003768/* Append data in the output side of the buffer. This data is immediately
3769 * sent. The function returns the amount of data written. If the buffer
3770 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003771 * if the channel is closed.
3772 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003773__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003774{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003775 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003776 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003777 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003778 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003779 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003780 struct hlua *hlua;
3781
3782 /* Get hlua struct, or NULL if we execute from main lua state */
3783 hlua = hlua_gethlua(L);
3784 if (!hlua) {
3785 lua_pushnil(L);
3786 return 1;
3787 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003788
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003789 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3790 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3791 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003792
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003793 offset = co_data(chn);
3794 len = ci_data(chn);
3795
3796 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3797 if (filter && !hlua_filter_from_payload(filter))
3798 WILL_LJMP(lua_error(L));
3799
3800
Willy Tarreau47860ed2015-03-10 14:07:50 +01003801 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003802 lua_pushinteger(L, -1);
3803 return 1;
3804 }
3805
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003806 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003807 if (len > sz -l) {
3808 if (filter) {
3809 lua_pushinteger(L, -1);
3810 return 1;
3811 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003812 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003813 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003814
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003815 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003816 if (ret == -1) {
3817 lua_pop(L, 1);
3818 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003819 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003820 }
3821 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003822 if (filter) {
3823 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3824
3825
3826 flt_update_offsets(filter, chn, ret);
3827 FLT_OFF(filter, chn) += ret;
3828 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3829 }
3830 else
3831 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003832
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003833 l += ret;
3834 lua_pop(L, 1);
3835 lua_pushinteger(L, l);
3836 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003837
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 if (l < sz) {
3839 /* Yield only if the channel's output is not empty.
3840 * Otherwise it means we cannot add more data. */
3841 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003842 return 1;
3843
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003844 /* If we are waiting for space in the response buffer, we
3845 * must set the flag WAKERESWR. This flag required the task
3846 * wake up if any activity is detected on the response buffer.
3847 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003848 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003849 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003850 else
3851 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003852 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003853 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003854
3855 return 1;
3856}
3857
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003858/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003859 * yield the LUA process, and resume it without checking the
3860 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003861 *
3862 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003863 */
3864__LJMP static int hlua_channel_send(lua_State *L)
3865{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003866 struct channel *chn;
3867
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003869 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3870 if (IS_HTX_STRM(chn_strm(chn))) {
3871 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3872 WILL_LJMP(lua_error(L));
3873 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003874 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003875 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003876}
3877
3878/* This function forward and amount of butes. The data pass from
3879 * the input side of the buffer to the output side, and can be
3880 * forwarded. This function never fails.
3881 *
3882 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003883 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003884 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003885__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003886{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003887 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003888 struct filter *filter;
3889 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003890 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003891 struct hlua *hlua;
3892
3893 /* Get hlua struct, or NULL if we execute from main lua state */
3894 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003895 if (!hlua) {
3896 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003897 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003898 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003899
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003900 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003901 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902 l = MAY_LJMP(luaL_checkinteger(L, -1));
3903
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003904 offset = co_data(chn);
3905 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003906
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003907 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3908 if (filter && !hlua_filter_from_payload(filter))
3909 WILL_LJMP(lua_error(L));
3910
3911 max = fwd - l;
3912 if (max > len)
3913 max = len;
3914
3915 if (filter) {
3916 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3917
3918 FLT_OFF(filter, chn) += max;
3919 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3920 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3921 }
3922 else
3923 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003924
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003925 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003926 lua_pop(L, 1);
3927 lua_pushinteger(L, l);
3928
3929 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003930 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003931 /* The the input channel or the output channel are closed, we
3932 * must return the amount of data forwarded.
3933 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003934 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003935 return 1;
3936
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003937 /* If we are waiting for space data in the response buffer, we
3938 * must set the flag WAKERESWR. This flag required the task
3939 * wake up if any activity is detected on the response buffer.
3940 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003941 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003942 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003943 else
3944 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003945
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003946 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003947 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003948 }
3949
3950 return 1;
3951}
3952
3953/* Just check the input and prepare the stack for the previous
3954 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003955 *
3956 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003957 */
3958__LJMP static int hlua_channel_forward(lua_State *L)
3959{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003960 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003961
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003962 MAY_LJMP(check_args(L, 2, "forward"));
3963 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3964 if (IS_HTX_STRM(chn_strm(chn))) {
3965 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3966 WILL_LJMP(lua_error(L));
3967 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003968 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003969 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003970}
3971
3972/* Just returns the number of bytes available in the input
3973 * side of the buffer. This function never fails.
3974 */
3975__LJMP static int hlua_channel_get_in_len(lua_State *L)
3976{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003977 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003978 struct filter *filter;
3979 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003980
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003981 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003982 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003983
3984 output = co_data(chn);
3985 input = ci_data(chn);
3986 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3987 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3988 lua_pushinteger(L, input);
3989 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003990 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003991
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003992 lua_pushinteger(L, htx->data - co_data(chn));
3993 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003994 return 1;
3995}
3996
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003997/* Returns true if the channel is full. */
3998__LJMP static int hlua_channel_is_full(lua_State *L)
3999{
4000 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004001
4002 MAY_LJMP(check_args(L, 1, "is_full"));
4003 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004004 /* ignore the reserve, we are not on a producer side (ie in an
4005 * applet).
4006 */
4007 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004008 return 1;
4009}
4010
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004011/* Returns true if the channel may still receive data. */
4012__LJMP static int hlua_channel_may_recv(lua_State *L)
4013{
4014 struct channel *chn;
4015
4016 MAY_LJMP(check_args(L, 1, "may_recv"));
4017 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4018 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4019 return 1;
4020}
4021
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004022/* Returns true if the channel is the response channel. */
4023__LJMP static int hlua_channel_is_resp(lua_State *L)
4024{
4025 struct channel *chn;
4026
4027 MAY_LJMP(check_args(L, 1, "is_resp"));
4028 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4029
4030 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4031 return 1;
4032}
4033
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004034/* Just returns the number of bytes available in the output
4035 * side of the buffer. This function never fails.
4036 */
4037__LJMP static int hlua_channel_get_out_len(lua_State *L)
4038{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004039 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004040 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004041
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004042 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004043 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004044
4045 output = co_data(chn);
4046 input = ci_data(chn);
4047 hlua_channel_filter(L, 1, chn, &output, &input);
4048
4049 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004050 return 1;
4051}
4052
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004053/*
4054 *
4055 *
4056 * Class Fetches
4057 *
4058 *
4059 */
4060
4061/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004062 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004063 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004064__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004065{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004066 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004067}
4068
4069/* This function creates and push in the stack a fetch object according
4070 * with a current TXN.
4071 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004072static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004073{
Willy Tarreau7073c472015-04-06 11:15:40 +02004074 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004075
4076 /* Check stack size. */
4077 if (!lua_checkstack(L, 3))
4078 return 0;
4079
4080 /* Create the object: obj[0] = userdata.
4081 * Note that the base of the Fetches object is the
4082 * transaction object.
4083 */
4084 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004085 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004086 lua_rawseti(L, -2, 0);
4087
Willy Tarreau7073c472015-04-06 11:15:40 +02004088 hsmp->s = txn->s;
4089 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004090 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004091 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004092
4093 /* Pop a class sesison metatable and affect it to the userdata. */
4094 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4095 lua_setmetatable(L, -2);
4096
4097 return 1;
4098}
4099
4100/* This function is an LUA binding. It is called with each sample-fetch.
4101 * It uses closure argument to store the associated sample-fetch. It
4102 * returns only one argument or throws an error. An error is thrown
4103 * only if an error is encountered during the argument parsing. If
4104 * the "sample-fetch" function fails, nil is returned.
4105 */
4106__LJMP static int hlua_run_sample_fetch(lua_State *L)
4107{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004108 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004109 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004110 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004111 int i;
4112 struct sample smp;
4113
4114 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004115 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004116
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004117 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004118 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004119
Thierry FOURNIERca988662015-12-20 18:43:03 +01004120 /* Check execution authorization. */
4121 if (f->use & SMP_USE_HTTP_ANY &&
4122 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4123 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4124 "is not available in Lua services", f->kw);
4125 WILL_LJMP(lua_error(L));
4126 }
4127
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004128 /* Get extra arguments. */
4129 for (i = 0; i < lua_gettop(L) - 1; i++) {
4130 if (i >= ARGM_NBARGS)
4131 break;
4132 hlua_lua2arg(L, i + 2, &args[i]);
4133 }
4134 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004135 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004136
4137 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004138 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139
4140 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004141 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004142 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004143 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004144 }
4145
4146 /* Initialise the sample. */
4147 memset(&smp, 0, sizeof(smp));
4148
4149 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004150 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004151 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004152 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004153 lua_pushstring(L, "");
4154 else
4155 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004156 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004157 }
4158
4159 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004160 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004161 hlua_smp2lua_str(L, &smp);
4162 else
4163 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004164
4165 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004166 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004167 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004168
4169 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004170 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004171 WILL_LJMP(lua_error(L));
4172 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004173}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004174
4175/*
4176 *
4177 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004178 * Class Converters
4179 *
4180 *
4181 */
4182
4183/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004184 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004185 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004186__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004187{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004188 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004189}
4190
4191/* This function creates and push in the stack a Converters object
4192 * according with a current TXN.
4193 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004194static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004195{
Willy Tarreau7073c472015-04-06 11:15:40 +02004196 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004197
4198 /* Check stack size. */
4199 if (!lua_checkstack(L, 3))
4200 return 0;
4201
4202 /* Create the object: obj[0] = userdata.
4203 * Note that the base of the Converters object is the
4204 * same than the TXN object.
4205 */
4206 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004207 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 lua_rawseti(L, -2, 0);
4209
Willy Tarreau7073c472015-04-06 11:15:40 +02004210 hsmp->s = txn->s;
4211 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004212 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004213 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004214
Willy Tarreau87b09662015-04-03 00:22:06 +02004215 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004216 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4217 lua_setmetatable(L, -2);
4218
4219 return 1;
4220}
4221
4222/* This function is an LUA binding. It is called with each converter.
4223 * It uses closure argument to store the associated converter. It
4224 * returns only one argument or throws an error. An error is thrown
4225 * only if an error is encountered during the argument parsing. If
4226 * the converter function function fails, nil is returned.
4227 */
4228__LJMP static int hlua_run_sample_conv(lua_State *L)
4229{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004230 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004231 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004232 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004233 int i;
4234 struct sample smp;
4235
4236 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004237 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004239 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004240 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004241
4242 /* Get extra arguments. */
4243 for (i = 0; i < lua_gettop(L) - 2; i++) {
4244 if (i >= ARGM_NBARGS)
4245 break;
4246 hlua_lua2arg(L, i + 3, &args[i]);
4247 }
4248 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004249 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004250
4251 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004252 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004253
4254 /* Run the special args checker. */
4255 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4256 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004257 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004258 }
4259
4260 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004261 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004262 if (!hlua_lua2smp(L, 2, &smp)) {
4263 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004264 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004265 }
4266
Willy Tarreau1777ea62016-03-10 16:15:46 +01004267 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4268
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004269 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004270 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004271 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004272 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004273 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004274 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004275 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4276 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004277 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004278 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004279 }
4280
4281 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004282 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004283 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004284 lua_pushstring(L, "");
4285 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004286 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004287 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004288 }
4289
4290 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004291 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004292 hlua_smp2lua_str(L, &smp);
4293 else
4294 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004295 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004296 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004297 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004298
4299 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004300 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004301 WILL_LJMP(lua_error(L));
4302 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004303}
4304
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004305/*
4306 *
4307 *
4308 * Class AppletTCP
4309 *
4310 *
4311 */
4312
4313/* Returns a struct hlua_txn if the stack entry "ud" is
4314 * a class stream, otherwise it throws an error.
4315 */
4316__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4317{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004318 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004319}
4320
4321/* This function creates and push in the stack an Applet object
4322 * according with a current TXN.
4323 */
4324static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4325{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004326 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004327 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004328 struct proxy *p;
4329
4330 ALREADY_CHECKED(s);
4331 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004332
4333 /* Check stack size. */
4334 if (!lua_checkstack(L, 3))
4335 return 0;
4336
4337 /* Create the object: obj[0] = userdata.
4338 * Note that the base of the Converters object is the
4339 * same than the TXN object.
4340 */
4341 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004342 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004343 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004344 luactx->appctx = ctx;
4345 luactx->htxn.s = s;
4346 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004347
4348 /* Create the "f" field that contains a list of fetches. */
4349 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004350 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004351 return 0;
4352 lua_settable(L, -3);
4353
4354 /* Create the "sf" field that contains a list of stringsafe fetches. */
4355 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004356 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004357 return 0;
4358 lua_settable(L, -3);
4359
4360 /* Create the "c" field that contains a list of converters. */
4361 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004362 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004363 return 0;
4364 lua_settable(L, -3);
4365
4366 /* Create the "sc" field that contains a list of stringsafe converters. */
4367 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004368 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004369 return 0;
4370 lua_settable(L, -3);
4371
4372 /* Pop a class stream metatable and affect it to the table. */
4373 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4374 lua_setmetatable(L, -2);
4375
4376 return 1;
4377}
4378
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004379__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4380{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004381 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004382 struct stream *s;
4383 const char *name;
4384 size_t len;
4385 struct sample smp;
4386
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004387 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4388 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004389
4390 /* It is useles to retrieve the stream, but this function
4391 * runs only in a stream context.
4392 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004393 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004394 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004395 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004396
4397 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004398 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004399 hlua_lua2smp(L, 3, &smp);
4400
4401 /* Store the sample in a variable. */
4402 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004403
4404 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4405 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4406 else
4407 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4408
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004409 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004410}
4411
4412__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4413{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004414 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004415 struct stream *s;
4416 const char *name;
4417 size_t len;
4418 struct sample smp;
4419
4420 MAY_LJMP(check_args(L, 2, "unset_var"));
4421
4422 /* It is useles to retrieve the stream, but this function
4423 * runs only in a stream context.
4424 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004425 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004426 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004427 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004428
4429 /* Unset the variable. */
4430 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004431 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4432 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433}
4434
4435__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4436{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004437 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438 struct stream *s;
4439 const char *name;
4440 size_t len;
4441 struct sample smp;
4442
4443 MAY_LJMP(check_args(L, 2, "get_var"));
4444
4445 /* It is useles to retrieve the stream, but this function
4446 * runs only in a stream context.
4447 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004448 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004449 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004450 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004451
4452 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004453 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004454 lua_pushnil(L);
4455 return 1;
4456 }
4457
4458 return hlua_smp2lua(L, &smp);
4459}
4460
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004461__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4462{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004463 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4464 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004465 struct hlua *hlua;
4466
4467 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004468 if (!s->hlua)
4469 return 0;
4470 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004471
4472 MAY_LJMP(check_args(L, 2, "set_priv"));
4473
4474 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004475 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004476
4477 /* Get and store new value. */
4478 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4479 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4480
4481 return 0;
4482}
4483
4484__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4485{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4487 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004488 struct hlua *hlua;
4489
4490 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004491 if (!s->hlua) {
4492 lua_pushnil(L);
4493 return 1;
4494 }
4495 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004496
4497 /* Push configuration index in the stack. */
4498 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4499
4500 return 1;
4501}
4502
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004503/* If expected data not yet available, it returns a yield. This function
4504 * consumes the data in the buffer. It returns a string containing the
4505 * data. This string can be empty.
4506 */
4507__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4508{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004509 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004510 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004511 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004512 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004513 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004514 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004515 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004517 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004518 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004519
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004520 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004522 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004523 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004524 }
4525
4526 /* End of data: commit the total strings and return. */
4527 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004528 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529 return 1;
4530 }
4531
4532 /* Ensure that the block 2 length is usable. */
4533 if (ret == 1)
4534 len2 = 0;
4535
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004536 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004537 luaL_addlstring(&luactx->b, blk1, len1);
4538 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004539
4540 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004541 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004542 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004543 return 1;
4544}
4545
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004546/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004547__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4548{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004549 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004550
4551 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004552 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553
4554 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4555}
4556
4557/* If expected data not yet available, it returns a yield. This function
4558 * consumes the data in the buffer. It returns a string containing the
4559 * data. This string can be empty.
4560 */
4561__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4562{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004563 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004564 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004565 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004567 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004568 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004569 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004570 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004571
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004572 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004573 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004574
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004575 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004577 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004578 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004579 }
4580
4581 /* End of data: commit the total strings and return. */
4582 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004583 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584 return 1;
4585 }
4586
4587 /* Ensure that the block 2 length is usable. */
4588 if (ret == 1)
4589 len2 = 0;
4590
4591 if (len == -1) {
4592
4593 /* If len == -1, catenate all the data avalaile and
4594 * yield because we want to get all the data until
4595 * the end of data stream.
4596 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004597 luaL_addlstring(&luactx->b, blk1, len1);
4598 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004599 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004600 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004601 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602
4603 } else {
4604
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004605 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004606 if (len1 > len)
4607 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004608 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004609 len -= len1;
4610
4611 /* Copy the second block. */
4612 if (len2 > len)
4613 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004614 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 len -= len2;
4616
4617 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004618 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004619
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004620 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004621 if (len > 0) {
4622 lua_pushinteger(L, len);
4623 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004624 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004625 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626 }
4627
4628 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004629 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004630 return 1;
4631 }
4632
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004633 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004634 hlua_pusherror(L, "Lua: internal error");
4635 WILL_LJMP(lua_error(L));
4636 return 0;
4637}
4638
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004639/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004640__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4641{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004642 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004643 int len = -1;
4644
4645 if (lua_gettop(L) > 2)
4646 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4647 if (lua_gettop(L) >= 2) {
4648 len = MAY_LJMP(luaL_checkinteger(L, 2));
4649 lua_pop(L, 1);
4650 }
4651
4652 /* Confirm or set the required length */
4653 lua_pushinteger(L, len);
4654
4655 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004656 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004657
4658 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4659}
4660
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004661/* Append data in the output side of the buffer. This data is immediately
4662 * sent. The function returns the amount of data written. If the buffer
4663 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004664 * if the channel is closed.
4665 */
4666__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4667{
4668 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004669 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004670 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4671 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004672 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004673 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004674 int max;
4675
4676 /* Get the max amount of data which can write as input in the channel. */
4677 max = channel_recv_max(chn);
4678 if (max > (len - l))
4679 max = len - l;
4680
4681 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004682 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004683
4684 /* update counters. */
4685 l += max;
4686 lua_pop(L, 1);
4687 lua_pushinteger(L, l);
4688
4689 /* If some data is not send, declares the situation to the
4690 * applet, and returns a yield.
4691 */
4692 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004693 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004694 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004695 }
4696
4697 return 1;
4698}
4699
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004700/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004701 * yield the LUA process, and resume it without checking the
4702 * input arguments.
4703 */
4704__LJMP static int hlua_applet_tcp_send(lua_State *L)
4705{
4706 MAY_LJMP(check_args(L, 2, "send"));
4707 lua_pushinteger(L, 0);
4708
4709 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4710}
4711
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004712/*
4713 *
4714 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004716 *
4717 *
4718 */
4719
4720/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004721 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004722 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004723__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004724{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004725 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004726}
4727
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004728/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004730 * It relies on the caller to have already reserved the room in ctx->svcctx
4731 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004732 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004733static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004734{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004735 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004736 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004737 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004738 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004739 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004740 struct htx *htx;
4741 struct htx_blk *blk;
4742 struct htx_sl *sl;
4743 struct ist path;
4744 unsigned long long len = 0;
4745 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004746 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747
4748 /* Check stack size. */
4749 if (!lua_checkstack(L, 3))
4750 return 0;
4751
4752 /* Create the object: obj[0] = userdata.
4753 * Note that the base of the Converters object is the
4754 * same than the TXN object.
4755 */
4756 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004757 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004758 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004759 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004760 http_ctx->status = 200; /* Default status code returned. */
4761 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004762 luactx->htxn.s = s;
4763 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004764
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004765 /* Create the "f" field that contains a list of fetches. */
4766 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004768 return 0;
4769 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004770
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004771 /* Create the "sf" field that contains a list of stringsafe fetches. */
4772 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004773 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004774 return 0;
4775 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004776
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004777 /* Create the "c" field that contains a list of converters. */
4778 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004779 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004780 return 0;
4781 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004782
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004783 /* Create the "sc" field that contains a list of stringsafe converters. */
4784 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004785 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004786 return 0;
4787 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004788
Christopher Fauleta2097962019-07-15 16:25:33 +02004789 htx = htxbuf(&s->req.buf);
4790 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004791 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004792 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004793
Christopher Fauleta2097962019-07-15 16:25:33 +02004794 /* Stores the request method. */
4795 lua_pushstring(L, "method");
4796 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4797 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004798
Christopher Fauleta2097962019-07-15 16:25:33 +02004799 /* Stores the http version. */
4800 lua_pushstring(L, "version");
4801 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4802 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004803
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 /* creates an array of headers. hlua_http_get_headers() crates and push
4805 * the array on the top of the stack.
4806 */
4807 lua_pushstring(L, "headers");
4808 htxn.s = s;
4809 htxn.p = px;
4810 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004811 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004812 return 0;
4813 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004814
Amaury Denoyellec453f952021-07-06 11:40:12 +02004815 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4816 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004817 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004818 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004819
Christopher Fauleta2097962019-07-15 16:25:33 +02004820 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004821 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004822 q = p;
4823 while (q < end && *q != '?')
4824 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004826 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004827 lua_pushstring(L, "path");
4828 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004829 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004830
Christopher Fauleta2097962019-07-15 16:25:33 +02004831 /* Stores the query string. */
4832 lua_pushstring(L, "qs");
4833 if (*q == '?')
4834 q++;
4835 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004836 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004837 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004838
Christopher Fauleta2097962019-07-15 16:25:33 +02004839 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4840 struct htx_blk *blk = htx_get_blk(htx, pos);
4841 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004842
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004843 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004844 break;
4845 if (type == HTX_BLK_DATA)
4846 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004847 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004848 if (htx->extra != ULLONG_MAX)
4849 len += htx->extra;
4850
4851 /* Stores the request path. */
4852 lua_pushstring(L, "length");
4853 lua_pushinteger(L, len);
4854 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004855
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004856 /* Create an empty array of HTTP request headers. */
4857 lua_pushstring(L, "response");
4858 lua_newtable(L);
4859 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004861 /* Pop a class stream metatable and affect it to the table. */
4862 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4863 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004864
4865 return 1;
4866}
4867
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004868__LJMP static int hlua_applet_http_set_var(lua_State *L)
4869{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004871 struct stream *s;
4872 const char *name;
4873 size_t len;
4874 struct sample smp;
4875
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004876 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4877 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004878
4879 /* It is useles to retrieve the stream, but this function
4880 * runs only in a stream context.
4881 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004882 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004884 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004885
4886 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004887 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888 hlua_lua2smp(L, 3, &smp);
4889
4890 /* Store the sample in a variable. */
4891 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004892
4893 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4894 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4895 else
4896 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4897
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004898 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004899}
4900
4901__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4902{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004903 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904 struct stream *s;
4905 const char *name;
4906 size_t len;
4907 struct sample smp;
4908
4909 MAY_LJMP(check_args(L, 2, "unset_var"));
4910
4911 /* It is useles to retrieve the stream, but this function
4912 * runs only in a stream context.
4913 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004914 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004915 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004916 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004917
4918 /* Unset the variable. */
4919 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004920 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4921 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922}
4923
4924__LJMP static int hlua_applet_http_get_var(lua_State *L)
4925{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004926 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927 struct stream *s;
4928 const char *name;
4929 size_t len;
4930 struct sample smp;
4931
4932 MAY_LJMP(check_args(L, 2, "get_var"));
4933
4934 /* It is useles to retrieve the stream, but this function
4935 * runs only in a stream context.
4936 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004937 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004938 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004939 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004940
4941 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004942 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004943 lua_pushnil(L);
4944 return 1;
4945 }
4946
4947 return hlua_smp2lua(L, &smp);
4948}
4949
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004950__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4951{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004952 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4953 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004954 struct hlua *hlua;
4955
4956 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004957 if (!s->hlua)
4958 return 0;
4959 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004960
4961 MAY_LJMP(check_args(L, 2, "set_priv"));
4962
4963 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004964 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004965
4966 /* Get and store new value. */
4967 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4968 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4969
4970 return 0;
4971}
4972
4973__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4974{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4976 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004977 struct hlua *hlua;
4978
4979 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004980 if (!s->hlua) {
4981 lua_pushnil(L);
4982 return 1;
4983 }
4984 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004985
4986 /* Push configuration index in the stack. */
4987 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4988
4989 return 1;
4990}
4991
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004992/* If expected data not yet available, it returns a yield. This function
4993 * consumes the data in the buffer. It returns a string containing the
4994 * data. This string can be empty.
4995 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004996__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004997{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004998 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004999 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005000 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005001 struct htx *htx;
5002 struct htx_blk *blk;
5003 size_t count;
5004 int stop = 0;
5005
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005006 htx = htx_from_buf(&req->buf);
5007 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005008 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005009
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005010 while (count && !stop && blk) {
5011 enum htx_blk_type type = htx_get_blk_type(blk);
5012 uint32_t sz = htx_get_blksz(blk);
5013 struct ist v;
5014 uint32_t vlen;
5015 char *nl;
5016
5017 vlen = sz;
5018 if (vlen > count) {
5019 if (type != HTX_BLK_DATA)
5020 break;
5021 vlen = count;
5022 }
5023
5024 switch (type) {
5025 case HTX_BLK_UNUSED:
5026 break;
5027
5028 case HTX_BLK_DATA:
5029 v = htx_get_blk_value(htx, blk);
5030 v.len = vlen;
5031 nl = istchr(v, '\n');
5032 if (nl != NULL) {
5033 stop = 1;
5034 vlen = nl - v.ptr + 1;
5035 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005036 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037 break;
5038
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005039 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005040 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005041 stop = 1;
5042 break;
5043
5044 default:
5045 break;
5046 }
5047
Willy Tarreau84240042022-02-28 16:51:23 +01005048 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005049 count -= vlen;
5050 if (sz == vlen)
5051 blk = htx_remove_blk(htx, blk);
5052 else {
5053 htx_cut_data_blk(htx, blk, vlen);
5054 break;
5055 }
5056 }
5057
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005058 /* The message was fully consumed and no more data are expected
5059 * (EOM flag set).
5060 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005061 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005062 stop = 1;
5063
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005064 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005065 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005066 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005067 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005068 }
5069
5070 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005071 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 return 1;
5073}
5074
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005075
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005076/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005077__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005078{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005079 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005080
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005081 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005082 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005083
Christopher Fauleta2097962019-07-15 16:25:33 +02005084 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005085}
5086
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005087/* If expected data not yet available, it returns a yield. This function
5088 * consumes the data in the buffer. It returns a string containing the
5089 * data. This string can be empty.
5090 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005091__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005092{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005093 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005094 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005095 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005096 struct htx *htx;
5097 struct htx_blk *blk;
5098 size_t count;
5099 int len;
5100
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005101 htx = htx_from_buf(&req->buf);
5102 len = MAY_LJMP(luaL_checkinteger(L, 2));
5103 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005104 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105 while (count && len && blk) {
5106 enum htx_blk_type type = htx_get_blk_type(blk);
5107 uint32_t sz = htx_get_blksz(blk);
5108 struct ist v;
5109 uint32_t vlen;
5110
5111 vlen = sz;
5112 if (len > 0 && vlen > len)
5113 vlen = len;
5114 if (vlen > count) {
5115 if (type != HTX_BLK_DATA)
5116 break;
5117 vlen = count;
5118 }
5119
5120 switch (type) {
5121 case HTX_BLK_UNUSED:
5122 break;
5123
5124 case HTX_BLK_DATA:
5125 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005126 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005127 break;
5128
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005129 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005130 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131 len = 0;
5132 break;
5133
5134 default:
5135 break;
5136 }
5137
Willy Tarreau84240042022-02-28 16:51:23 +01005138 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005139 count -= vlen;
5140 if (len > 0)
5141 len -= vlen;
5142 if (sz == vlen)
5143 blk = htx_remove_blk(htx, blk);
5144 else {
5145 htx_cut_data_blk(htx, blk, vlen);
5146 break;
5147 }
5148 }
5149
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005150 /* The message was fully consumed and no more data are expected
5151 * (EOM flag set).
5152 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005153 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005154 len = 0;
5155
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005156 htx_to_buf(htx, &req->buf);
5157
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005158 /* If we are no other data available, yield waiting for new data. */
5159 if (len) {
5160 if (len > 0) {
5161 lua_pushinteger(L, len);
5162 lua_replace(L, 2);
5163 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005164 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005165 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005166 }
5167
5168 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005169 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005170 return 1;
5171}
5172
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005173/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005174__LJMP static int hlua_applet_http_recv(lua_State *L)
5175{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005176 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005177 int len = -1;
5178
5179 /* Check arguments. */
5180 if (lua_gettop(L) > 2)
5181 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5182 if (lua_gettop(L) >= 2) {
5183 len = MAY_LJMP(luaL_checkinteger(L, 2));
5184 lua_pop(L, 1);
5185 }
5186
Christopher Fauleta2097962019-07-15 16:25:33 +02005187 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005188
Christopher Fauleta2097962019-07-15 16:25:33 +02005189 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005190 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005191
Christopher Fauleta2097962019-07-15 16:25:33 +02005192 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005193}
5194
5195/* Append data in the output side of the buffer. This data is immediately
5196 * sent. The function returns the amount of data written. If the buffer
5197 * cannot contain the data, the function yields. The function returns -1
5198 * if the channel is closed.
5199 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005200__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005201{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005202 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005203 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005204 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005205 struct htx *htx = htx_from_buf(&res->buf);
5206 const char *data;
5207 size_t len;
5208 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5209 int max;
5210
Christopher Faulet9060fc02019-07-03 11:39:30 +02005211 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005212 if (!max)
5213 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005214
5215 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5216
5217 /* Get the max amount of data which can write as input in the channel. */
5218 if (max > (len - l))
5219 max = len - l;
5220
5221 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005222 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005223 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005224
5225 /* update counters. */
5226 l += max;
5227 lua_pop(L, 1);
5228 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005229
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005230 /* If some data is not send, declares the situation to the
5231 * applet, and returns a yield.
5232 */
5233 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005234 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005235 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005236 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005237 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238 }
5239
Christopher Fauleta2097962019-07-15 16:25:33 +02005240 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005241 return 1;
5242}
5243
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005244/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005245 * yield the LUA process, and resume it without checking the
5246 * input arguments.
5247 */
5248__LJMP static int hlua_applet_http_send(lua_State *L)
5249{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005250 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005251 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005252
5253 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005254 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005255 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5256 WILL_LJMP(lua_error(L));
5257 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005258
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005259 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005260 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005261
Christopher Fauleta2097962019-07-15 16:25:33 +02005262 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005263}
5264
5265__LJMP static int hlua_applet_http_addheader(lua_State *L)
5266{
5267 const char *name;
5268 int ret;
5269
5270 MAY_LJMP(hlua_checkapplet_http(L, 1));
5271 name = MAY_LJMP(luaL_checkstring(L, 2));
5272 MAY_LJMP(luaL_checkstring(L, 3));
5273
5274 /* Push in the stack the "response" entry. */
5275 ret = lua_getfield(L, 1, "response");
5276 if (ret != LUA_TTABLE) {
5277 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5278 "is expected as an array. %s found", lua_typename(L, ret));
5279 WILL_LJMP(lua_error(L));
5280 }
5281
5282 /* check if the header is already registered if it is not
5283 * the case, register it.
5284 */
5285 ret = lua_getfield(L, -1, name);
5286 if (ret == LUA_TNIL) {
5287
5288 /* Entry not found. */
5289 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5290
5291 /* Insert the new header name in the array in the top of the stack.
5292 * It left the new array in the top of the stack.
5293 */
5294 lua_newtable(L);
5295 lua_pushvalue(L, 2);
5296 lua_pushvalue(L, -2);
5297 lua_settable(L, -4);
5298
5299 } else if (ret != LUA_TTABLE) {
5300
5301 /* corruption error. */
5302 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5303 "is expected as an array. %s found", name, lua_typename(L, ret));
5304 WILL_LJMP(lua_error(L));
5305 }
5306
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005307 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005308 * the header value as new entry.
5309 */
5310 lua_pushvalue(L, 3);
5311 ret = lua_rawlen(L, -2);
5312 lua_rawseti(L, -2, ret + 1);
5313 lua_pushboolean(L, 1);
5314 return 1;
5315}
5316
5317__LJMP static int hlua_applet_http_status(lua_State *L)
5318{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005319 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005320 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005321 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005322 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005323
5324 if (status < 100 || status > 599) {
5325 lua_pushboolean(L, 0);
5326 return 1;
5327 }
5328
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005329 http_ctx->status = status;
5330 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005331 lua_pushboolean(L, 1);
5332 return 1;
5333}
5334
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005335
Christopher Fauleta2097962019-07-15 16:25:33 +02005336__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005337{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005338 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005339 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005340 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005341 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 struct htx *htx;
5343 struct htx_sl *sl;
5344 struct h1m h1m;
5345 const char *status, *reason;
5346 const char *name, *value;
5347 size_t nlen, vlen;
5348 unsigned int flags;
5349
5350 /* Send the message at once. */
5351 htx = htx_from_buf(&res->buf);
5352 h1m_init_res(&h1m);
5353
5354 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005355 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5356 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005357 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005358 reason = http_get_reason(http_ctx->status);
5359 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5361 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5362 }
5363 else {
5364 flags = HTX_SL_F_IS_RESP;
5365 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5366 }
5367 if (!sl) {
5368 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005369 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005370 WILL_LJMP(lua_error(L));
5371 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005372 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005373
5374 /* Get the array associated to the field "response" in the object AppletHTTP. */
Aurelien DARRAGONcd341d52022-09-29 12:00:04 +02005375 /* FIXME: according to Lua doc, 0 is considered to be invalid index? */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005376 lua_pushvalue(L, 0);
5377 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5378 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005379 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380 WILL_LJMP(lua_error(L));
5381 }
5382
5383 /* Browse the list of headers. */
5384 lua_pushnil(L);
5385 while(lua_next(L, -2) != 0) {
5386 /* We expect a string as -2. */
5387 if (lua_type(L, -2) != LUA_TSTRING) {
5388 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005389 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005390 lua_typename(L, lua_type(L, -2)));
5391 WILL_LJMP(lua_error(L));
5392 }
5393 name = lua_tolstring(L, -2, &nlen);
5394
5395 /* We expect an array as -1. */
5396 if (lua_type(L, -1) != LUA_TTABLE) {
5397 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 +02005398 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005399 name,
5400 lua_typename(L, lua_type(L, -1)));
5401 WILL_LJMP(lua_error(L));
5402 }
5403
5404 /* Browse the table who is on the top of the stack. */
5405 lua_pushnil(L);
5406 while(lua_next(L, -2) != 0) {
5407 int id;
5408
5409 /* We expect a number as -2. */
5410 if (lua_type(L, -2) != LUA_TNUMBER) {
5411 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 +02005412 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005413 name,
5414 lua_typename(L, lua_type(L, -2)));
5415 WILL_LJMP(lua_error(L));
5416 }
5417 id = lua_tointeger(L, -2);
5418
5419 /* We expect a string as -2. */
5420 if (lua_type(L, -1) != LUA_TSTRING) {
5421 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 +02005422 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005423 name, id,
5424 lua_typename(L, lua_type(L, -1)));
5425 WILL_LJMP(lua_error(L));
5426 }
5427 value = lua_tolstring(L, -1, &vlen);
5428
5429 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005430 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5431 int ret;
5432
5433 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5434 if (ret < 0) {
5435 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5436 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5437 name);
5438 WILL_LJMP(lua_error(L));
5439 }
5440 else if (ret == 0)
5441 goto next; /* Skip it */
5442 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005443 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5444 struct ist v = ist2(value, vlen);
5445 int ret;
5446
5447 ret = h1_parse_cont_len_header(&h1m, &v);
5448 if (ret < 0) {
5449 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005450 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005451 name);
5452 WILL_LJMP(lua_error(L));
5453 }
5454 else if (ret == 0)
5455 goto next; /* Skip it */
5456 }
5457
5458 /* Add a new header */
5459 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5460 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005461 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005462 name);
5463 WILL_LJMP(lua_error(L));
5464 }
5465 next:
5466 /* Remove the array from the stack, and get next element with a remaining string. */
5467 lua_pop(L, 1);
5468 }
5469
5470 /* Remove the array from the stack, and get next element with a remaining string. */
5471 lua_pop(L, 1);
5472 }
5473
5474 if (h1m.flags & H1_MF_CHNK)
5475 h1m.flags &= ~H1_MF_CLEN;
5476 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5477 h1m.flags |= H1_MF_XFER_LEN;
5478
5479 /* Uset HTX start-line flags */
5480 if (h1m.flags & H1_MF_XFER_ENC)
5481 flags |= HTX_SL_F_XFER_ENC;
5482 if (h1m.flags & H1_MF_XFER_LEN) {
5483 flags |= HTX_SL_F_XFER_LEN;
5484 if (h1m.flags & H1_MF_CHNK)
5485 flags |= HTX_SL_F_CHNK;
5486 else if (h1m.flags & H1_MF_CLEN)
5487 flags |= HTX_SL_F_CLEN;
5488 if (h1m.body_len == 0)
5489 flags |= HTX_SL_F_BODYLESS;
5490 }
5491 sl->flags |= flags;
5492
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005493 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005494 * and the status code implies the presence of a message body, we must
5495 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005496 * for the keepalive compliance. If the applet announces a transfer-encoding
5497 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005498 */
5499 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005500 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005501 /* Add a new header */
5502 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5503 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5504 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005505 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005506 WILL_LJMP(lua_error(L));
5507 }
5508 }
5509
5510 /* Finalize headers. */
5511 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5512 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005513 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005514 WILL_LJMP(lua_error(L));
5515 }
5516
5517 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5518 b_reset(&res->buf);
5519 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5520 WILL_LJMP(lua_error(L));
5521 }
5522
5523 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005524 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005525
5526 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005527 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005528 return 0;
5529
5530}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005531/* We will build the status line and the headers of the HTTP response.
5532 * We will try send at once if its not possible, we give back the hand
5533 * waiting for more room.
5534 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005535__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005536{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005537 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005538 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005539 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005540
5541 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005542 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005543 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005544 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005545 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005546}
5547
5548
Christopher Fauleta2097962019-07-15 16:25:33 +02005549__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005550{
Christopher Fauleta2097962019-07-15 16:25:33 +02005551 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005552}
5553
Christopher Fauleta2097962019-07-15 16:25:33 +02005554/*
5555 *
5556 *
5557 * Class HTTP
5558 *
5559 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005560 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005561
5562/* Returns a struct hlua_txn if the stack entry "ud" is
5563 * a class stream, otherwise it throws an error.
5564 */
5565__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005566{
Christopher Fauleta2097962019-07-15 16:25:33 +02005567 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5568}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005569
Christopher Fauleta2097962019-07-15 16:25:33 +02005570/* This function creates and push in the stack a HTTP object
5571 * according with a current TXN.
5572 */
5573static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5574{
5575 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005576
Christopher Fauleta2097962019-07-15 16:25:33 +02005577 /* Check stack size. */
5578 if (!lua_checkstack(L, 3))
5579 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005580
Christopher Fauleta2097962019-07-15 16:25:33 +02005581 /* Create the object: obj[0] = userdata.
5582 * Note that the base of the Converters object is the
5583 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005584 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005585 lua_newtable(L);
5586 htxn = lua_newuserdata(L, sizeof(*htxn));
5587 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005588
5589 htxn->s = txn->s;
5590 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005591 htxn->dir = txn->dir;
5592 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005593
5594 /* Pop a class stream metatable and affect it to the table. */
5595 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5596 lua_setmetatable(L, -2);
5597
5598 return 1;
5599}
5600
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005601/* This function creates and returns an array containing the status-line
5602 * elements. This function does not fails.
5603 */
5604__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5605{
5606 /* Create the table. */
5607 lua_newtable(L);
5608
5609 if (sl->flags & HTX_SL_F_IS_RESP) {
5610 lua_pushstring(L, "version");
5611 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5612 lua_settable(L, -3);
5613 lua_pushstring(L, "code");
5614 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5615 lua_settable(L, -3);
5616 lua_pushstring(L, "reason");
5617 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5618 lua_settable(L, -3);
5619 }
5620 else {
5621 lua_pushstring(L, "method");
5622 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5623 lua_settable(L, -3);
5624 lua_pushstring(L, "uri");
5625 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5626 lua_settable(L, -3);
5627 lua_pushstring(L, "version");
5628 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5629 lua_settable(L, -3);
5630 }
5631 return 1;
5632}
5633
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005634/* This function creates ans returns an array of HTTP headers.
5635 * This function does not fails. It is used as wrapper with the
5636 * 2 following functions.
5637 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005638__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005639{
Christopher Fauleta2097962019-07-15 16:25:33 +02005640 struct htx *htx;
5641 int32_t pos;
5642
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005643 /* Create the table. */
5644 lua_newtable(L);
5645
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005646
Christopher Fauleta2097962019-07-15 16:25:33 +02005647 htx = htxbuf(&msg->chn->buf);
5648 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5649 struct htx_blk *blk = htx_get_blk(htx, pos);
5650 enum htx_blk_type type = htx_get_blk_type(blk);
5651 struct ist n, v;
5652 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005653
Christopher Fauleta2097962019-07-15 16:25:33 +02005654 if (type == HTX_BLK_HDR) {
5655 n = htx_get_blk_name(htx,blk);
5656 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005657 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005658 else if (type == HTX_BLK_EOH)
5659 break;
5660 else
5661 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005662
Christopher Fauleta2097962019-07-15 16:25:33 +02005663 /* Check for existing entry:
5664 * assume that the table is on the top of the stack, and
5665 * push the key in the stack, the function lua_gettable()
5666 * perform the lookup.
5667 */
5668 lua_pushlstring(L, n.ptr, n.len);
5669 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005670
Christopher Fauleta2097962019-07-15 16:25:33 +02005671 switch (lua_type(L, -1)) {
5672 case LUA_TNIL:
5673 /* Table not found, create it. */
5674 lua_pop(L, 1); /* remove the nil value. */
5675 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5676 lua_newtable(L); /* create and push empty table. */
5677 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5678 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5679 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005680 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005681
Christopher Fauleta2097962019-07-15 16:25:33 +02005682 case LUA_TTABLE:
5683 /* Entry found: push the value in the table. */
5684 len = lua_rawlen(L, -1);
5685 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5686 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5687 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5688 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005689
Christopher Fauleta2097962019-07-15 16:25:33 +02005690 default:
5691 /* Other cases are errors. */
5692 hlua_pusherror(L, "internal error during the parsing of headers.");
5693 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005694 }
5695 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005696 return 1;
5697}
5698
5699__LJMP static int hlua_http_req_get_headers(lua_State *L)
5700{
5701 struct hlua_txn *htxn;
5702
5703 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5704 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5705
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005706 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005707 WILL_LJMP(lua_error(L));
5708
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005709 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005710}
5711
5712__LJMP static int hlua_http_res_get_headers(lua_State *L)
5713{
5714 struct hlua_txn *htxn;
5715
5716 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5717 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5718
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005719 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005720 WILL_LJMP(lua_error(L));
5721
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005722 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005723}
5724
5725/* This function replace full header, or just a value in
5726 * the request or in the response. It is a wrapper fir the
5727 * 4 following functions.
5728 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005729__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005730{
5731 size_t name_len;
5732 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5733 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5734 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005735 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005736 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005737
Dragan Dosen26743032019-04-30 15:54:36 +02005738 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005739 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5740
Christopher Fauleta2097962019-07-15 16:25:33 +02005741 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005742 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005743 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005744 return 0;
5745}
5746
5747__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5748{
5749 struct hlua_txn *htxn;
5750
5751 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5752 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5753
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005754 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005755 WILL_LJMP(lua_error(L));
5756
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005757 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005758}
5759
5760__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5761{
5762 struct hlua_txn *htxn;
5763
5764 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5765 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5766
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005767 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005768 WILL_LJMP(lua_error(L));
5769
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005770 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005771}
5772
5773__LJMP static int hlua_http_req_rep_val(lua_State *L)
5774{
5775 struct hlua_txn *htxn;
5776
5777 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5778 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5779
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005780 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005781 WILL_LJMP(lua_error(L));
5782
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005783 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005784}
5785
5786__LJMP static int hlua_http_res_rep_val(lua_State *L)
5787{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005788 struct hlua_txn *htxn;
5789
5790 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5791 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5792
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005793 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005794 WILL_LJMP(lua_error(L));
5795
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005796 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005797}
5798
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005799/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005800 * It is a wrapper for the 2 following functions.
5801 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005802__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005803{
5804 size_t len;
5805 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005806 struct htx *htx = htxbuf(&msg->chn->buf);
5807 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005808
Christopher Fauleta2097962019-07-15 16:25:33 +02005809 ctx.blk = NULL;
5810 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5811 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005812 return 0;
5813}
5814
5815__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5816{
5817 struct hlua_txn *htxn;
5818
5819 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5820 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5821
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005822 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005823 WILL_LJMP(lua_error(L));
5824
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005825 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005826}
5827
5828__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5829{
5830 struct hlua_txn *htxn;
5831
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005832 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005833 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5834
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005835 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005836 WILL_LJMP(lua_error(L));
5837
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005838 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005839}
5840
5841/* This function adds an header. It is a wrapper used by
5842 * the 2 following functions.
5843 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005844__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005845{
5846 size_t name_len;
5847 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5848 size_t value_len;
5849 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005850 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005851
Christopher Fauleta2097962019-07-15 16:25:33 +02005852 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5853 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005854 return 0;
5855}
5856
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005857__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5858{
5859 struct hlua_txn *htxn;
5860
5861 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5862 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5863
5864 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5865 WILL_LJMP(lua_error(L));
5866
5867 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5868}
5869
5870__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5871{
5872 struct hlua_txn *htxn;
5873
5874 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5875 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5876
5877 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5878 WILL_LJMP(lua_error(L));
5879
5880 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5881}
5882
5883static int hlua_http_req_set_hdr(lua_State *L)
5884{
5885 struct hlua_txn *htxn;
5886
5887 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5888 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5889
5890 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5891 WILL_LJMP(lua_error(L));
5892
5893 hlua_http_del_hdr(L, &htxn->s->txn->req);
5894 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5895}
5896
5897static int hlua_http_res_set_hdr(lua_State *L)
5898{
5899 struct hlua_txn *htxn;
5900
5901 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5902 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5903
5904 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5905 WILL_LJMP(lua_error(L));
5906
5907 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5908 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5909}
5910
5911/* This function set the method. */
5912static int hlua_http_req_set_meth(lua_State *L)
5913{
5914 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5915 size_t name_len;
5916 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5917
5918 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5919 WILL_LJMP(lua_error(L));
5920
5921 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5922 return 1;
5923}
5924
5925/* This function set the method. */
5926static int hlua_http_req_set_path(lua_State *L)
5927{
5928 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5929 size_t name_len;
5930 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5931
5932 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5933 WILL_LJMP(lua_error(L));
5934
5935 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5936 return 1;
5937}
5938
5939/* This function set the query-string. */
5940static int hlua_http_req_set_query(lua_State *L)
5941{
5942 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5943 size_t name_len;
5944 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5945
5946 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5947 WILL_LJMP(lua_error(L));
5948
5949 /* Check length. */
5950 if (name_len > trash.size - 1) {
5951 lua_pushboolean(L, 0);
5952 return 1;
5953 }
5954
5955 /* Add the mark question as prefix. */
5956 chunk_reset(&trash);
5957 trash.area[trash.data++] = '?';
5958 memcpy(trash.area + trash.data, name, name_len);
5959 trash.data += name_len;
5960
5961 lua_pushboolean(L,
5962 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5963 return 1;
5964}
5965
5966/* This function set the uri. */
5967static int hlua_http_req_set_uri(lua_State *L)
5968{
5969 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5970 size_t name_len;
5971 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5972
5973 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5974 WILL_LJMP(lua_error(L));
5975
5976 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5977 return 1;
5978}
5979
5980/* This function set the response code & optionally reason. */
5981static int hlua_http_res_set_status(lua_State *L)
5982{
5983 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5984 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5985 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5986 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5987
5988 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5989 WILL_LJMP(lua_error(L));
5990
5991 http_res_set_status(code, reason, htxn->s);
5992 return 0;
5993}
5994
5995/*
5996 *
5997 *
5998 * Class HTTPMessage
5999 *
6000 *
6001 */
6002
6003/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6004 * otherwise it throws an error.
6005 */
6006__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6007{
6008 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6009}
6010
6011/* Creates and pushes on the stack a HTTP object according with a current TXN.
6012 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006013static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006014{
6015 /* Check stack size. */
6016 if (!lua_checkstack(L, 3))
6017 return 0;
6018
6019 lua_newtable(L);
6020 lua_pushlightuserdata(L, msg);
6021 lua_rawseti(L, -2, 0);
6022
6023 /* Create the "channel" field that contains the request channel object. */
6024 lua_pushstring(L, "channel");
6025 if (!hlua_channel_new(L, msg->chn))
6026 return 0;
6027 lua_rawset(L, -3);
6028
6029 /* Pop a class stream metatable and affect it to the table. */
6030 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6031 lua_setmetatable(L, -2);
6032
6033 return 1;
6034}
6035
6036/* Helper function returning a filter attached to the HTTP message at the
6037 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006038 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006039 * filled with output and input length respectively.
6040 */
6041static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6042{
6043 struct channel *chn = msg->chn;
6044 struct htx *htx = htxbuf(&chn->buf);
6045 struct filter *filter = NULL;
6046
6047 *offset = co_data(msg->chn);
6048 *len = htx->data - co_data(msg->chn);
6049
6050 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6051 filter = lua_touserdata (L, -1);
6052 if (msg->msg_state >= HTTP_MSG_DATA) {
6053 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6054
6055 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6056 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6057 }
6058 }
6059
6060 lua_pop(L, 1);
6061 return filter;
6062}
6063
6064/* Returns true if the channel attached to the HTTP message is the response
6065 * channel.
6066 */
6067__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6068{
6069 struct http_msg *msg;
6070
6071 MAY_LJMP(check_args(L, 1, "is_resp"));
6072 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6073
6074 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6075 return 1;
6076}
6077
6078/* Returns an array containing the elements status-line of the HTTP message. It relies
6079 * on hlua_http_get_stline().
6080 */
6081__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6082{
6083 struct http_msg *msg;
6084 struct htx *htx;
6085 struct htx_sl *sl;
6086
6087 MAY_LJMP(check_args(L, 1, "get_stline"));
6088 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6089
6090 if (msg->msg_state > HTTP_MSG_BODY)
6091 WILL_LJMP(lua_error(L));
6092
6093 htx = htxbuf(&msg->chn->buf);
6094 sl = http_get_stline(htx);
6095 if (!sl)
6096 return 0;
6097 return hlua_http_get_stline(L, sl);
6098}
6099
6100/* Returns an array containing all headers of the HTTP message. it relies on
6101 * hlua_http_get_headers().
6102 */
6103__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6104{
6105 struct http_msg *msg;
6106
6107 MAY_LJMP(check_args(L, 1, "get_headers"));
6108 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6109
6110 if (msg->msg_state > HTTP_MSG_BODY)
6111 WILL_LJMP(lua_error(L));
6112
6113 return hlua_http_get_headers(L, msg);
6114}
6115
6116/* Deletes all occurrences of an header in the HTTP message matching on its
6117 * name. It relies on hlua_http_del_hdr().
6118 */
6119__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6120{
6121 struct http_msg *msg;
6122
6123 MAY_LJMP(check_args(L, 2, "del_header"));
6124 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6125
6126 if (msg->msg_state > HTTP_MSG_BODY)
6127 WILL_LJMP(lua_error(L));
6128
6129 return hlua_http_del_hdr(L, msg);
6130}
6131
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006132/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006133 * message given its name against a regex and replaces it if it matches. It
6134 * relies on hlua_http_rep_hdr().
6135 */
6136__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6137{
6138 struct http_msg *msg;
6139
6140 MAY_LJMP(check_args(L, 4, "rep_header"));
6141 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6142
6143 if (msg->msg_state > HTTP_MSG_BODY)
6144 WILL_LJMP(lua_error(L));
6145
6146 return hlua_http_rep_hdr(L, msg, 1);
6147}
6148
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006149/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006150 * message given its name against a regex and replaces it if it matches. It
6151 * relies on hlua_http_rep_hdr().
6152 */
6153__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6154{
6155 struct http_msg *msg;
6156
6157 MAY_LJMP(check_args(L, 4, "rep_value"));
6158 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6159
6160 if (msg->msg_state > HTTP_MSG_BODY)
6161 WILL_LJMP(lua_error(L));
6162
6163 return hlua_http_rep_hdr(L, msg, 0);
6164}
6165
6166/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6167__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6168{
6169 struct http_msg *msg;
6170
6171 MAY_LJMP(check_args(L, 3, "add_header"));
6172 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6173
6174 if (msg->msg_state > HTTP_MSG_BODY)
6175 WILL_LJMP(lua_error(L));
6176
6177 return hlua_http_add_hdr(L, msg);
6178}
6179
6180/* Add an header in the HTTP message removing existing headers with the same
6181 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6182 */
6183__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6184{
6185 struct http_msg *msg;
6186
6187 MAY_LJMP(check_args(L, 3, "set_header"));
6188 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6189
6190 if (msg->msg_state > HTTP_MSG_BODY)
6191 WILL_LJMP(lua_error(L));
6192
6193 hlua_http_del_hdr(L, msg);
6194 return hlua_http_add_hdr(L, msg);
6195}
6196
6197/* Rewrites the request method. It relies on http_req_replace_stline(). */
6198__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6199{
6200 struct stream *s;
6201 struct http_msg *msg;
6202 const char *name;
6203 size_t name_len;
6204
6205 MAY_LJMP(check_args(L, 2, "set_method"));
6206 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6207 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6208
6209 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6210 WILL_LJMP(lua_error(L));
6211
6212 s = chn_strm(msg->chn);
6213 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6214 return 1;
6215}
6216
6217/* Rewrites the request path. It relies on http_req_replace_stline(). */
6218__LJMP static int hlua_http_msg_set_path(lua_State *L)
6219{
6220 struct stream *s;
6221 struct http_msg *msg;
6222 const char *name;
6223 size_t name_len;
6224
6225 MAY_LJMP(check_args(L, 2, "set_path"));
6226 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6227 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6228
6229 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6230 WILL_LJMP(lua_error(L));
6231
6232 s = chn_strm(msg->chn);
6233 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6234 return 1;
6235}
6236
6237/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6238__LJMP static int hlua_http_msg_set_query(lua_State *L)
6239{
6240 struct stream *s;
6241 struct http_msg *msg;
6242 const char *name;
6243 size_t name_len;
6244
6245 MAY_LJMP(check_args(L, 2, "set_query"));
6246 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6247 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6248
6249 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6250 WILL_LJMP(lua_error(L));
6251
6252 /* Check length. */
6253 if (name_len > trash.size - 1) {
6254 lua_pushboolean(L, 0);
6255 return 1;
6256 }
6257
6258 /* Add the mark question as prefix. */
6259 chunk_reset(&trash);
6260 trash.area[trash.data++] = '?';
6261 memcpy(trash.area + trash.data, name, name_len);
6262 trash.data += name_len;
6263
6264 s = chn_strm(msg->chn);
6265 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6266 return 1;
6267}
6268
6269/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6270__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6271{
6272 struct stream *s;
6273 struct http_msg *msg;
6274 const char *name;
6275 size_t name_len;
6276
6277 MAY_LJMP(check_args(L, 2, "set_uri"));
6278 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6279 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6280
6281 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6282 WILL_LJMP(lua_error(L));
6283
6284 s = chn_strm(msg->chn);
6285 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6286 return 1;
6287}
6288
6289/* Rewrites the response status code. It relies on http_res_set_status(). */
6290__LJMP static int hlua_http_msg_set_status(lua_State *L)
6291{
6292 struct http_msg *msg;
6293 unsigned int code;
6294 const char *reason;
6295 size_t reason_len;
6296
6297 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6298 code = MAY_LJMP(luaL_checkinteger(L, 2));
6299 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6300
6301 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6302 WILL_LJMP(lua_error(L));
6303
6304 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6305 return 1;
6306}
6307
6308/* Returns true if the HTTP message is full. */
6309__LJMP static int hlua_http_msg_is_full(lua_State *L)
6310{
6311 struct http_msg *msg;
6312
6313 MAY_LJMP(check_args(L, 1, "is_full"));
6314 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6315 lua_pushboolean(L, channel_full(msg->chn, 0));
6316 return 1;
6317}
6318
6319/* Returns true if the HTTP message may still receive data. */
6320__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6321{
6322 struct http_msg *msg;
6323 struct htx *htx;
6324
6325 MAY_LJMP(check_args(L, 1, "may_recv"));
6326 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6327 htx = htxbuf(&msg->chn->buf);
6328 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6329 return 1;
6330}
6331
6332/* Returns true if the HTTP message EOM was received */
6333__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6334{
6335 struct http_msg *msg;
6336 struct htx *htx;
6337
6338 MAY_LJMP(check_args(L, 1, "may_recv"));
6339 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6340 htx = htxbuf(&msg->chn->buf);
6341 lua_pushboolean(L, !htx_expect_more(htx));
6342 return 1;
6343}
6344
6345/* Returns the number of bytes available in the input side of the HTTP
6346 * message. This function never fails.
6347 */
6348__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6349{
6350 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006351 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006352
6353 MAY_LJMP(check_args(L, 1, "input"));
6354 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006355 hlua_http_msg_filter(L, 1, msg, &output, &input);
6356 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006357 return 1;
6358}
6359
6360/* Returns the number of bytes available in the output side of the HTTP
6361 * message. This function never fails.
6362 */
6363__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6364{
6365 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006366 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006367
6368 MAY_LJMP(check_args(L, 1, "output"));
6369 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006370 hlua_http_msg_filter(L, 1, msg, &output, &input);
6371 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006372 return 1;
6373}
6374
6375/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6376 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006377 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006378 * block. This function is called during the payload filtering, so the headers
6379 * are already scheduled for output (from the filter point of view).
6380 */
6381static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6382{
6383 struct htx *htx = htxbuf(&msg->chn->buf);
6384 struct htx_blk *blk;
6385 struct htx_ret htxret;
6386 luaL_Buffer b;
6387 int ret = 0;
6388
6389 luaL_buffinit(L, &b);
6390 htxret = htx_find_offset(htx, offset);
6391 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6392 enum htx_blk_type type = htx_get_blk_type(blk);
6393 struct ist v;
6394
6395 switch (type) {
6396 case HTX_BLK_UNUSED:
6397 break;
6398
6399 case HTX_BLK_DATA:
6400 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006401 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006402 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006403
6404 luaL_addlstring(&b, v.ptr, v.len);
6405 ret += v.len;
6406 break;
6407
6408 default:
vishnu0af4bd72021-10-24 06:46:24 +05306409 if (!ret)
6410 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006411 goto end;
6412 }
6413 offset = 0;
6414 }
6415
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006416end:
vishnu0af4bd72021-10-24 06:46:24 +05306417 if (!ret && (htx->flags & HTX_FL_EOM))
6418 goto no_data;
6419 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006420 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306421
6422 no_data:
6423 /* Remove the empty string and push nil on the stack */
6424 lua_pop(L, 1);
6425 lua_pushnil(L);
6426 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006427}
6428
6429/* Copies the string <str> to the HTTP message <msg> at the offset
6430 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006431 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006432 * the filter context.
6433 */
6434static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6435{
6436 struct htx *htx = htx_from_buf(&msg->chn->buf);
6437 struct htx_ret htxret;
6438 int /*max, */ret = 0;
6439
6440 /* Nothing to do, just return */
6441 if (unlikely(istlen(str) == 0))
6442 goto end;
6443
6444 if (istlen(str) > htx_free_data_space(htx)) {
6445 ret = -1;
6446 goto end;
6447 }
6448
6449 htxret = htx_find_offset(htx, offset);
6450 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6451 if (!htx_add_last_data(htx, str))
6452 goto end;
6453 }
6454 else {
6455 struct ist v = htx_get_blk_value(htx, htxret.blk);
6456 v.ptr += htxret.ret;
6457 v.len = 0;
6458 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6459 goto end;
6460 }
6461 ret = str.len;
6462 if (ret) {
6463 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6464 flt_update_offsets(filter, msg->chn, ret);
6465 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6466 }
6467
6468 end:
6469 htx_to_buf(htx, &msg->chn->buf);
6470 return ret;
6471}
6472
6473/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6474 * position <offset>. It stops on the first non-DATA HTX block. This function is
6475 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006476 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006477 * update the filter context.
6478 */
6479static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6480{
6481 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6482 struct htx *htx = htx_from_buf(&msg->chn->buf);
6483 struct htx_blk *blk;
6484 struct htx_ret htxret;
6485 size_t ret = 0;
6486
6487 /* Be sure <len> is always the amount of DATA to remove */
6488 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006489 /* When htx tail type == HTX_BLK_DATA, no need to take care
6490 * of special blocks like HTX_BLK_EOT.
6491 * We simply truncate after offset
6492 * (truncate targeted blk and discard the following ones)
6493 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006494 htx_truncate(htx, offset);
6495 ret = len;
6496 goto end;
6497 }
6498
6499 htxret = htx_find_offset(htx, offset);
6500 blk = htxret.blk;
6501 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006502 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006503 struct ist v;
6504
6505 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6506 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006507
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006508 v = htx_get_blk_value(htx, blk);
6509 v.ptr += htxret.ret;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006510 v.len -= htxret.ret;
6511
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006512 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006513 /* trimming data in blk: discard everything after the offset
6514 * (replace 'v' with 'IST_NULL')
6515 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006516 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006517 if (blk && v.len < len) {
6518 /* In this case, caller wants to keep removing data,
6519 * but we need to spare current blk
6520 * because it was already trimmed
6521 */
6522 blk = htx_get_next_blk(htx, blk);
6523 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006524 len -= v.len;
6525 ret += v.len;
6526 }
6527
6528
6529 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006530 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006531 enum htx_blk_type type = htx_get_blk_type(blk);
6532 uint32_t sz = htx_get_blksz(blk);
6533
6534 switch (type) {
6535 case HTX_BLK_UNUSED:
6536 break;
6537
6538 case HTX_BLK_DATA:
6539 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006540 /* don't discard whole blk, only part of it
6541 * (from the beginning)
6542 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006543 htx_cut_data_blk(htx, blk, len);
6544 ret += len;
6545 goto end;
6546 }
6547 break;
6548
6549 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006550 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006551 goto end;
6552 }
6553
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006554 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006555 len -= sz;
6556 ret += sz;
6557 blk = htx_remove_blk(htx, blk);
6558 }
6559
6560end:
6561 flt_update_offsets(filter, msg->chn, -ret);
6562 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6563 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6564 * to loose the EOM flag if the message is empty.
6565 */
6566}
6567
6568/* Copies input data found in an HTTP message. Unlike the channel function used
6569 * to duplicate raw data, this one can only be called inside a filter, from
6570 * http_payload callback. So it cannot yield. An exception is returned if it is
6571 * called from another callback. If nothing was copied, a nil value is pushed on
6572 * the stack.
6573 */
6574__LJMP static int hlua_http_msg_get_body(lua_State *L)
6575{
6576 struct http_msg *msg;
6577 struct filter *filter;
6578 size_t output, input;
6579 int offset, len;
6580
6581 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6582 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6583 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6584
6585 if (msg->msg_state < HTTP_MSG_DATA)
6586 WILL_LJMP(lua_error(L));
6587
6588 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6589 if (!filter || !hlua_filter_from_payload(filter))
6590 WILL_LJMP(lua_error(L));
6591
6592 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6593 lua_pushnil(L);
6594 return 1;
6595 }
6596
6597 offset = output;
6598 if (lua_gettop(L) > 1) {
6599 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6600 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006601 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006602 offset += output;
6603 if (offset < output || offset > input + output) {
6604 lua_pushfstring(L, "offset out of range.");
6605 WILL_LJMP(lua_error(L));
6606 }
6607 }
6608 len = output + input - offset;
6609 if (lua_gettop(L) == 3) {
6610 len = MAY_LJMP(luaL_checkinteger(L, 3));
6611 if (!len)
6612 goto dup;
6613 if (len == -1)
6614 len = global.tune.bufsize;
6615 if (len < 0) {
6616 lua_pushfstring(L, "length out of range.");
6617 WILL_LJMP(lua_error(L));
6618 }
6619 }
6620
6621 dup:
6622 _hlua_http_msg_dup(msg, L, offset, len);
6623 return 1;
6624}
6625
6626/* Appends a string to the HTTP message, after all existing DATA blocks but
6627 * before the trailers, if any. It returns the amount of data written or -1 if
6628 * nothing was copied. Unlike the channel function used to append data, this one
6629 * can only be called inside a filter, from http_payload callback. So it cannot
6630 * yield. An exception is returned if it is called from another callback.
6631 */
6632__LJMP static int hlua_http_msg_append(lua_State *L)
6633{
6634 struct http_msg *msg;
6635 struct filter *filter;
6636 const char *str;
6637 size_t offset, len, sz;
6638 int ret;
6639
6640 MAY_LJMP(check_args(L, 2, "append"));
6641 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6642
6643 if (msg->msg_state < HTTP_MSG_DATA)
6644 WILL_LJMP(lua_error(L));
6645
6646 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6647 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6648 if (!filter || !hlua_filter_from_payload(filter))
6649 WILL_LJMP(lua_error(L));
6650
6651 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6652 lua_pushinteger(L, ret);
6653 return 1;
6654}
6655
6656/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6657 * returns the amount of data written or -1 if nothing was copied. Unlike the
6658 * channel function used to prepend data, this one can only be called inside a
6659 * filter, from http_payload callback. So it cannot yield. An exception is
6660 * returned if it is called from another callback.
6661 */
6662__LJMP static int hlua_http_msg_prepend(lua_State *L)
6663{
6664 struct http_msg *msg;
6665 struct filter *filter;
6666 const char *str;
6667 size_t offset, len, sz;
6668 int ret;
6669
6670 MAY_LJMP(check_args(L, 2, "prepend"));
6671 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006672
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006673 if (msg->msg_state < HTTP_MSG_DATA)
6674 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006675
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006676 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6677 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6678 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006679 WILL_LJMP(lua_error(L));
6680
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006681 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6682 lua_pushinteger(L, ret);
6683 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006684}
6685
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006686/* Inserts a string to the HTTP message at a given offset. By default the string
6687 * is appended at the end of DATA blocks. It returns the amount of data written
6688 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6689 * this one can only be called inside a filter, from http_payload callback. So
6690 * it cannot yield. An exception is returned if it is called from another
6691 * callback.
6692 */
6693__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006694{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006695 struct http_msg *msg;
6696 struct filter *filter;
6697 const char *str;
6698 size_t input, output, sz;
6699 int offset;
6700 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006701
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006702 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6703 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006704 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006705
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006707 WILL_LJMP(lua_error(L));
6708
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006709 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006710 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006711 if (!filter || !hlua_filter_from_payload(filter))
6712 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006713
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006714 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 if (lua_gettop(L) > 2) {
6716 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6717 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006718 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006719 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006720 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006721 lua_pushfstring(L, "offset out of range.");
6722 WILL_LJMP(lua_error(L));
6723 }
6724 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006725
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006726 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6727 lua_pushinteger(L, ret);
6728 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006729}
6730
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006731/* Removes a given amount of data from the HTTP message at a given offset. By
6732 * default all DATA blocks are removed. It returns the amount of data
6733 * removed. Unlike the channel function used to remove data, this one can only
6734 * be called inside a filter, from http_payload callback. So it cannot yield. An
6735 * exception is returned if it is called from another callback.
6736 */
6737__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006738{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006739 struct http_msg *msg;
6740 struct filter *filter;
6741 size_t input, output;
6742 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006743
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006744 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006745 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006747
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006748 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006749 WILL_LJMP(lua_error(L));
6750
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006751 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006752 if (!filter || !hlua_filter_from_payload(filter))
6753 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006754
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006755 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006756 if (lua_gettop(L) > 1) {
6757 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006758 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006759 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006760 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006761 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006762 lua_pushfstring(L, "offset out of range.");
6763 WILL_LJMP(lua_error(L));
6764 }
6765 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006766
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006767 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006768 if (lua_gettop(L) == 3) {
6769 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770 if (!len)
6771 goto end;
6772 if (len == -1)
6773 len = output + input - offset;
6774 if (len < 0 || offset + len > output + input) {
6775 lua_pushfstring(L, "length out of range.");
6776 WILL_LJMP(lua_error(L));
6777 }
6778 }
6779
6780 _hlua_http_msg_delete(msg, filter, offset, len);
6781
6782 end:
6783 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006784 return 1;
6785}
6786
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006787/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006788 * all remaining data are removed, accordingly to the filter context. It returns
6789 * the amount of data written or -1 if nothing was copied. Unlike the channel
6790 * function used to replace data, this one can only be called inside a filter,
6791 * from http_payload callback. So it cannot yield. An exception is returned if
6792 * it is called from another callback.
6793 */
6794__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006795{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006796 struct http_msg *msg;
6797 struct filter *filter;
6798 struct htx *htx;
6799 const char *str;
6800 size_t input, output, sz;
6801 int offset, len;
6802 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006803
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006804 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6805 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6806 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6807
6808 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006809 WILL_LJMP(lua_error(L));
6810
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006811 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6812 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6813 if (!filter || !hlua_filter_from_payload(filter))
6814 WILL_LJMP(lua_error(L));
6815
6816 offset = output;
6817 if (lua_gettop(L) > 2) {
6818 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6819 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006820 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006821 offset += output;
6822 if (offset < output || offset > input + output) {
6823 lua_pushfstring(L, "offset out of range.");
6824 WILL_LJMP(lua_error(L));
6825 }
6826 }
6827
6828 len = output + input - offset;
6829 if (lua_gettop(L) == 4) {
6830 len = MAY_LJMP(luaL_checkinteger(L, 4));
6831 if (!len)
6832 goto set;
6833 if (len == -1)
6834 len = output + input - offset;
6835 if (len < 0 || offset + len > output + input) {
6836 lua_pushfstring(L, "length out of range.");
6837 WILL_LJMP(lua_error(L));
6838 }
6839 }
6840
6841 set:
6842 /* Be sure we can copied the string once input data will be removed. */
6843 htx = htx_from_buf(&msg->chn->buf);
6844 if (sz > htx_free_data_space(htx) + len)
6845 lua_pushinteger(L, -1);
6846 else {
6847 _hlua_http_msg_delete(msg, filter, offset, len);
6848 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6849 lua_pushinteger(L, ret);
6850 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006851 return 1;
6852}
6853
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006854/* Prepends data into an HTTP message and forward it, from the filter point of
6855 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6856 * the channel function used to send data, this one can only be called inside a
6857 * filter, from http_payload callback. So it cannot yield. An exception is
6858 * returned if it is called from another callback.
6859 */
6860__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006861{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006862 struct http_msg *msg;
6863 struct filter *filter;
6864 struct htx *htx;
6865 const char *str;
6866 size_t offset, len, sz;
6867 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006868
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006869 MAY_LJMP(check_args(L, 2, "send"));
6870 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6871
6872 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006873 WILL_LJMP(lua_error(L));
6874
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006875 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6876 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6877 if (!filter || !hlua_filter_from_payload(filter))
6878 WILL_LJMP(lua_error(L));
6879
6880 /* Return an error if the channel's output is closed */
6881 if (unlikely(channel_output_closed(msg->chn))) {
6882 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006883 return 1;
6884 }
6885
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006886 htx = htx_from_buf(&msg->chn->buf);
6887 if (sz > htx_free_data_space(htx)) {
6888 lua_pushinteger(L, -1);
6889 return 1;
6890 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006891
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006892 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6893 if (ret > 0) {
6894 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6895
6896 FLT_OFF(filter, msg->chn) += ret;
6897 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6898 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6899 }
6900
6901 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006902 return 1;
6903}
6904
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006905/* Forwards a given amount of bytes. It return -1 if the channel's output is
6906 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6907 * channel function used to forward data, this one can only be called inside a
6908 * filter, from http_payload callback. So it cannot yield. An exception is
6909 * returned if it is called from another callback. All other functions deal with
6910 * DATA block, this one not.
6911*/
6912__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006913{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006914 struct http_msg *msg;
6915 struct filter *filter;
6916 size_t offset, len;
6917 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006918
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006919 MAY_LJMP(check_args(L, 2, "forward"));
6920 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6921
6922 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006923 WILL_LJMP(lua_error(L));
6924
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006925 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6926 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6927 if (!filter || !hlua_filter_from_payload(filter))
6928 WILL_LJMP(lua_error(L));
6929
6930 /* Nothing to do, just return */
6931 if (!fwd)
6932 goto end;
6933
6934 /* Return an error if the channel's output is closed */
6935 if (unlikely(channel_output_closed(msg->chn))) {
6936 ret = -1;
6937 goto end;
6938 }
6939
6940 ret = fwd;
6941 if (ret > len)
6942 ret = len;
6943
6944 if (ret) {
6945 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6946
6947 FLT_OFF(filter, msg->chn) += ret;
6948 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6949 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6950 }
6951
6952 end:
6953 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006954 return 1;
6955}
6956
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006957/* Set EOM flag on the HTX message.
6958 *
6959 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6960 * really know how to do without this feature.
6961 */
6962__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006963{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006964 struct http_msg *msg;
6965 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006966
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006967 MAY_LJMP(check_args(L, 1, "set_eom"));
6968 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6969 htx = htxbuf(&msg->chn->buf);
6970 htx->flags |= HTX_FL_EOM;
6971 return 0;
6972}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006973
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006974/* Unset EOM flag on the HTX message.
6975 *
6976 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6977 * really know how to do without this feature.
6978 */
6979__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6980{
6981 struct http_msg *msg;
6982 struct htx *htx;
6983
6984 MAY_LJMP(check_args(L, 1, "set_eom"));
6985 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6986 htx = htxbuf(&msg->chn->buf);
6987 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006988 return 0;
6989}
6990
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006991/*
6992 *
6993 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006994 * Class HTTPClient
6995 *
6996 *
6997 */
6998__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6999{
7000 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7001}
7002
William Lallemandf77f1de2021-09-28 19:10:38 +02007003
7004/* stops the httpclient and ask it to kill itself */
7005__LJMP static int hlua_httpclient_gc(lua_State *L)
7006{
7007 struct hlua_httpclient *hlua_hc;
7008
7009 MAY_LJMP(check_args(L, 1, "__gc"));
7010
7011 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7012
7013 httpclient_stop_and_destroy(hlua_hc->hc);
7014
7015 hlua_hc->hc = NULL;
7016
7017
7018 return 0;
7019}
7020
7021
William Lallemand3956c4e2021-09-21 16:25:15 +02007022__LJMP static int hlua_httpclient_new(lua_State *L)
7023{
7024 struct hlua_httpclient *hlua_hc;
7025 struct hlua *hlua;
7026
7027 /* Get hlua struct, or NULL if we execute from main lua state */
7028 hlua = hlua_gethlua(L);
7029 if (!hlua)
7030 return 0;
7031
7032 /* Check stack size. */
7033 if (!lua_checkstack(L, 3)) {
7034 hlua_pusherror(L, "httpclient: full stack");
7035 goto err;
7036 }
7037 /* Create the object: obj[0] = userdata. */
7038 lua_newtable(L);
7039 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7040 lua_rawseti(L, -2, 0);
7041 memset(hlua_hc, 0, sizeof(*hlua_hc));
7042
7043 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7044 if (!hlua_hc->hc)
7045 goto err;
7046
7047 /* Pop a class stream metatable and affect it to the userdata. */
7048 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7049 lua_setmetatable(L, -2);
7050
7051 return 1;
7052
7053 err:
7054 WILL_LJMP(lua_error(L));
7055 return 0;
7056}
7057
7058
7059/*
7060 * Callback of the httpclient, this callback wakes the lua task up, once the
7061 * httpclient receives some data
7062 *
7063 */
7064
William Lallemandbd5739e2021-10-28 15:41:38 +02007065static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007066{
7067 struct hlua *hlua = hc->caller;
7068
7069 if (!hlua || !hlua->task)
7070 return;
7071
7072 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7073}
7074
7075/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007076 * Fill the lua stack with headers from the httpclient response
7077 * This works the same way as the hlua_http_get_headers() function
7078 */
7079__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7080{
7081 struct http_hdr *hdr;
7082
7083 lua_newtable(L);
7084
William Lallemandef574b22021-10-05 16:19:31 +02007085 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007086 struct ist n, v;
7087 int len;
7088
7089 n = hdr->n;
7090 v = hdr->v;
7091
7092 /* Check for existing entry:
7093 * assume that the table is on the top of the stack, and
7094 * push the key in the stack, the function lua_gettable()
7095 * perform the lookup.
7096 */
7097
7098 lua_pushlstring(L, n.ptr, n.len);
7099 lua_gettable(L, -2);
7100
7101 switch (lua_type(L, -1)) {
7102 case LUA_TNIL:
7103 /* Table not found, create it. */
7104 lua_pop(L, 1); /* remove the nil value. */
7105 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7106 lua_newtable(L); /* create and push empty table. */
7107 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7108 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7109 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7110 break;
7111
7112 case LUA_TTABLE:
7113 /* Entry found: push the value in the table. */
7114 len = lua_rawlen(L, -1);
7115 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7116 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7117 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7118 break;
7119
7120 default:
7121 /* Other cases are errors. */
7122 hlua_pusherror(L, "internal error during the parsing of headers.");
7123 WILL_LJMP(lua_error(L));
7124 }
7125 }
7126 return 1;
7127}
7128
7129/*
William Lallemand746e6f32021-10-06 10:57:44 +02007130 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7131 *
7132 * Caller must free the result
7133 */
7134struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7135{
7136 struct http_hdr hdrs[global.tune.max_http_hdr];
7137 struct http_hdr *result = NULL;
7138 uint32_t hdr_num = 0;
7139
7140 lua_pushnil(L);
7141 while (lua_next(L, -2) != 0) {
7142 struct ist name, value;
7143 const char *n, *v;
7144 size_t nlen, vlen;
7145
7146 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7147 /* Skip element if the key is not a string or if the value is not a table */
7148 goto next_hdr;
7149 }
7150
7151 n = lua_tolstring(L, -2, &nlen);
7152 name = ist2(n, nlen);
7153
7154 /* Loop on header's values */
7155 lua_pushnil(L);
7156 while (lua_next(L, -2)) {
7157 if (!lua_isstring(L, -1)) {
7158 /* Skip the value if it is not a string */
7159 goto next_value;
7160 }
7161
7162 v = lua_tolstring(L, -1, &vlen);
7163 value = ist2(v, vlen);
7164 name = ist2(n, nlen);
7165
7166 hdrs[hdr_num].n = istdup(name);
7167 hdrs[hdr_num].v = istdup(value);
7168
7169 hdr_num++;
7170
7171 next_value:
7172 lua_pop(L, 1);
7173 }
7174
7175 next_hdr:
7176 lua_pop(L, 1);
7177
7178 }
7179
7180 if (hdr_num) {
7181 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007182 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007183 if (!result)
7184 goto skip_headers;
7185 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7186
7187 result[hdr_num].n = IST_NULL;
7188 result[hdr_num].v = IST_NULL;
7189 }
7190
7191skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007192
7193 return result;
7194}
7195
7196
William Lallemandbd5739e2021-10-28 15:41:38 +02007197/*
7198 * For each yield, checks if there is some data in the httpclient and push them
7199 * in the lua buffer, once the httpclient finished its job, push the result on
7200 * the stack
7201 */
7202__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7203{
7204 struct buffer *tr;
7205 int res;
7206 struct hlua *hlua = hlua_gethlua(L);
7207 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7208
7209
7210 tr = get_trash_chunk();
7211
7212 res = httpclient_res_xfer(hlua_hc->hc, tr);
7213 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7214
7215 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7216
7217 luaL_pushresult(&hlua_hc->b);
7218 lua_settable(L, -3);
7219
7220 lua_pushstring(L, "status");
7221 lua_pushinteger(L, hlua_hc->hc->res.status);
7222 lua_settable(L, -3);
7223
7224
7225 lua_pushstring(L, "reason");
7226 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7227 lua_settable(L, -3);
7228
7229 lua_pushstring(L, "headers");
7230 hlua_httpclient_get_headers(L, hlua_hc);
7231 lua_settable(L, -3);
7232
7233 return 1;
7234 }
7235
7236 if (httpclient_data(hlua_hc->hc))
7237 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7238
7239 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7240
7241 return 0;
7242}
7243
7244/*
7245 * Call this when trying to stream a body during a request
7246 */
7247__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7248{
7249 struct hlua *hlua;
7250 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7251 const char *body_str = NULL;
7252 int ret;
7253 int end = 0;
7254 size_t buf_len;
7255 size_t to_send = 0;
7256
7257 hlua = hlua_gethlua(L);
7258
7259 if (!hlua || !hlua->task)
7260 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7261 "'frontend', 'backend' or 'task'"));
7262
7263 ret = lua_getfield(L, -1, "body");
7264 if (ret != LUA_TSTRING)
7265 goto rcv;
7266
7267 body_str = lua_tolstring(L, -1, &buf_len);
7268 lua_pop(L, 1);
7269
Christopher Fauletfc591292022-01-12 14:46:03 +01007270 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007271
7272 if ((hlua_hc->sent + to_send) >= buf_len)
7273 end = 1;
7274
7275 /* the end flag is always set since we are using the whole remaining size */
7276 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7277
7278 if (buf_len > hlua_hc->sent) {
7279 /* still need to process the buffer */
7280 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7281 } else {
7282 goto rcv;
7283 /* we sent the whole request buffer we can recv */
7284 }
7285 return 0;
7286
7287rcv:
7288
7289 /* we return a "res" object */
7290 lua_newtable(L);
7291
William Lallemandbd5739e2021-10-28 15:41:38 +02007292 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007293 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007294
William Lallemand933fe392021-11-04 09:45:58 +01007295 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007296 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7297
7298 return 1;
7299}
William Lallemand746e6f32021-10-06 10:57:44 +02007300
William Lallemand3956c4e2021-09-21 16:25:15 +02007301/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007302 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007303 */
7304
William Lallemanddc2cc902021-10-26 11:43:26 +02007305__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007306{
7307 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007308 struct http_hdr *hdrs = NULL;
7309 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007310 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007311 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007312 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007313 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007314 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007315
7316 hlua = hlua_gethlua(L);
7317
7318 if (!hlua || !hlua->task)
7319 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7320 "'frontend', 'backend' or 'task'"));
7321
William Lallemand746e6f32021-10-06 10:57:44 +02007322 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7323 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7324
William Lallemand4f4f2b72022-02-17 20:00:23 +01007325 hlua_hc = hlua_checkhttpclient(L, 1);
7326
William Lallemand7177a952022-03-03 15:33:12 +01007327 lua_pushnil(L); /* first key */
7328 while (lua_next(L, 2)) {
7329 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7330 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7331 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007332
William Lallemand7177a952022-03-03 15:33:12 +01007333 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7334 if (lua_type(L, -1) != LUA_TSTRING)
7335 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7336 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007337
William Lallemand7177a952022-03-03 15:33:12 +01007338 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7339 if (lua_type(L, -1) != LUA_TNUMBER)
7340 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7341 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007342
William Lallemand7177a952022-03-03 15:33:12 +01007343 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7344 if (lua_type(L, -1) != LUA_TTABLE)
7345 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7346 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007347
William Lallemand7177a952022-03-03 15:33:12 +01007348 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7349 if (lua_type(L, -1) != LUA_TSTRING)
7350 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7351 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007352
William Lallemand7177a952022-03-03 15:33:12 +01007353 } else {
7354 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7355 }
7356 /* removes 'value'; keeps 'key' for next iteration */
7357 lua_pop(L, 1);
7358 }
William Lallemanddec25c32021-10-25 19:48:37 +02007359
William Lallemand746e6f32021-10-06 10:57:44 +02007360 if (!url_str) {
7361 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7362 return 0;
7363 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007364
William Lallemand10a37362022-03-02 16:18:26 +01007365 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007366
7367 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007368 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007369
7370 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007371 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7372 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7373 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007374 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007375
William Lallemandbd5739e2021-10-28 15:41:38 +02007376 /* a body is available, it will use the request callback */
7377 if (body_str) {
7378 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7379 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007380
William Lallemandbd5739e2021-10-28 15:41:38 +02007381 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007382
William Lallemand746e6f32021-10-06 10:57:44 +02007383 /* free the temporary headers array */
7384 hdrs_i = hdrs;
7385 while (hdrs_i && isttest(hdrs_i->n)) {
7386 istfree(&hdrs_i->n);
7387 istfree(&hdrs_i->v);
7388 hdrs_i++;
7389 }
7390 ha_free(&hdrs);
7391
7392
William Lallemand6137a9e2021-10-26 15:01:53 +02007393 if (ret != ERR_NONE) {
7394 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7395 return 0;
7396 }
7397
William Lallemandc2d3db42022-04-26 11:46:13 +02007398 if (!httpclient_start(hlua_hc->hc))
7399 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007400
William Lallemandbd5739e2021-10-28 15:41:38 +02007401 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007402
William Lallemand3956c4e2021-09-21 16:25:15 +02007403 return 0;
7404}
7405
7406/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007407 * Sends an HTTP HEAD request and wait for a response
7408 *
7409 * httpclient:head(url, headers, payload)
7410 */
7411__LJMP static int hlua_httpclient_head(lua_State *L)
7412{
7413 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7414}
7415
7416/*
7417 * Send an HTTP GET request and wait for a response
7418 *
7419 * httpclient:get(url, headers, payload)
7420 */
7421__LJMP static int hlua_httpclient_get(lua_State *L)
7422{
7423 return hlua_httpclient_send(L, HTTP_METH_GET);
7424
7425}
7426
7427/*
7428 * Sends an HTTP PUT request and wait for a response
7429 *
7430 * httpclient:put(url, headers, payload)
7431 */
7432__LJMP static int hlua_httpclient_put(lua_State *L)
7433{
7434 return hlua_httpclient_send(L, HTTP_METH_PUT);
7435}
7436
7437/*
7438 * Send an HTTP POST request and wait for a response
7439 *
7440 * httpclient:post(url, headers, payload)
7441 */
7442__LJMP static int hlua_httpclient_post(lua_State *L)
7443{
7444 return hlua_httpclient_send(L, HTTP_METH_POST);
7445}
7446
7447
7448/*
7449 * Sends an HTTP DELETE request and wait for a response
7450 *
7451 * httpclient:delete(url, headers, payload)
7452 */
7453__LJMP static int hlua_httpclient_delete(lua_State *L)
7454{
7455 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7456}
7457
7458/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007459 *
7460 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007461 * Class TXN
7462 *
7463 *
7464 */
7465
7466/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007467 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007468 */
7469__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7470{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007471 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007472}
7473
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007474__LJMP static int hlua_set_var(lua_State *L)
7475{
7476 struct hlua_txn *htxn;
7477 const char *name;
7478 size_t len;
7479 struct sample smp;
7480
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007481 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7482 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007483
7484 /* It is useles to retrieve the stream, but this function
7485 * runs only in a stream context.
7486 */
7487 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7488 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7489
7490 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007491 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007492 hlua_lua2smp(L, 3, &smp);
7493
7494 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007495 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007496
7497 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7498 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7499 else
7500 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7501
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007502 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007503}
7504
Christopher Faulet85d79c92016-11-09 16:54:56 +01007505__LJMP static int hlua_unset_var(lua_State *L)
7506{
7507 struct hlua_txn *htxn;
7508 const char *name;
7509 size_t len;
7510 struct sample smp;
7511
7512 MAY_LJMP(check_args(L, 2, "unset_var"));
7513
7514 /* It is useles to retrieve the stream, but this function
7515 * runs only in a stream context.
7516 */
7517 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7518 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7519
7520 /* Unset the variable. */
7521 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007522 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7523 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007524}
7525
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007526__LJMP static int hlua_get_var(lua_State *L)
7527{
7528 struct hlua_txn *htxn;
7529 const char *name;
7530 size_t len;
7531 struct sample smp;
7532
7533 MAY_LJMP(check_args(L, 2, "get_var"));
7534
7535 /* It is useles to retrieve the stream, but this function
7536 * runs only in a stream context.
7537 */
7538 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7539 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7540
Willy Tarreau7560dd42016-03-10 16:28:58 +01007541 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007542 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007543 lua_pushnil(L);
7544 return 1;
7545 }
7546
7547 return hlua_smp2lua(L, &smp);
7548}
7549
Willy Tarreau59551662015-03-10 14:23:13 +01007550__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007551{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007552 struct hlua *hlua;
7553
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007554 MAY_LJMP(check_args(L, 2, "set_priv"));
7555
Willy Tarreau87b09662015-04-03 00:22:06 +02007556 /* It is useles to retrieve the stream, but this function
7557 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007558 */
7559 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007560
7561 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007562 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007563 if (!hlua)
7564 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007565
7566 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007567 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007568
7569 /* Get and store new value. */
7570 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7571 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7572
7573 return 0;
7574}
7575
Willy Tarreau59551662015-03-10 14:23:13 +01007576__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007577{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007578 struct hlua *hlua;
7579
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007580 MAY_LJMP(check_args(L, 1, "get_priv"));
7581
Willy Tarreau87b09662015-04-03 00:22:06 +02007582 /* It is useles to retrieve the stream, but this function
7583 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007584 */
7585 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007586
7587 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007588 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007589 if (!hlua) {
7590 lua_pushnil(L);
7591 return 1;
7592 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007593
7594 /* Push configuration index in the stack. */
7595 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7596
7597 return 1;
7598}
7599
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007600/* Create stack entry containing a class TXN. This function
7601 * return 0 if the stack does not contains free slots,
7602 * otherwise it returns 1.
7603 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007604static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007605{
Willy Tarreaude491382015-04-06 11:04:28 +02007606 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007607
7608 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007609 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007610 return 0;
7611
7612 /* NOTE: The allocation never fails. The failure
7613 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007614 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007615 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007616 /* Create the object: obj[0] = userdata. */
7617 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007618 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007619 lua_rawseti(L, -2, 0);
7620
Willy Tarreaude491382015-04-06 11:04:28 +02007621 htxn->s = s;
7622 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007623 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007624 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007625
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007626 /* Create the "f" field that contains a list of fetches. */
7627 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007628 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007629 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007630 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007631
7632 /* Create the "sf" field that contains a list of stringsafe fetches. */
7633 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007634 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007635 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007636 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007637
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007638 /* Create the "c" field that contains a list of converters. */
7639 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007640 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007641 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007642 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007643
7644 /* Create the "sc" field that contains a list of stringsafe converters. */
7645 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007646 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007647 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007648 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007649
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007650 /* Create the "req" field that contains the request channel object. */
7651 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007652 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007653 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007654 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007655
7656 /* Create the "res" field that contains the response channel object. */
7657 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007658 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007659 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007660 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007661
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007662 /* Creates the HTTP object is the current proxy allows http. */
7663 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007664 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007665 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007666 return 0;
7667 }
7668 else
7669 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007670 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007671
Christopher Faulet78c35472020-02-26 17:14:08 +01007672 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7673 /* HTTPMessage object are created when a lua TXN is created from
7674 * a filter context only
7675 */
7676
7677 /* Creates the HTTP-Request object is the current proxy allows http. */
7678 lua_pushstring(L, "http_req");
7679 if (p->mode == PR_MODE_HTTP) {
7680 if (!hlua_http_msg_new(L, &s->txn->req))
7681 return 0;
7682 }
7683 else
7684 lua_pushnil(L);
7685 lua_rawset(L, -3);
7686
7687 /* Creates the HTTP-Response object is the current proxy allows http. */
7688 lua_pushstring(L, "http_res");
7689 if (p->mode == PR_MODE_HTTP) {
7690 if (!hlua_http_msg_new(L, &s->txn->rsp))
7691 return 0;
7692 }
7693 else
7694 lua_pushnil(L);
7695 lua_rawset(L, -3);
7696 }
7697
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007698 /* Pop a class sesison metatable and affect it to the userdata. */
7699 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7700 lua_setmetatable(L, -2);
7701
7702 return 1;
7703}
7704
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007705__LJMP static int hlua_txn_deflog(lua_State *L)
7706{
7707 const char *msg;
7708 struct hlua_txn *htxn;
7709
7710 MAY_LJMP(check_args(L, 2, "deflog"));
7711 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7712 msg = MAY_LJMP(luaL_checkstring(L, 2));
7713
7714 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7715 return 0;
7716}
7717
7718__LJMP static int hlua_txn_log(lua_State *L)
7719{
7720 int level;
7721 const char *msg;
7722 struct hlua_txn *htxn;
7723
7724 MAY_LJMP(check_args(L, 3, "log"));
7725 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7726 level = MAY_LJMP(luaL_checkinteger(L, 2));
7727 msg = MAY_LJMP(luaL_checkstring(L, 3));
7728
7729 if (level < 0 || level >= NB_LOG_LEVELS)
7730 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7731
7732 hlua_sendlog(htxn->s->be, level, msg);
7733 return 0;
7734}
7735
7736__LJMP static int hlua_txn_log_debug(lua_State *L)
7737{
7738 const char *msg;
7739 struct hlua_txn *htxn;
7740
7741 MAY_LJMP(check_args(L, 2, "Debug"));
7742 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7743 msg = MAY_LJMP(luaL_checkstring(L, 2));
7744 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7745 return 0;
7746}
7747
7748__LJMP static int hlua_txn_log_info(lua_State *L)
7749{
7750 const char *msg;
7751 struct hlua_txn *htxn;
7752
7753 MAY_LJMP(check_args(L, 2, "Info"));
7754 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7755 msg = MAY_LJMP(luaL_checkstring(L, 2));
7756 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7757 return 0;
7758}
7759
7760__LJMP static int hlua_txn_log_warning(lua_State *L)
7761{
7762 const char *msg;
7763 struct hlua_txn *htxn;
7764
7765 MAY_LJMP(check_args(L, 2, "Warning"));
7766 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7767 msg = MAY_LJMP(luaL_checkstring(L, 2));
7768 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7769 return 0;
7770}
7771
7772__LJMP static int hlua_txn_log_alert(lua_State *L)
7773{
7774 const char *msg;
7775 struct hlua_txn *htxn;
7776
7777 MAY_LJMP(check_args(L, 2, "Alert"));
7778 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7779 msg = MAY_LJMP(luaL_checkstring(L, 2));
7780 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7781 return 0;
7782}
7783
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007784__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7785{
7786 struct hlua_txn *htxn;
7787 int ll;
7788
7789 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7790 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7791 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7792
7793 if (ll < 0 || ll > 7)
7794 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7795
7796 htxn->s->logs.level = ll;
7797 return 0;
7798}
7799
7800__LJMP static int hlua_txn_set_tos(lua_State *L)
7801{
7802 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007803 int tos;
7804
7805 MAY_LJMP(check_args(L, 2, "set_tos"));
7806 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7807 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7808
Willy Tarreau1a18b542018-12-11 16:37:42 +01007809 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007810 return 0;
7811}
7812
7813__LJMP static int hlua_txn_set_mark(lua_State *L)
7814{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007815 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007816 int mark;
7817
7818 MAY_LJMP(check_args(L, 2, "set_mark"));
7819 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7820 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7821
Lukas Tribus579e3e32019-08-11 18:03:45 +02007822 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007823 return 0;
7824}
7825
Patrick Hemmer268a7072018-05-11 12:52:31 -04007826__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7827{
7828 struct hlua_txn *htxn;
7829
7830 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7831 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7832 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7833 return 0;
7834}
7835
7836__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7837{
7838 struct hlua_txn *htxn;
7839
7840 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7841 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7842 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7843 return 0;
7844}
7845
Christopher Faulet700d9e82020-01-31 12:21:52 +01007846/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007847 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007848 * message and terminate the transaction. It returns 1 on success and 0 on
7849 * error. The Reply must be on top of the stack.
7850 */
7851__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7852{
7853 struct htx *htx;
7854 struct htx_sl *sl;
7855 struct h1m h1m;
7856 const char *status, *reason, *body;
7857 size_t status_len, reason_len, body_len;
7858 int ret, code, flags;
7859
7860 code = 200;
7861 status = "200";
7862 status_len = 3;
7863 ret = lua_getfield(L, -1, "status");
7864 if (ret == LUA_TNUMBER) {
7865 code = lua_tointeger(L, -1);
7866 status = lua_tolstring(L, -1, &status_len);
7867 }
7868 lua_pop(L, 1);
7869
7870 reason = http_get_reason(code);
7871 reason_len = strlen(reason);
7872 ret = lua_getfield(L, -1, "reason");
7873 if (ret == LUA_TSTRING)
7874 reason = lua_tolstring(L, -1, &reason_len);
7875 lua_pop(L, 1);
7876
7877 body = NULL;
7878 body_len = 0;
7879 ret = lua_getfield(L, -1, "body");
7880 if (ret == LUA_TSTRING)
7881 body = lua_tolstring(L, -1, &body_len);
7882 lua_pop(L, 1);
7883
7884 /* Prepare the response before inserting the headers */
7885 h1m_init_res(&h1m);
7886 htx = htx_from_buf(&s->res.buf);
7887 channel_htx_truncate(&s->res, htx);
7888 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7889 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7890 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7891 ist2(status, status_len), ist2(reason, reason_len));
7892 }
7893 else {
7894 flags = HTX_SL_F_IS_RESP;
7895 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7896 ist2(status, status_len), ist2(reason, reason_len));
7897 }
7898 if (!sl)
7899 goto fail;
7900 sl->info.res.status = code;
7901
7902 /* Push in the stack the "headers" entry. */
7903 ret = lua_getfield(L, -1, "headers");
7904 if (ret != LUA_TTABLE)
7905 goto skip_headers;
7906
7907 lua_pushnil(L);
7908 while (lua_next(L, -2) != 0) {
7909 struct ist name, value;
7910 const char *n, *v;
7911 size_t nlen, vlen;
7912
7913 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7914 /* Skip element if the key is not a string or if the value is not a table */
7915 goto next_hdr;
7916 }
7917
7918 n = lua_tolstring(L, -2, &nlen);
7919 name = ist2(n, nlen);
7920 if (isteqi(name, ist("content-length"))) {
7921 /* Always skip content-length header. It will be added
7922 * later with the correct len
7923 */
7924 goto next_hdr;
7925 }
7926
7927 /* Loop on header's values */
7928 lua_pushnil(L);
7929 while (lua_next(L, -2)) {
7930 if (!lua_isstring(L, -1)) {
7931 /* Skip the value if it is not a string */
7932 goto next_value;
7933 }
7934
7935 v = lua_tolstring(L, -1, &vlen);
7936 value = ist2(v, vlen);
7937
7938 if (isteqi(name, ist("transfer-encoding")))
7939 h1_parse_xfer_enc_header(&h1m, value);
7940 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7941 goto fail;
7942
7943 next_value:
7944 lua_pop(L, 1);
7945 }
7946
7947 next_hdr:
7948 lua_pop(L, 1);
7949 }
7950 skip_headers:
7951 lua_pop(L, 1);
7952
7953 /* Update h1m flags: CLEN is set if CHNK is not present */
7954 if (!(h1m.flags & H1_MF_CHNK)) {
7955 const char *clen = ultoa(body_len);
7956
7957 h1m.flags |= H1_MF_CLEN;
7958 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7959 goto fail;
7960 }
7961 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7962 h1m.flags |= H1_MF_XFER_LEN;
7963
7964 /* Update HTX start-line flags */
7965 if (h1m.flags & H1_MF_XFER_ENC)
7966 flags |= HTX_SL_F_XFER_ENC;
7967 if (h1m.flags & H1_MF_XFER_LEN) {
7968 flags |= HTX_SL_F_XFER_LEN;
7969 if (h1m.flags & H1_MF_CHNK)
7970 flags |= HTX_SL_F_CHNK;
7971 else if (h1m.flags & H1_MF_CLEN)
7972 flags |= HTX_SL_F_CLEN;
7973 if (h1m.body_len == 0)
7974 flags |= HTX_SL_F_BODYLESS;
7975 }
7976 sl->flags |= flags;
7977
7978
7979 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007980 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007981 goto fail;
7982
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007983 htx->flags |= HTX_FL_EOM;
7984
Christopher Faulet700d9e82020-01-31 12:21:52 +01007985 /* Now, forward the response and terminate the transaction */
7986 s->txn->status = code;
7987 htx_to_buf(htx, &s->res.buf);
7988 if (!http_forward_proxy_resp(s, 1))
7989 goto fail;
7990
7991 return 1;
7992
7993 fail:
7994 channel_htx_truncate(&s->res, htx);
7995 return 0;
7996}
7997
7998/* Terminate a transaction if called from a lua action. For TCP streams,
7999 * processing is just aborted. Nothing is returned to the client and all
8000 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8001 * is forwarded to the client before terminating the transaction. On success,
8002 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8003 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8004 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008005 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008006__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008007{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008008 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008009 struct stream *s;
8010 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008011
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008012 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008013
Christopher Faulet700d9e82020-01-31 12:21:52 +01008014 /* If the flags NOTERM is set, we cannot terminate the session, so we
8015 * just end the execution of the current lua code. */
8016 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008017 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008018
Christopher Faulet700d9e82020-01-31 12:21:52 +01008019 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008020 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008021 struct channel *req = &s->req;
8022 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008023
Christopher Faulet700d9e82020-01-31 12:21:52 +01008024 channel_auto_read(req);
8025 channel_abort(req);
8026 channel_auto_close(req);
8027 channel_erase(req);
8028
8029 res->wex = tick_add_ifset(now_ms, res->wto);
8030 channel_auto_read(res);
8031 channel_auto_close(res);
8032 channel_shutr_now(res);
8033
8034 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8035 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008036 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008037
Christopher Faulet700d9e82020-01-31 12:21:52 +01008038 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8039 /* No reply or invalid reply */
8040 s->txn->status = 0;
8041 http_reply_and_close(s, 0, NULL);
8042 }
8043 else {
8044 /* Remove extra args to have the reply on top of the stack */
8045 if (lua_gettop(L) > 2)
8046 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008047
Christopher Faulet700d9e82020-01-31 12:21:52 +01008048 if (!hlua_txn_forward_reply(L, s)) {
8049 if (!(s->flags & SF_ERR_MASK))
8050 s->flags |= SF_ERR_PRXCOND;
8051 lua_pushinteger(L, ACT_RET_ERR);
8052 WILL_LJMP(hlua_done(L));
8053 return 0; /* Never reached */
8054 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008055 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008056
Christopher Faulet700d9e82020-01-31 12:21:52 +01008057 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8058 if (htxn->dir == SMP_OPT_DIR_REQ) {
8059 /* let's log the request time */
8060 s->logs.tv_request = now;
8061 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008062 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008063 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008064
Christopher Faulet700d9e82020-01-31 12:21:52 +01008065 done:
8066 if (!(s->flags & SF_ERR_MASK))
8067 s->flags |= SF_ERR_LOCAL;
8068 if (!(s->flags & SF_FINST_MASK))
8069 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008070
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008071 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8072 lua_pushinteger(L, -1);
8073 else
8074 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008075 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008076 return 0;
8077}
8078
Christopher Faulet700d9e82020-01-31 12:21:52 +01008079/*
8080 *
8081 *
8082 * Class REPLY
8083 *
8084 *
8085 */
8086
8087/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8088 * free slots, the function fails and returns 0;
8089 */
8090static int hlua_txn_reply_new(lua_State *L)
8091{
8092 struct hlua_txn *htxn;
8093 const char *reason, *body = NULL;
8094 int ret, status;
8095
8096 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008097 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008098 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8099 WILL_LJMP(lua_error(L));
8100 }
8101
8102 /* Default value */
8103 status = 200;
8104 reason = http_get_reason(status);
8105
8106 if (lua_istable(L, 2)) {
8107 /* load status and reason from the table argument at index 2 */
8108 ret = lua_getfield(L, 2, "status");
8109 if (ret == LUA_TNIL)
8110 goto reason;
8111 else if (ret != LUA_TNUMBER) {
8112 /* invalid status: ignore the reason */
8113 goto body;
8114 }
8115 status = lua_tointeger(L, -1);
8116
8117 reason:
8118 lua_pop(L, 1); /* restore the stack: remove status */
8119 ret = lua_getfield(L, 2, "reason");
8120 if (ret == LUA_TSTRING)
8121 reason = lua_tostring(L, -1);
8122
8123 body:
8124 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8125 ret = lua_getfield(L, 2, "body");
8126 if (ret == LUA_TSTRING)
8127 body = lua_tostring(L, -1);
8128 lua_pop(L, 1); /* restore the stack: remove body */
8129 }
8130
8131 /* Create the Reply table */
8132 lua_newtable(L);
8133
8134 /* Add status element */
8135 lua_pushstring(L, "status");
8136 lua_pushinteger(L, status);
8137 lua_settable(L, -3);
8138
8139 /* Add reason element */
8140 reason = http_get_reason(status);
8141 lua_pushstring(L, "reason");
8142 lua_pushstring(L, reason);
8143 lua_settable(L, -3);
8144
8145 /* Add body element, nil if undefined */
8146 lua_pushstring(L, "body");
8147 if (body)
8148 lua_pushstring(L, body);
8149 else
8150 lua_pushnil(L);
8151 lua_settable(L, -3);
8152
8153 /* Add headers element */
8154 lua_pushstring(L, "headers");
8155 lua_newtable(L);
8156
8157 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8158 if (lua_istable(L, 2)) {
8159 /* load headers from the table argument at index 2. If it is a table, copy it. */
8160 ret = lua_getfield(L, 2, "headers");
8161 if (ret == LUA_TTABLE) {
8162 /* stack: [ ... <headers:table>, <table> ] */
8163 lua_pushnil(L);
8164 while (lua_next(L, -2) != 0) {
8165 /* stack: [ ... <headers:table>, <table>, k, v] */
8166 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8167 /* invalid value type, skip it */
8168 lua_pop(L, 1);
8169 continue;
8170 }
8171
8172
8173 /* Duplicate the key and swap it with the value. */
8174 lua_pushvalue(L, -2);
8175 lua_insert(L, -2);
8176 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8177
8178 lua_newtable(L);
8179 lua_insert(L, -2);
8180 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8181
8182 if (lua_isstring(L, -1)) {
8183 /* push the value in the inner table */
8184 lua_rawseti(L, -2, 1);
8185 }
8186 else { /* table */
8187 lua_pushnil(L);
8188 while (lua_next(L, -2) != 0) {
8189 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8190 if (!lua_isstring(L, -1)) {
8191 /* invalid value type, skip it*/
8192 lua_pop(L, 1);
8193 continue;
8194 }
8195 /* push the value in the inner table */
8196 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8197 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8198 }
8199 lua_pop(L, 1);
8200 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8201 }
8202
8203 /* push (k,v) on the stack in the headers table:
8204 * stack: [ ... <headers:table>, <table>, k, k, v ]
8205 */
8206 lua_settable(L, -5);
8207 /* stack: [ ... <headers:table>, <table>, k ] */
8208 }
8209 }
8210 lua_pop(L, 1);
8211 }
8212 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8213 lua_settable(L, -3);
8214 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8215
8216 /* Pop a class sesison metatable and affect it to the userdata. */
8217 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8218 lua_setmetatable(L, -2);
8219 return 1;
8220}
8221
8222/* Set the reply status code, and optionally the reason. If no reason is
8223 * provided, the default one corresponding to the status code is used.
8224 */
8225__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8226{
8227 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8228 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8229
8230 /* First argument (self) must be a table */
8231 luaL_checktype(L, 1, LUA_TTABLE);
8232
8233 if (status < 100 || status > 599) {
8234 lua_pushboolean(L, 0);
8235 return 1;
8236 }
8237 if (!reason)
8238 reason = http_get_reason(status);
8239
8240 lua_pushinteger(L, status);
8241 lua_setfield(L, 1, "status");
8242
8243 lua_pushstring(L, reason);
8244 lua_setfield(L, 1, "reason");
8245
8246 lua_pushboolean(L, 1);
8247 return 1;
8248}
8249
8250/* Add a header into the reply object. Each header name is associated to an
8251 * array of values in the "headers" table. If the header name is not found, a
8252 * new entry is created.
8253 */
8254__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8255{
8256 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8257 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8258 int ret;
8259
8260 /* First argument (self) must be a table */
8261 luaL_checktype(L, 1, LUA_TTABLE);
8262
8263 /* Push in the stack the "headers" entry. */
8264 ret = lua_getfield(L, 1, "headers");
8265 if (ret != LUA_TTABLE) {
8266 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8267 WILL_LJMP(lua_error(L));
8268 }
8269
8270 /* check if the header is already registered. If not, register it. */
8271 ret = lua_getfield(L, -1, name);
8272 if (ret == LUA_TNIL) {
8273 /* Entry not found. */
8274 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8275
8276 /* Insert the new header name in the array in the top of the stack.
8277 * It left the new array in the top of the stack.
8278 */
8279 lua_newtable(L);
8280 lua_pushstring(L, name);
8281 lua_pushvalue(L, -2);
8282 lua_settable(L, -4);
8283 }
8284 else if (ret != LUA_TTABLE) {
8285 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8286 WILL_LJMP(lua_error(L));
8287 }
8288
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008289 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008290 * the header value as new entry.
8291 */
8292 lua_pushstring(L, value);
8293 ret = lua_rawlen(L, -2);
8294 lua_rawseti(L, -2, ret + 1);
8295
8296 lua_pushboolean(L, 1);
8297 return 1;
8298}
8299
8300/* Remove all occurrences of a given header name. */
8301__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8302{
8303 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8304 int ret;
8305
8306 /* First argument (self) must be a table */
8307 luaL_checktype(L, 1, LUA_TTABLE);
8308
8309 /* Push in the stack the "headers" entry. */
8310 ret = lua_getfield(L, 1, "headers");
8311 if (ret != LUA_TTABLE) {
8312 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8313 WILL_LJMP(lua_error(L));
8314 }
8315
8316 lua_pushstring(L, name);
8317 lua_pushnil(L);
8318 lua_settable(L, -3);
8319
8320 lua_pushboolean(L, 1);
8321 return 1;
8322}
8323
8324/* Set the reply's body. Overwrite any existing entry. */
8325__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8326{
8327 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8328
8329 /* First argument (self) must be a table */
8330 luaL_checktype(L, 1, LUA_TTABLE);
8331
8332 lua_pushstring(L, payload);
8333 lua_setfield(L, 1, "body");
8334
8335 lua_pushboolean(L, 1);
8336 return 1;
8337}
8338
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008339__LJMP static int hlua_log(lua_State *L)
8340{
8341 int level;
8342 const char *msg;
8343
8344 MAY_LJMP(check_args(L, 2, "log"));
8345 level = MAY_LJMP(luaL_checkinteger(L, 1));
8346 msg = MAY_LJMP(luaL_checkstring(L, 2));
8347
8348 if (level < 0 || level >= NB_LOG_LEVELS)
8349 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8350
8351 hlua_sendlog(NULL, level, msg);
8352 return 0;
8353}
8354
8355__LJMP static int hlua_log_debug(lua_State *L)
8356{
8357 const char *msg;
8358
8359 MAY_LJMP(check_args(L, 1, "debug"));
8360 msg = MAY_LJMP(luaL_checkstring(L, 1));
8361 hlua_sendlog(NULL, LOG_DEBUG, msg);
8362 return 0;
8363}
8364
8365__LJMP static int hlua_log_info(lua_State *L)
8366{
8367 const char *msg;
8368
8369 MAY_LJMP(check_args(L, 1, "info"));
8370 msg = MAY_LJMP(luaL_checkstring(L, 1));
8371 hlua_sendlog(NULL, LOG_INFO, msg);
8372 return 0;
8373}
8374
8375__LJMP static int hlua_log_warning(lua_State *L)
8376{
8377 const char *msg;
8378
8379 MAY_LJMP(check_args(L, 1, "warning"));
8380 msg = MAY_LJMP(luaL_checkstring(L, 1));
8381 hlua_sendlog(NULL, LOG_WARNING, msg);
8382 return 0;
8383}
8384
8385__LJMP static int hlua_log_alert(lua_State *L)
8386{
8387 const char *msg;
8388
8389 MAY_LJMP(check_args(L, 1, "alert"));
8390 msg = MAY_LJMP(luaL_checkstring(L, 1));
8391 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008392 return 0;
8393}
8394
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008395__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008396{
8397 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008398 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008399 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008400 return 0;
8401}
8402
8403__LJMP static int hlua_sleep(lua_State *L)
8404{
8405 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008406 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008407
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008408 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008409
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008410 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008411 wakeup_ms = tick_add(now_ms, delay);
8412 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008413
Willy Tarreau9635e032018-10-16 17:52:55 +02008414 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008415 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008416}
8417
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008418__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008419{
8420 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008421 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008422
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008423 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008424
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008425 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008426 wakeup_ms = tick_add(now_ms, delay);
8427 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008428
Willy Tarreau9635e032018-10-16 17:52:55 +02008429 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008430 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008431}
8432
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008433/* This functionis an LUA binding. it permits to give back
8434 * the hand at the HAProxy scheduler. It is used when the
8435 * LUA processing consumes a lot of time.
8436 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008437__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008438{
8439 return 0;
8440}
8441
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008442__LJMP static int hlua_yield(lua_State *L)
8443{
Willy Tarreau9635e032018-10-16 17:52:55 +02008444 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008445 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008446}
8447
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008448/* This function change the nice of the currently executed
8449 * task. It is used set low or high priority at the current
8450 * task.
8451 */
Willy Tarreau59551662015-03-10 14:23:13 +01008452__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008453{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008454 struct hlua *hlua;
8455 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008456
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008457 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008458 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008459
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008460 /* Get hlua struct, or NULL if we execute from main lua state */
8461 hlua = hlua_gethlua(L);
8462
8463 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008464 if (!hlua || !hlua->task)
8465 return 0;
8466
8467 if (nice < -1024)
8468 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008469 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008470 nice = 1024;
8471
8472 hlua->task->nice = nice;
8473 return 0;
8474}
8475
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008476/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008477 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8478 * return an E_AGAIN signal, the emmiter of this signal must set a
8479 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008480 *
8481 * Task wrapper are longjmp safe because the only one Lua code
8482 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008483 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008484struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008485{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008486 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008487 enum hlua_exec status;
8488
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008489 if (task->tid < 0)
8490 task->tid = tid;
8491
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008492 /* If it is the first call to the task, we must initialize the
8493 * execution timeouts.
8494 */
8495 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008496 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008497
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008498 /* Execute the Lua code. */
8499 status = hlua_ctx_resume(hlua, 1);
8500
8501 switch (status) {
8502 /* finished or yield */
8503 case HLUA_E_OK:
8504 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008505 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008506 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008507 break;
8508
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008509 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008510 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008511 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008512 break;
8513
8514 /* finished with error. */
8515 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008516 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008517 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008518 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008519 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008520 break;
8521
8522 case HLUA_E_ERR:
8523 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008524 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008525 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008526 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008527 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008528 break;
8529 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008530 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008531}
8532
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008533/* This function is an LUA binding that register LUA function to be
8534 * executed after the HAProxy configuration parsing and before the
8535 * HAProxy scheduler starts. This function expect only one LUA
8536 * argument that is a function. This function returns nothing, but
8537 * throws if an error is encountered.
8538 */
8539__LJMP static int hlua_register_init(lua_State *L)
8540{
8541 struct hlua_init_function *init;
8542 int ref;
8543
8544 MAY_LJMP(check_args(L, 1, "register_init"));
8545
8546 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8547
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008548 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008549 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008550 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008551
8552 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008553 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008554 return 0;
8555}
8556
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008557/* This functio is an LUA binding. It permits to register a task
8558 * executed in parallel of the main HAroxy activity. The task is
8559 * created and it is set in the HAProxy scheduler. It can be called
8560 * from the "init" section, "post init" or during the runtime.
8561 *
8562 * Lua prototype:
8563 *
8564 * <none> core.register_task(<function>)
8565 */
8566static int hlua_register_task(lua_State *L)
8567{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008568 struct hlua *hlua = NULL;
8569 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008570 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008571 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008572
8573 MAY_LJMP(check_args(L, 1, "register_task"));
8574
8575 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8576
Thierry Fournier75fc0292020-11-28 13:18:56 +01008577 /* Get the reference state. If the reference is NULL, L is the master
8578 * state, otherwise hlua->T is.
8579 */
8580 hlua = hlua_gethlua(L);
8581 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008582 /* we are in runtime processing */
8583 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008584 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008585 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008586 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008587
Willy Tarreaubafbe012017-11-24 17:34:44 +01008588 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008589 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008590 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008591 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008592
Thierry Fournier59f11be2020-11-29 00:37:41 +01008593 /* We are in the common lua state, execute the task anywhere,
8594 * otherwise, inherit the current thread identifier
8595 */
8596 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008597 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008598 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008599 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008600 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008601 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008602
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008603 task->context = hlua;
8604 task->process = hlua_process_task;
8605
Thierry Fournier021d9862020-11-28 23:42:03 +01008606 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008607 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008608
8609 /* Restore the function in the stack. */
8610 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8611 hlua->nargs = 0;
8612
8613 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008614 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008615
8616 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008617
8618 alloc_error:
8619 task_destroy(task);
8620 hlua_ctx_destroy(hlua);
8621 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8622 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008623}
8624
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008625/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8626 * doesn't allow "yield" functions because the HAProxy engine cannot
8627 * resume converters.
8628 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008629static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008630{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008631 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008632 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008633 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008634
Willy Tarreaube508f12016-03-10 11:47:01 +01008635 if (!stream)
8636 return 0;
8637
Willy Tarreau87b09662015-04-03 00:22:06 +02008638 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008639 * Lua context can be not initialized. This behavior
8640 * permits to save performances because a systematic
8641 * Lua initialization cause 5% performances loss.
8642 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008643 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008644 struct hlua *hlua;
8645
8646 hlua = pool_alloc(pool_head_hlua);
8647 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008648 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8649 return 0;
8650 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008651 HLUA_INIT(hlua);
8652 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008653 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008654 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8655 return 0;
8656 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008657 }
8658
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008659 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008660 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008661
8662 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008663 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008664 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8665 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008666 else
8667 error = "critical error";
8668 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008669 return 0;
8670 }
8671
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008672 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008673 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008674 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008675 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008676 return 0;
8677 }
8678
8679 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008680 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008681
8682 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008683 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008684 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008685 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008686 return 0;
8687 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008688 hlua_smp2lua(stream->hlua->T, smp);
8689 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008690
8691 /* push keywords in the stack. */
8692 if (arg_p) {
8693 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008694 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008695 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008696 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008697 return 0;
8698 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008699 hlua_arg2lua(stream->hlua->T, arg_p);
8700 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008701 }
8702 }
8703
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008704 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008705 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008706
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008707 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008708 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008709 }
8710
8711 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008712 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008713 /* finished. */
8714 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008715 /* If the stack is empty, the function fails. */
8716 if (lua_gettop(stream->hlua->T) <= 0)
8717 return 0;
8718
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008719 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008720 hlua_lua2smp(stream->hlua->T, -1, smp);
8721 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008722 return 1;
8723
8724 /* yield. */
8725 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008726 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008727 return 0;
8728
8729 /* finished with error. */
8730 case HLUA_E_ERRMSG:
8731 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008732 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008733 fcn->name, lua_tostring(stream->hlua->T, -1));
8734 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008735 return 0;
8736
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008737 case HLUA_E_ETMOUT:
8738 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8739 return 0;
8740
8741 case HLUA_E_NOMEM:
8742 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8743 return 0;
8744
8745 case HLUA_E_YIELD:
8746 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8747 return 0;
8748
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008749 case HLUA_E_ERR:
8750 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008751 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008752 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008753
8754 default:
8755 return 0;
8756 }
8757}
8758
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008759/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8760 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008761 * resume sample-fetches. This function will be called by the sample
8762 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008763 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008764static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8765 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008766{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008767 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008768 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008769 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008770 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008771
Willy Tarreaube508f12016-03-10 11:47:01 +01008772 if (!stream)
8773 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008774
Willy Tarreau87b09662015-04-03 00:22:06 +02008775 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008776 * Lua context can be not initialized. This behavior
8777 * permits to save performances because a systematic
8778 * Lua initialization cause 5% performances loss.
8779 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008780 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008781 struct hlua *hlua;
8782
8783 hlua = pool_alloc(pool_head_hlua);
8784 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008785 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8786 return 0;
8787 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008788 hlua->T = NULL;
8789 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008790 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008791 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8792 return 0;
8793 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008794 }
8795
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008796 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008797 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008798
8799 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008800 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008801 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8802 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008803 else
8804 error = "critical error";
8805 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008806 return 0;
8807 }
8808
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008809 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008810 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008811 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008812 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008813 return 0;
8814 }
8815
8816 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008817 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008818
8819 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008820 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008821 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008822 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008823 return 0;
8824 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008825 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008826
8827 /* push keywords in the stack. */
8828 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8829 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008830 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008831 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008832 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008833 return 0;
8834 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008835 hlua_arg2lua(stream->hlua->T, arg_p);
8836 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008837 }
8838
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008839 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008840 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008841
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008842 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008843 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008844 }
8845
8846 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008847 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008848 /* finished. */
8849 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008850 /* If the stack is empty, the function fails. */
8851 if (lua_gettop(stream->hlua->T) <= 0)
8852 return 0;
8853
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008854 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008855 hlua_lua2smp(stream->hlua->T, -1, smp);
8856 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008857
8858 /* Set the end of execution flag. */
8859 smp->flags &= ~SMP_F_MAY_CHANGE;
8860 return 1;
8861
8862 /* yield. */
8863 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008864 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008865 return 0;
8866
8867 /* finished with error. */
8868 case HLUA_E_ERRMSG:
8869 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008870 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008871 fcn->name, lua_tostring(stream->hlua->T, -1));
8872 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008873 return 0;
8874
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008875 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008876 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8877 return 0;
8878
8879 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008880 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8881 return 0;
8882
8883 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008884 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8885 return 0;
8886
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008887 case HLUA_E_ERR:
8888 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008889 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008890 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008891
8892 default:
8893 return 0;
8894 }
8895}
8896
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008897/* This function is an LUA binding used for registering
8898 * "sample-conv" functions. It expects a converter name used
8899 * in the haproxy configuration file, and an LUA function.
8900 */
8901__LJMP static int hlua_register_converters(lua_State *L)
8902{
8903 struct sample_conv_kw_list *sck;
8904 const char *name;
8905 int ref;
8906 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008907 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008908 struct sample_conv *sc;
8909 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008910
8911 MAY_LJMP(check_args(L, 2, "register_converters"));
8912
8913 /* First argument : converter name. */
8914 name = MAY_LJMP(luaL_checkstring(L, 1));
8915
8916 /* Second argument : lua function. */
8917 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8918
Thierry Fournierf67442e2020-11-28 20:41:07 +01008919 /* Check if the converter is already registered */
8920 trash = get_trash_chunk();
8921 chunk_printf(trash, "lua.%s", name);
8922 sc = find_sample_conv(trash->area, trash->data);
8923 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008924 fcn = sc->private;
8925 if (fcn->function_ref[hlua_state_id] != -1) {
8926 ha_warning("Trying to register converter 'lua.%s' more than once. "
8927 "This will become a hard error in version 2.5.\n", name);
8928 }
8929 fcn->function_ref[hlua_state_id] = ref;
8930 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008931 }
8932
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008933 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008934 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008935 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008936 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008937 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008938 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008939 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008940
8941 /* Fill fcn. */
8942 fcn->name = strdup(name);
8943 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008944 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008945 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008946
8947 /* List head */
8948 sck->list.n = sck->list.p = NULL;
8949
8950 /* converter keyword. */
8951 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008952 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008953 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008954 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008955
8956 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8957 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008958 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 +01008959 sck->kw[0].val_args = NULL;
8960 sck->kw[0].in_type = SMP_T_STR;
8961 sck->kw[0].out_type = SMP_T_STR;
8962 sck->kw[0].private = fcn;
8963
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008964 /* Register this new converter */
8965 sample_register_convs(sck);
8966
8967 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008968
8969 alloc_error:
8970 release_hlua_function(fcn);
8971 ha_free(&sck);
8972 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8973 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008974}
8975
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008976/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008977 * "sample-fetch" functions. It expects a converter name used
8978 * in the haproxy configuration file, and an LUA function.
8979 */
8980__LJMP static int hlua_register_fetches(lua_State *L)
8981{
8982 const char *name;
8983 int ref;
8984 int len;
8985 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008986 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008987 struct sample_fetch *sf;
8988 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008989
8990 MAY_LJMP(check_args(L, 2, "register_fetches"));
8991
8992 /* First argument : sample-fetch name. */
8993 name = MAY_LJMP(luaL_checkstring(L, 1));
8994
8995 /* Second argument : lua function. */
8996 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8997
Thierry Fournierf67442e2020-11-28 20:41:07 +01008998 /* Check if the sample-fetch is already registered */
8999 trash = get_trash_chunk();
9000 chunk_printf(trash, "lua.%s", name);
9001 sf = find_sample_fetch(trash->area, trash->data);
9002 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009003 fcn = sf->private;
9004 if (fcn->function_ref[hlua_state_id] != -1) {
9005 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9006 "This will become a hard error in version 2.5.\n", name);
9007 }
9008 fcn->function_ref[hlua_state_id] = ref;
9009 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009010 }
9011
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009012 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009013 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009014 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009015 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009016 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009017 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009018 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009019
9020 /* Fill fcn. */
9021 fcn->name = strdup(name);
9022 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009023 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009024 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009025
9026 /* List head */
9027 sfk->list.n = sfk->list.p = NULL;
9028
9029 /* sample-fetch keyword. */
9030 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009031 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009032 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009033 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009034
9035 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9036 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009037 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 +01009038 sfk->kw[0].val_args = NULL;
9039 sfk->kw[0].out_type = SMP_T_STR;
9040 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9041 sfk->kw[0].val = 0;
9042 sfk->kw[0].private = fcn;
9043
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009044 /* Register this new fetch. */
9045 sample_register_fetches(sfk);
9046
9047 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009048
9049 alloc_error:
9050 release_hlua_function(fcn);
9051 ha_free(&sfk);
9052 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9053 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009054}
9055
Christopher Faulet501465d2020-02-26 14:54:16 +01009056/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009057 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009058__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009059{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009060 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009061 unsigned int delay;
9062 unsigned int wakeup_ms;
9063
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009064 /* Get hlua struct, or NULL if we execute from main lua state */
9065 hlua = hlua_gethlua(L);
9066 if (!hlua) {
9067 return 0;
9068 }
9069
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009070 MAY_LJMP(check_args(L, 1, "wake_time"));
9071
9072 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9073 wakeup_ms = tick_add(now_ms, delay);
9074 hlua->wake_time = wakeup_ms;
9075 return 0;
9076}
9077
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009078/* This function is a wrapper to execute each LUA function declared as an action
9079 * wrapper during the initialisation period. This function may return any
9080 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9081 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9082 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009083 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009084static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009085 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009086{
9087 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009088 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009089 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009090 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009091
9092 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009093 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9094 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9095 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9096 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009097 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009098 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009099 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009100 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009101
Willy Tarreau87b09662015-04-03 00:22:06 +02009102 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009103 * Lua context can be not initialized. This behavior
9104 * permits to save performances because a systematic
9105 * Lua initialization cause 5% performances loss.
9106 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009107 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009108 struct hlua *hlua;
9109
9110 hlua = pool_alloc(pool_head_hlua);
9111 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009112 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009113 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009114 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009115 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009116 HLUA_INIT(hlua);
9117 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009118 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 +01009119 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009120 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009121 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009122 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009123 }
9124
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009125 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009126 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009127
9128 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009129 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009130 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9131 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009132 else
9133 error = "critical error";
9134 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009135 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009136 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009137 }
9138
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009139 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009140 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009141 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009142 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009143 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009144 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009145 }
9146
9147 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009148 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 +01009149
Willy Tarreau87b09662015-04-03 00:22:06 +02009150 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009151 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009152 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009153 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009154 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009155 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009156 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009157 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009158
9159 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009160 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009161 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009162 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009163 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009164 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009165 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009166 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009167 lua_pushstring(s->hlua->T, *arg);
9168 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009169 }
9170
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009171 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009172 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009173
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009174 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009175 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009176 }
9177
9178 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009179 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009180 /* finished. */
9181 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009182 /* Catch the return value */
9183 if (lua_gettop(s->hlua->T) > 0)
9184 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009185
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009186 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009187 if (act_ret == ACT_RET_YIELD) {
9188 if (flags & ACT_OPT_FINAL)
9189 goto err_yield;
9190
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009191 if (dir == SMP_OPT_DIR_REQ)
9192 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9193 s->hlua->wake_time);
9194 else
9195 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9196 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009197 }
9198 goto end;
9199
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009200 /* yield. */
9201 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009202 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009203 if (dir == SMP_OPT_DIR_REQ)
9204 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9205 s->hlua->wake_time);
9206 else
9207 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9208 s->hlua->wake_time);
9209
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009210 /* Some actions can be wake up when a "write" event
9211 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009212 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009213 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009214 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009215 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009216 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009217 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009218 act_ret = ACT_RET_YIELD;
9219 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009220
9221 /* finished with error. */
9222 case HLUA_E_ERRMSG:
9223 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009224 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009225 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009226 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009227 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009228
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009229 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009230 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009231 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009232
9233 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009234 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009235 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009236
9237 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009238 err_yield:
9239 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009240 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009241 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009242 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009243
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009244 case HLUA_E_ERR:
9245 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009246 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009247 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009248
9249 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009250 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009251 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009252
9253 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009254 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009255 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009256 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009257}
9258
Willy Tarreau144f84a2021-03-02 16:09:26 +01009259struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009260{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009261 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009262
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009263 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009264 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009265 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009266}
9267
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009268static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009269{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009270 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009271 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009272 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009273 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009274 struct task *task;
9275 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009276 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009277
Willy Tarreaubafbe012017-11-24 17:34:44 +01009278 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009279 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009280 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009281 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009282 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009283 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009284 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009285 tcp_ctx->hlua = hlua;
9286 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009287
9288 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009289 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009290 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009291 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009292 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009293 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009294 }
9295 task->nice = 0;
9296 task->context = ctx;
9297 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009298 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299
9300 /* In the execution wrappers linked with a stream, the
9301 * Lua context can be not initialized. This behavior
9302 * permits to save performances because a systematic
9303 * Lua initialization cause 5% performances loss.
9304 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009305 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 +01009306 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009307 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009308 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009309 }
9310
9311 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009312 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009313
9314 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009315 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009316 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9317 error = lua_tostring(hlua->T, -1);
9318 else
9319 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009320 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009321 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009322 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009323 }
9324
9325 /* Check stack available size. */
9326 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009327 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009328 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009329 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009330 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009331 }
9332
9333 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009334 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009335
9336 /* Create and and push object stream in the stack. */
9337 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009338 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009339 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009340 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009341 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009342 }
9343 hlua->nargs = 1;
9344
9345 /* push keywords in the stack. */
9346 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9347 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009348 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009349 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009350 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009351 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009352 }
9353 lua_pushstring(hlua->T, *arg);
9354 hlua->nargs++;
9355 }
9356
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009357 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358
9359 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009360 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009361 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009362
Christopher Fauletc9929382022-05-12 11:52:27 +02009363 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009364}
9365
Willy Tarreau60409db2019-08-21 14:14:50 +02009366void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009367{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009368 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009369 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009370 struct stream *strm = __sc_strm(sc);
9371 struct channel *res = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372 struct act_rule *rule = ctx->rule;
9373 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009374 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009375
9376 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009377 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009378 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009379 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009380 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009381 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009382
9383 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009384 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009385 return;
9386
9387 /* Execute the function. */
9388 switch (hlua_ctx_resume(hlua, 1)) {
9389 /* finished. */
9390 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009391 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009392
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009393 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009394 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009395 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009396 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009397 return;
9398
9399 /* yield. */
9400 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009401 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009402 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009403 return;
9404
9405 /* finished with error. */
9406 case HLUA_E_ERRMSG:
9407 /* Display log. */
9408 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009409 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009410 lua_pop(hlua->T, 1);
9411 goto error;
9412
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009413 case HLUA_E_ETMOUT:
9414 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009415 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009416 goto error;
9417
9418 case HLUA_E_NOMEM:
9419 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009420 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009421 goto error;
9422
9423 case HLUA_E_YIELD: /* unexpected */
9424 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009425 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009426 goto error;
9427
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009428 case HLUA_E_ERR:
9429 /* Display log. */
9430 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009431 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009432 goto error;
9433
9434 default:
9435 goto error;
9436 }
9437
9438error:
9439
9440 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009441 sc_shutw(sc);
9442 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009443 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009444}
9445
9446static void hlua_applet_tcp_release(struct appctx *ctx)
9447{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009448 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9449
9450 task_destroy(tcp_ctx->task);
9451 tcp_ctx->task = NULL;
9452 hlua_ctx_destroy(tcp_ctx->hlua);
9453 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009454}
9455
Christopher Fauletc9929382022-05-12 11:52:27 +02009456/* The function returns 0 if the initialisation is complete or -1 if
9457 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009458 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009459static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009460{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009461 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009462 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009463 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009464 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009465 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009466 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009467 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009468 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009469
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009470 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009471 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009472 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009473 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009474 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009475 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009476 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009477 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009478 http_ctx->hlua = hlua;
9479 http_ctx->left_bytes = -1;
9480 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009481
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009482 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009483 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009484
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009485 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009486 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009487 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009488 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009489 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009490 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009491 }
9492 task->nice = 0;
9493 task->context = ctx;
9494 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009495 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009496
9497 /* In the execution wrappers linked with a stream, the
9498 * Lua context can be not initialized. This behavior
9499 * permits to save performances because a systematic
9500 * Lua initialization cause 5% performances loss.
9501 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009502 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 +01009503 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009504 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009505 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009506 }
9507
9508 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009509 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009510
9511 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009512 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009513 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9514 error = lua_tostring(hlua->T, -1);
9515 else
9516 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009517 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009518 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009519 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009520 }
9521
9522 /* Check stack available size. */
9523 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009524 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009525 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009526 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009527 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009528 }
9529
9530 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009531 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009532
9533 /* Create and and push object stream in the stack. */
9534 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009535 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009536 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009537 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009538 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009539 }
9540 hlua->nargs = 1;
9541
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009542 /* push keywords in the stack. */
9543 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9544 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009545 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009546 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009547 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009548 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009549 }
9550 lua_pushstring(hlua->T, *arg);
9551 hlua->nargs++;
9552 }
9553
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009554 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009555
9556 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009557 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009558
Christopher Fauletc9929382022-05-12 11:52:27 +02009559 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009560}
9561
Willy Tarreau60409db2019-08-21 14:14:50 +02009562void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009563{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009564 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009565 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009566 struct stream *strm = __sc_strm(sc);
9567 struct channel *req = sc_oc(sc);
9568 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009569 struct act_rule *rule = ctx->rule;
9570 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009571 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009572 struct htx *req_htx, *res_htx;
9573
9574 res_htx = htx_from_buf(&res->buf);
9575
9576 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009577 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009578 goto out;
9579
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009580 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009581 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009582 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009583 goto out;
9584 }
9585 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009586 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009587 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009588
9589 /* Set the currently running flag. */
9590 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009591 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009592 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009593 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009594 goto out;
9595 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009596 }
9597
9598 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009599 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009600
9601 /* Execute the function. */
9602 switch (hlua_ctx_resume(hlua, 1)) {
9603 /* finished. */
9604 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009605 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009606 break;
9607
9608 /* yield. */
9609 case HLUA_E_AGAIN:
9610 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009611 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009612 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009613
9614 /* finished with error. */
9615 case HLUA_E_ERRMSG:
9616 /* Display log. */
9617 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009618 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009619 lua_pop(hlua->T, 1);
9620 goto error;
9621
9622 case HLUA_E_ETMOUT:
9623 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009624 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009625 goto error;
9626
9627 case HLUA_E_NOMEM:
9628 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009629 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009630 goto error;
9631
9632 case HLUA_E_YIELD: /* unexpected */
9633 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009634 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009635 goto error;
9636
9637 case HLUA_E_ERR:
9638 /* Display log. */
9639 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009640 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009641 goto error;
9642
9643 default:
9644 goto error;
9645 }
9646 }
9647
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009648 if (http_ctx->flags & APPLET_DONE) {
9649 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009650 goto done;
9651
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009652 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009653 goto error;
9654
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009655 /* no more data are expected. If the response buffer is empty
9656 * for a chunked message, be sure to add something (EOT block in
9657 * this case) to have something to send. It is important to be
9658 * sure the EOM flags will be handled by the endpoint.
9659 */
9660 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9661 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009662 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009663 goto out;
9664 }
9665 channel_add_input(res, 1);
9666 }
9667
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009668 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009669 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009670 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009671 strm->txn->status = http_ctx->status;
9672 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009673 }
9674
9675 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009676 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009677 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009678 res->flags |= CF_READ_NULL;
Willy Tarreau3e7be362022-05-27 10:35:27 +02009679 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009680 }
9681
9682 /* eat the whole request */
9683 if (co_data(req)) {
9684 req_htx = htx_from_buf(&req->buf);
9685 co_htx_skip(req, req_htx, co_data(req));
9686 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009687 }
9688 }
9689
9690 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009691 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009692 return;
9693
9694 error:
9695
9696 /* If we are in HTTP mode, and we are not send any
9697 * data, return a 500 server error in best effort:
9698 * if there is no room available in the buffer,
9699 * just close the connection.
9700 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009701 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009702 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009703
9704 channel_erase(res);
9705 res->buf.data = b_data(err);
9706 memcpy(res->buf.area, b_head(err), b_data(err));
9707 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009708 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009709 }
9710 if (!(strm->flags & SF_ERR_MASK))
9711 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009712 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009713 goto done;
9714}
9715
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009716static void hlua_applet_http_release(struct appctx *ctx)
9717{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009718 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9719
9720 task_destroy(http_ctx->task);
9721 http_ctx->task = NULL;
9722 hlua_ctx_destroy(http_ctx->hlua);
9723 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009724}
9725
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009726/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009727 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009728 *
9729 * This function can fail with an abort() due to an Lua critical error.
9730 * We are in the configuration parsing process of HAProxy, this abort() is
9731 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009732 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009733static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9734 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009735{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009736 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009737 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009738
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009739 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009740 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009741 if (!rule->arg.hlua_rule) {
9742 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009743 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009744 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009745
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009746 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009747 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9748 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009749 if (!rule->arg.hlua_rule->args) {
9750 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009751 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009752 }
9753
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009754 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009755 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009756
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009757 /* Expect some arguments */
9758 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009759 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009760 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009761 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009762 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009763 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009764 if (!rule->arg.hlua_rule->args[i]) {
9765 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009766 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009767 }
9768 (*cur_arg)++;
9769 }
9770 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009771
Thierry FOURNIER42148732015-09-02 17:17:33 +02009772 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009773 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009774 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009775
9776 error:
9777 if (rule->arg.hlua_rule) {
9778 if (rule->arg.hlua_rule->args) {
9779 for (i = 0; i < fcn->nargs; i++)
9780 ha_free(&rule->arg.hlua_rule->args[i]);
9781 ha_free(&rule->arg.hlua_rule->args);
9782 }
9783 ha_free(&rule->arg.hlua_rule);
9784 }
9785 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009786}
9787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009788static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9789 struct act_rule *rule, char **err)
9790{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009791 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009792
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009793 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009794 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009795 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009796 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009797 * the call of this analyzer.
9798 */
9799 if (rule->from != ACT_F_HTTP_REQ) {
9800 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9801 return ACT_RET_PRS_ERR;
9802 }
9803
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009804 /* Memory for the rule. */
9805 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9806 if (!rule->arg.hlua_rule) {
9807 memprintf(err, "out of memory error");
9808 return ACT_RET_PRS_ERR;
9809 }
9810
9811 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009812 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009813
9814 /* TODO: later accept arguments. */
9815 rule->arg.hlua_rule->args = NULL;
9816
9817 /* Add applet pointer in the rule. */
9818 rule->applet.obj_type = OBJ_TYPE_APPLET;
9819 rule->applet.name = fcn->name;
9820 rule->applet.init = hlua_applet_http_init;
9821 rule->applet.fct = hlua_applet_http_fct;
9822 rule->applet.release = hlua_applet_http_release;
9823 rule->applet.timeout = hlua_timeout_applet;
9824
9825 return ACT_RET_PRS_OK;
9826}
9827
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009828/* This function is an LUA binding used for registering
9829 * "sample-conv" functions. It expects a converter name used
9830 * in the haproxy configuration file, and an LUA function.
9831 */
9832__LJMP static int hlua_register_action(lua_State *L)
9833{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009834 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009835 const char *name;
9836 int ref;
9837 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009838 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009839 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009840 struct buffer *trash;
9841 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009842
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009843 /* Initialise the number of expected arguments at 0. */
9844 nargs = 0;
9845
9846 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9847 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009848
9849 /* First argument : converter name. */
9850 name = MAY_LJMP(luaL_checkstring(L, 1));
9851
9852 /* Second argument : environment. */
9853 if (lua_type(L, 2) != LUA_TTABLE)
9854 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9855
9856 /* Third argument : lua function. */
9857 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9858
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009859 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009860 if (lua_gettop(L) >= 4)
9861 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9862
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009863 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009864 lua_pushnil(L);
9865 while (lua_next(L, 2) != 0) {
9866 if (lua_type(L, -1) != LUA_TSTRING)
9867 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9868
Thierry Fournierf67442e2020-11-28 20:41:07 +01009869 /* Check if action exists */
9870 trash = get_trash_chunk();
9871 chunk_printf(trash, "lua.%s", name);
9872 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9873 akw = tcp_req_cont_action(trash->area);
9874 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9875 akw = tcp_res_cont_action(trash->area);
9876 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9877 akw = action_http_req_custom(trash->area);
9878 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9879 akw = action_http_res_custom(trash->area);
9880 } else {
9881 akw = NULL;
9882 }
9883 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009884 fcn = akw->private;
9885 if (fcn->function_ref[hlua_state_id] != -1) {
9886 ha_warning("Trying to register action 'lua.%s' more than once. "
9887 "This will become a hard error in version 2.5.\n", name);
9888 }
9889 fcn->function_ref[hlua_state_id] = ref;
9890
9891 /* pop the environment string. */
9892 lua_pop(L, 1);
9893 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009894 }
9895
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009896 /* Check required environment. Only accepted "http" or "tcp". */
9897 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009898 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009899 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009900 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009901 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009902 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009903 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009904
9905 /* Fill fcn. */
9906 fcn->name = strdup(name);
9907 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009908 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009909 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009910
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009911 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009912 fcn->nargs = nargs;
9913
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009914 /* List head */
9915 akl->list.n = akl->list.p = NULL;
9916
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009917 /* action keyword. */
9918 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009919 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009920 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009921 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009922
9923 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9924
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009925 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009926 akl->kw[0].private = fcn;
9927 akl->kw[0].parse = action_register_lua;
9928
9929 /* select the action registering point. */
9930 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9931 tcp_req_cont_keywords_register(akl);
9932 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9933 tcp_res_cont_keywords_register(akl);
9934 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9935 http_req_keywords_register(akl);
9936 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9937 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009938 else {
9939 release_hlua_function(fcn);
9940 if (akl)
9941 ha_free((char **)&(akl->kw[0].kw));
9942 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009943 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009944 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9945 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009946 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009947
9948 /* pop the environment string. */
9949 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009950
9951 /* reset for next loop */
9952 akl = NULL;
9953 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009954 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009955 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009956
9957 alloc_error:
9958 release_hlua_function(fcn);
9959 ha_free(&akl);
9960 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9961 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009962}
9963
9964static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9965 struct act_rule *rule, char **err)
9966{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009967 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009968
Christopher Faulet280f85b2019-07-15 15:02:04 +02009969 if (px->mode == PR_MODE_HTTP) {
9970 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009971 return ACT_RET_PRS_ERR;
9972 }
9973
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009974 /* Memory for the rule. */
9975 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9976 if (!rule->arg.hlua_rule) {
9977 memprintf(err, "out of memory error");
9978 return ACT_RET_PRS_ERR;
9979 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009980
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009981 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009982 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009983
9984 /* TODO: later accept arguments. */
9985 rule->arg.hlua_rule->args = NULL;
9986
9987 /* Add applet pointer in the rule. */
9988 rule->applet.obj_type = OBJ_TYPE_APPLET;
9989 rule->applet.name = fcn->name;
9990 rule->applet.init = hlua_applet_tcp_init;
9991 rule->applet.fct = hlua_applet_tcp_fct;
9992 rule->applet.release = hlua_applet_tcp_release;
9993 rule->applet.timeout = hlua_timeout_applet;
9994
9995 return 0;
9996}
9997
9998/* This function is an LUA binding used for registering
9999 * "sample-conv" functions. It expects a converter name used
10000 * in the haproxy configuration file, and an LUA function.
10001 */
10002__LJMP static int hlua_register_service(lua_State *L)
10003{
10004 struct action_kw_list *akl;
10005 const char *name;
10006 const char *env;
10007 int ref;
10008 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010009 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010010 struct buffer *trash;
10011 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010012
10013 MAY_LJMP(check_args(L, 3, "register_service"));
10014
10015 /* First argument : converter name. */
10016 name = MAY_LJMP(luaL_checkstring(L, 1));
10017
10018 /* Second argument : environment. */
10019 env = MAY_LJMP(luaL_checkstring(L, 2));
10020
10021 /* Third argument : lua function. */
10022 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10023
Thierry Fournierf67442e2020-11-28 20:41:07 +010010024 /* Check for service already registered */
10025 trash = get_trash_chunk();
10026 chunk_printf(trash, "lua.%s", name);
10027 akw = service_find(trash->area);
10028 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010029 fcn = akw->private;
10030 if (fcn->function_ref[hlua_state_id] != -1) {
10031 ha_warning("Trying to register service 'lua.%s' more than once. "
10032 "This will become a hard error in version 2.5.\n", name);
10033 }
10034 fcn->function_ref[hlua_state_id] = ref;
10035 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010036 }
10037
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010038 /* Allocate and fill the sample fetch keyword struct. */
10039 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10040 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010041 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010042 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010043 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010044 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010045
10046 /* Fill fcn. */
10047 len = strlen("<lua.>") + strlen(name) + 1;
10048 fcn->name = calloc(1, len);
10049 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010050 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010051 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010052 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010053
10054 /* List head */
10055 akl->list.n = akl->list.p = NULL;
10056
10057 /* converter keyword. */
10058 len = strlen("lua.") + strlen(name) + 1;
10059 akl->kw[0].kw = calloc(1, len);
10060 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010061 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010062
10063 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10064
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010065 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010066 if (strcmp(env, "tcp") == 0)
10067 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010068 else if (strcmp(env, "http") == 0)
10069 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010070 else {
10071 release_hlua_function(fcn);
10072 if (akl)
10073 ha_free((char **)&(akl->kw[0].kw));
10074 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010075 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010076 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010077 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010078
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010079 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010080 akl->kw[0].private = fcn;
10081
10082 /* End of array. */
10083 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10084
10085 /* Register this new converter */
10086 service_keywords_register(akl);
10087
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010088 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010089
10090 alloc_error:
10091 release_hlua_function(fcn);
10092 ha_free(&akl);
10093 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10094 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010095}
10096
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010097/* This function initialises Lua cli handler. It copies the
10098 * arguments in the Lua stack and create channel IO objects.
10099 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010100static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010101{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010102 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010103 struct hlua *hlua;
10104 struct hlua_function *fcn;
10105 int i;
10106 const char *error;
10107
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010108 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010109 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010110
Willy Tarreaubafbe012017-11-24 17:34:44 +010010111 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010112 if (!hlua) {
10113 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010114 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010115 }
10116 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010117 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010118
10119 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010120 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010121 * applet_http. It is absolutely compatible.
10122 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010123 ctx->task = task_new_here();
10124 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010125 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010126 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010127 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010128 ctx->task->nice = 0;
10129 ctx->task->context = appctx;
10130 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010131
10132 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010133 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010134 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010135 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010136 }
10137
10138 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010139 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010140 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10141 error = lua_tostring(hlua->T, -1);
10142 else
10143 error = "critical error";
10144 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10145 goto error;
10146 }
10147
10148 /* Check stack available size. */
10149 if (!lua_checkstack(hlua->T, 2)) {
10150 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10151 goto error;
10152 }
10153
10154 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010155 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010156
10157 /* Once the arguments parsed, the CLI is like an AppletTCP,
10158 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010159 */
10160 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10161 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10162 goto error;
10163 }
10164 hlua->nargs = 1;
10165
10166 /* push keywords in the stack. */
10167 for (i = 0; *args[i]; i++) {
10168 /* Check stack available size. */
10169 if (!lua_checkstack(hlua->T, 1)) {
10170 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10171 goto error;
10172 }
10173 lua_pushstring(hlua->T, args[i]);
10174 hlua->nargs++;
10175 }
10176
10177 /* We must initialize the execution timeouts. */
10178 hlua->max_time = hlua_timeout_session;
10179
10180 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010181 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010182
10183 /* It's ok */
10184 return 0;
10185
10186 /* It's not ok. */
10187error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010188 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010189 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010190 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010191 return 1;
10192}
10193
10194static int hlua_cli_io_handler_fct(struct appctx *appctx)
10195{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010196 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010197 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010198 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010199 struct hlua_function *fcn;
10200
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010201 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010202 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010203 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010204
10205 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010206 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010207 return 1;
10208
10209 /* Execute the function. */
10210 switch (hlua_ctx_resume(hlua, 1)) {
10211
10212 /* finished. */
10213 case HLUA_E_OK:
10214 return 1;
10215
10216 /* yield. */
10217 case HLUA_E_AGAIN:
10218 /* We want write. */
10219 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010220 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010221 /* Set the timeout. */
10222 if (hlua->wake_time != TICK_ETERNITY)
10223 task_schedule(hlua->task, hlua->wake_time);
10224 return 0;
10225
10226 /* finished with error. */
10227 case HLUA_E_ERRMSG:
10228 /* Display log. */
10229 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10230 fcn->name, lua_tostring(hlua->T, -1));
10231 lua_pop(hlua->T, 1);
10232 return 1;
10233
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010234 case HLUA_E_ETMOUT:
10235 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10236 fcn->name);
10237 return 1;
10238
10239 case HLUA_E_NOMEM:
10240 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10241 fcn->name);
10242 return 1;
10243
10244 case HLUA_E_YIELD: /* unexpected */
10245 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10246 fcn->name);
10247 return 1;
10248
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010249 case HLUA_E_ERR:
10250 /* Display log. */
10251 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10252 fcn->name);
10253 return 1;
10254
10255 default:
10256 return 1;
10257 }
10258
10259 return 1;
10260}
10261
10262static void hlua_cli_io_release_fct(struct appctx *appctx)
10263{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010264 struct hlua_cli_ctx *ctx = appctx->svcctx;
10265
10266 hlua_ctx_destroy(ctx->hlua);
10267 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010268}
10269
10270/* This function is an LUA binding used for registering
10271 * new keywords in the cli. It expects a list of keywords
10272 * which are the "path". It is limited to 5 keywords. A
10273 * description of the command, a function to be executed
10274 * for the parsing and a function for io handlers.
10275 */
10276__LJMP static int hlua_register_cli(lua_State *L)
10277{
10278 struct cli_kw_list *cli_kws;
10279 const char *message;
10280 int ref_io;
10281 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010282 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010283 int index;
10284 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010285 struct buffer *trash;
10286 const char *kw[5];
10287 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010288 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010289
10290 MAY_LJMP(check_args(L, 3, "register_cli"));
10291
10292 /* First argument : an array of maximum 5 keywords. */
10293 if (!lua_istable(L, 1))
10294 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10295
10296 /* Second argument : string with contextual message. */
10297 message = MAY_LJMP(luaL_checkstring(L, 2));
10298
10299 /* Third and fourth argument : lua function. */
10300 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10301
Thierry Fournierf67442e2020-11-28 20:41:07 +010010302 /* Check for CLI service already registered */
10303 trash = get_trash_chunk();
10304 index = 0;
10305 lua_pushnil(L);
10306 memset(kw, 0, sizeof(kw));
10307 while (lua_next(L, 1) != 0) {
10308 if (index >= CLI_PREFIX_KW_NB)
10309 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10310 if (lua_type(L, -1) != LUA_TSTRING)
10311 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10312 kw[index] = lua_tostring(L, -1);
10313 if (index == 0)
10314 chunk_printf(trash, "%s", kw[index]);
10315 else
10316 chunk_appendf(trash, " %s", kw[index]);
10317 index++;
10318 lua_pop(L, 1);
10319 }
10320 cli_kw = cli_find_kw_exact((char **)kw);
10321 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010322 fcn = cli_kw->private;
10323 if (fcn->function_ref[hlua_state_id] != -1) {
10324 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10325 "This will become a hard error in version 2.5.\n", trash->area);
10326 }
10327 fcn->function_ref[hlua_state_id] = ref_io;
10328 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010329 }
10330
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010331 /* Allocate and fill the sample fetch keyword struct. */
10332 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010333 if (!cli_kws) {
10334 errmsg = "Lua out of memory error.";
10335 goto error;
10336 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010337 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010338 if (!fcn) {
10339 errmsg = "Lua out of memory error.";
10340 goto error;
10341 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010342
10343 /* Fill path. */
10344 index = 0;
10345 lua_pushnil(L);
10346 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010347 if (index >= 5) {
10348 errmsg = "1st argument must be a table with a maximum of 5 entries";
10349 goto error;
10350 }
10351 if (lua_type(L, -1) != LUA_TSTRING) {
10352 errmsg = "1st argument must be a table filled with strings";
10353 goto error;
10354 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010355 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010356 if (!cli_kws->kw[0].str_kw[index]) {
10357 errmsg = "Lua out of memory error.";
10358 goto error;
10359 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010360 index++;
10361 lua_pop(L, 1);
10362 }
10363
10364 /* Copy help message. */
10365 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010366 if (!cli_kws->kw[0].usage) {
10367 errmsg = "Lua out of memory error.";
10368 goto error;
10369 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010370
10371 /* Fill fcn io handler. */
10372 len = strlen("<lua.cli>") + 1;
10373 for (i = 0; i < index; i++)
10374 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10375 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010376 if (!fcn->name) {
10377 errmsg = "Lua out of memory error.";
10378 goto error;
10379 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010380 strncat((char *)fcn->name, "<lua.cli", len);
10381 for (i = 0; i < index; i++) {
10382 strncat((char *)fcn->name, ".", len);
10383 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10384 }
10385 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010386 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010387
10388 /* Fill last entries. */
10389 cli_kws->kw[0].private = fcn;
10390 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10391 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10392 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10393
10394 /* Register this new converter */
10395 cli_register_kw(cli_kws);
10396
10397 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010398
10399 error:
10400 release_hlua_function(fcn);
10401 if (cli_kws) {
10402 for (i = 0; i < index; i++)
10403 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10404 ha_free((char **)&(cli_kws->kw[0].usage));
10405 }
10406 ha_free(&cli_kws);
10407 WILL_LJMP(luaL_error(L, errmsg));
10408 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010409}
10410
Christopher Faulet69c581a2021-05-31 08:54:04 +020010411static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10412{
10413 struct hlua_flt_config *conf = fconf->conf;
10414 lua_State *L;
10415 int error, pos, state_id, flt_ref;
10416
10417 state_id = reg_flt_to_stack_id(conf->reg);
10418 L = hlua_states[state_id];
10419 pos = lua_gettop(L);
10420
10421 /* The filter parsing function */
10422 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10423
10424 /* Push the filter class on the stack and resolve all callbacks */
10425 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10426
10427 /* Duplicate the filter class so each filter will have its own copy */
10428 lua_newtable(L);
10429 lua_pushnil(L);
10430
10431 while (lua_next(L, pos+2)) {
10432 lua_pushvalue(L, -2);
10433 lua_insert(L, -2);
10434 lua_settable(L, -4);
10435 }
10436 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10437
10438 /* Remove the original lua filter class from the stack */
10439 lua_pop(L, 1);
10440
10441 /* Push the copy on the stack */
10442 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10443
10444 /* extra args are pushed in a table */
10445 lua_newtable(L);
10446 for (pos = 0; conf->args[pos]; pos++) {
10447 /* Check stack available size. */
10448 if (!lua_checkstack(L, 1)) {
10449 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10450 goto error;
10451 }
10452 lua_pushstring(L, conf->args[pos]);
10453 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10454 }
10455
10456 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10457 switch (error) {
10458 case LUA_OK:
10459 /* replace the filter ref */
10460 conf->ref[state_id] = flt_ref;
10461 break;
10462 case LUA_ERRRUN:
10463 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10464 goto error;
10465 case LUA_ERRMEM:
10466 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10467 goto error;
10468 case LUA_ERRERR:
10469 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10470 goto error;
10471#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10472 case LUA_ERRGCMM:
10473 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10474 goto error;
10475#endif
10476 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010477 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010478 goto error;
10479 }
10480
10481 lua_settop(L, 0);
10482 return 0;
10483
10484 error:
10485 lua_settop(L, 0);
10486 return -1;
10487}
10488
10489static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10490{
10491 struct hlua_flt_config *conf = fconf->conf;
10492 lua_State *L;
10493 int state_id;
10494
10495 if (!conf)
10496 return;
10497
10498 state_id = reg_flt_to_stack_id(conf->reg);
10499 L = hlua_states[state_id];
10500 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10501}
10502
10503static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10504{
10505 struct hlua_flt_config *conf = fconf->conf;
10506 int state_id = reg_flt_to_stack_id(conf->reg);
10507
10508 /* Rely on per-thread init for global scripts */
10509 if (!state_id)
10510 return hlua_filter_init_per_thread(px, fconf);
10511 return 0;
10512}
10513
10514static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10515{
10516
10517 if (fconf->conf) {
10518 struct hlua_flt_config *conf = fconf->conf;
10519 int state_id = reg_flt_to_stack_id(conf->reg);
10520 int pos;
10521
10522 /* Rely on per-thread deinit for global scripts */
10523 if (!state_id)
10524 hlua_filter_deinit_per_thread(px, fconf);
10525
10526 for (pos = 0; conf->args[pos]; pos++)
10527 free(conf->args[pos]);
10528 free(conf->args);
10529 }
10530 ha_free(&fconf->conf);
10531 ha_free((char **)&fconf->id);
10532 ha_free(&fconf->ops);
10533}
10534
10535static int hlua_filter_new(struct stream *s, struct filter *filter)
10536{
10537 struct hlua_flt_config *conf = FLT_CONF(filter);
10538 struct hlua_flt_ctx *flt_ctx = NULL;
10539 int ret = 1;
10540
10541 /* In the execution wrappers linked with a stream, the
10542 * Lua context can be not initialized. This behavior
10543 * permits to save performances because a systematic
10544 * Lua initialization cause 5% performances loss.
10545 */
10546 if (!s->hlua) {
10547 struct hlua *hlua;
10548
10549 hlua = pool_alloc(pool_head_hlua);
10550 if (!hlua) {
10551 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10552 conf->reg->name);
10553 ret = 0;
10554 goto end;
10555 }
10556 HLUA_INIT(hlua);
10557 s->hlua = hlua;
10558 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10559 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10560 conf->reg->name);
10561 ret = 0;
10562 goto end;
10563 }
10564 }
10565
10566 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10567 if (!flt_ctx) {
10568 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10569 conf->reg->name);
10570 ret = 0;
10571 goto end;
10572 }
10573 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10574 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10575 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10576 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10577 conf->reg->name);
10578 ret = 0;
10579 goto end;
10580 }
10581 HLUA_INIT(flt_ctx->hlua[0]);
10582 HLUA_INIT(flt_ctx->hlua[1]);
10583 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10584 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10585 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10586 conf->reg->name);
10587 ret = 0;
10588 goto end;
10589 }
10590
10591 if (!HLUA_IS_RUNNING(s->hlua)) {
10592 /* The following Lua calls can fail. */
10593 if (!SET_SAFE_LJMP(s->hlua)) {
10594 const char *error;
10595
10596 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10597 error = lua_tostring(s->hlua->T, -1);
10598 else
10599 error = "critical error";
10600 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10601 ret = 0;
10602 goto end;
10603 }
10604
10605 /* Check stack size. */
10606 if (!lua_checkstack(s->hlua->T, 1)) {
10607 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010608 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010609 ret = 0;
10610 goto end;
10611 }
10612
10613 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10614 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10615 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10616 conf->reg->name);
10617 RESET_SAFE_LJMP(s->hlua);
10618 ret = 0;
10619 goto end;
10620 }
10621 lua_insert(s->hlua->T, -2);
10622
10623 /* Push the copy on the stack */
10624 s->hlua->nargs = 1;
10625
10626 /* We must initialize the execution timeouts. */
10627 s->hlua->max_time = hlua_timeout_session;
10628
10629 /* At this point the execution is safe. */
10630 RESET_SAFE_LJMP(s->hlua);
10631 }
10632
10633 switch (hlua_ctx_resume(s->hlua, 0)) {
10634 case HLUA_E_OK:
10635 /* Nothing returned or not a table, ignore the filter for current stream */
10636 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10637 ret = 0;
10638 goto end;
10639 }
10640
10641 /* Attached the filter pointer to the ctx */
10642 lua_pushstring(s->hlua->T, "__filter");
10643 lua_pushlightuserdata(s->hlua->T, filter);
10644 lua_settable(s->hlua->T, -3);
10645
10646 /* Save a ref on the filter ctx */
10647 lua_pushvalue(s->hlua->T, 1);
10648 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10649 filter->ctx = flt_ctx;
10650 break;
10651 case HLUA_E_ERRMSG:
10652 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10653 ret = -1;
10654 goto end;
10655 case HLUA_E_ETMOUT:
10656 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10657 ret = 0;
10658 goto end;
10659 case HLUA_E_NOMEM:
10660 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10661 ret = 0;
10662 goto end;
10663 case HLUA_E_AGAIN:
10664 case HLUA_E_YIELD:
10665 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10666 " are not allowed from 'new' function.\n", conf->reg->name);
10667 ret = 0;
10668 goto end;
10669 case HLUA_E_ERR:
10670 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10671 ret = 0;
10672 goto end;
10673 default:
10674 ret = 0;
10675 goto end;
10676 }
10677
10678 end:
10679 if (s->hlua)
10680 lua_settop(s->hlua->T, 0);
10681 if (ret <= 0) {
10682 if (flt_ctx) {
10683 hlua_ctx_destroy(flt_ctx->hlua[0]);
10684 hlua_ctx_destroy(flt_ctx->hlua[1]);
10685 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10686 }
10687 }
10688 return ret;
10689}
10690
10691static void hlua_filter_delete(struct stream *s, struct filter *filter)
10692{
10693 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10694
10695 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10696 hlua_ctx_destroy(flt_ctx->hlua[0]);
10697 hlua_ctx_destroy(flt_ctx->hlua[1]);
10698 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10699 filter->ctx = NULL;
10700}
10701
Christopher Faulet9f55a502020-02-25 15:21:02 +010010702static int hlua_filter_from_payload(struct filter *filter)
10703{
10704 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10705
10706 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10707}
10708
Christopher Fauletc404f112020-02-26 15:03:09 +010010709static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10710 int dir, unsigned int flags)
10711{
10712 struct hlua *flt_hlua;
10713 struct hlua_flt_config *conf = FLT_CONF(filter);
10714 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10715 unsigned int hflags = HLUA_TXN_FLT_CTX;
10716 int ret = 1;
10717
10718 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10719 if (!flt_hlua)
10720 goto end;
10721
10722 if (!HLUA_IS_RUNNING(flt_hlua)) {
10723 int extra_idx = lua_gettop(flt_hlua->T);
10724
10725 /* The following Lua calls can fail. */
10726 if (!SET_SAFE_LJMP(flt_hlua)) {
10727 const char *error;
10728
10729 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10730 error = lua_tostring(flt_hlua->T, -1);
10731 else
10732 error = "critical error";
10733 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10734 goto end;
10735 }
10736
10737 /* Check stack size. */
10738 if (!lua_checkstack(flt_hlua->T, 3)) {
10739 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10740 RESET_SAFE_LJMP(flt_hlua);
10741 goto end;
10742 }
10743
10744 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10745 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10746 RESET_SAFE_LJMP(flt_hlua);
10747 goto end;
10748 }
10749 lua_insert(flt_hlua->T, -2);
10750
10751 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10752 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10753 RESET_SAFE_LJMP(flt_hlua);
10754 goto end;
10755 }
10756 flt_hlua->nargs = 2;
10757
10758 if (flags & HLUA_FLT_CB_ARG_CHN) {
10759 if (dir == SMP_OPT_DIR_REQ)
10760 lua_getfield(flt_hlua->T, -1, "req");
10761 else
10762 lua_getfield(flt_hlua->T, -1, "res");
10763 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10764 lua_pushstring(flt_hlua->T, "__filter");
10765 lua_pushlightuserdata(flt_hlua->T, filter);
10766 lua_settable(flt_hlua->T, -3);
10767 }
10768 flt_hlua->nargs++;
10769 }
10770 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010771 if (dir == SMP_OPT_DIR_REQ)
10772 lua_getfield(flt_hlua->T, -1, "http_req");
10773 else
10774 lua_getfield(flt_hlua->T, -1, "http_res");
10775 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10776 lua_pushstring(flt_hlua->T, "__filter");
10777 lua_pushlightuserdata(flt_hlua->T, filter);
10778 lua_settable(flt_hlua->T, -3);
10779 }
10780 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010781 }
10782
10783 /* Check stack size. */
10784 if (!lua_checkstack(flt_hlua->T, 1)) {
10785 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10786 RESET_SAFE_LJMP(flt_hlua);
10787 goto end;
10788 }
10789
10790 while (extra_idx--) {
10791 lua_pushvalue(flt_hlua->T, 1);
10792 lua_remove(flt_hlua->T, 1);
10793 flt_hlua->nargs++;
10794 }
10795
10796 /* We must initialize the execution timeouts. */
10797 flt_hlua->max_time = hlua_timeout_session;
10798
10799 /* At this point the execution is safe. */
10800 RESET_SAFE_LJMP(flt_hlua);
10801 }
10802
10803 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10804 case HLUA_E_OK:
10805 /* Catch the return value if it required */
10806 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10807 ret = lua_tointeger(flt_hlua->T, -1);
10808 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10809 }
10810
10811 /* Set timeout in the required channel. */
10812 if (flt_hlua->wake_time != TICK_ETERNITY) {
10813 if (dir == SMP_OPT_DIR_REQ)
10814 s->req.analyse_exp = flt_hlua->wake_time;
10815 else
10816 s->res.analyse_exp = flt_hlua->wake_time;
10817 }
10818 break;
10819 case HLUA_E_AGAIN:
10820 /* Set timeout in the required channel. */
10821 if (flt_hlua->wake_time != TICK_ETERNITY) {
10822 if (dir == SMP_OPT_DIR_REQ)
10823 s->req.analyse_exp = flt_hlua->wake_time;
10824 else
10825 s->res.analyse_exp = flt_hlua->wake_time;
10826 }
10827 /* Some actions can be wake up when a "write" event
10828 * is detected on a response channel. This is useful
10829 * only for actions targeted on the requests.
10830 */
10831 if (HLUA_IS_WAKERESWR(flt_hlua))
10832 s->res.flags |= CF_WAKE_WRITE;
10833 if (HLUA_IS_WAKEREQWR(flt_hlua))
10834 s->req.flags |= CF_WAKE_WRITE;
10835 ret = 0;
10836 goto end;
10837 case HLUA_E_ERRMSG:
10838 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10839 ret = -1;
10840 goto end;
10841 case HLUA_E_ETMOUT:
10842 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10843 goto end;
10844 case HLUA_E_NOMEM:
10845 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10846 goto end;
10847 case HLUA_E_YIELD:
10848 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10849 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10850 goto end;
10851 case HLUA_E_ERR:
10852 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10853 goto end;
10854 default:
10855 goto end;
10856 }
10857
10858
10859 end:
10860 return ret;
10861}
10862
10863static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10864{
10865 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10866
10867 flt_ctx->flags = 0;
10868 return hlua_filter_callback(s, filter, "start_analyze",
10869 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10870 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10871}
10872
10873static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10874{
10875 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10876
10877 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10878 return hlua_filter_callback(s, filter, "end_analyze",
10879 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10880 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10881}
10882
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010883static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10884{
10885 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10886
10887 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10888 return hlua_filter_callback(s, filter, "http_headers",
10889 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10890 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10891}
10892
10893static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10894 unsigned int offset, unsigned int len)
10895{
10896 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10897 struct hlua *flt_hlua;
10898 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10899 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10900 int ret;
10901
10902 flt_hlua = flt_ctx->hlua[idx];
10903 flt_ctx->cur_off[idx] = offset;
10904 flt_ctx->cur_len[idx] = len;
10905 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10906 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10907 if (ret != -1) {
10908 ret = flt_ctx->cur_len[idx];
10909 if (lua_gettop(flt_hlua->T) > 0) {
10910 ret = lua_tointeger(flt_hlua->T, -1);
10911 if (ret > flt_ctx->cur_len[idx])
10912 ret = flt_ctx->cur_len[idx];
10913 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10914 }
10915 }
10916 return ret;
10917}
10918
10919static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10920{
10921 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10922
10923 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10924 return hlua_filter_callback(s, filter, "http_end",
10925 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10926 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10927}
10928
Christopher Fauletc404f112020-02-26 15:03:09 +010010929static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10930 unsigned int offset, unsigned int len)
10931{
10932 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10933 struct hlua *flt_hlua;
10934 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10935 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10936 int ret;
10937
10938 flt_hlua = flt_ctx->hlua[idx];
10939 flt_ctx->cur_off[idx] = offset;
10940 flt_ctx->cur_len[idx] = len;
10941 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10942 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10943 if (ret != -1) {
10944 ret = flt_ctx->cur_len[idx];
10945 if (lua_gettop(flt_hlua->T) > 0) {
10946 ret = lua_tointeger(flt_hlua->T, -1);
10947 if (ret > flt_ctx->cur_len[idx])
10948 ret = flt_ctx->cur_len[idx];
10949 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10950 }
10951 }
10952 return ret;
10953}
10954
Christopher Faulet69c581a2021-05-31 08:54:04 +020010955static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10956 struct flt_conf *fconf, char **err, void *private)
10957{
10958 struct hlua_reg_filter *reg_flt = private;
10959 lua_State *L;
10960 struct hlua_flt_config *conf = NULL;
10961 const char *flt_id = NULL;
10962 int state_id, pos, flt_flags = 0;
10963 struct flt_ops *hlua_flt_ops = NULL;
10964
10965 state_id = reg_flt_to_stack_id(reg_flt);
10966 L = hlua_states[state_id];
10967
10968 /* Initialize the filter ops with default callbacks */
10969 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010970 if (!hlua_flt_ops)
10971 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010972 hlua_flt_ops->init = hlua_filter_init;
10973 hlua_flt_ops->deinit = hlua_filter_deinit;
10974 if (state_id) {
10975 /* Set per-thread callback if script is loaded per-thread */
10976 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10977 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10978 }
10979 hlua_flt_ops->attach = hlua_filter_new;
10980 hlua_flt_ops->detach = hlua_filter_delete;
10981
10982 /* Push the filter class on the stack and resolve all callbacks */
10983 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10984
Christopher Fauletc404f112020-02-26 15:03:09 +010010985 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10986 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10987 lua_pop(L, 1);
10988 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10989 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10990 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010991 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10992 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10993 lua_pop(L, 1);
10994 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10995 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10996 lua_pop(L, 1);
10997 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10998 hlua_flt_ops->http_end = hlua_filter_http_end;
10999 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011000 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11001 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11002 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011003
11004 /* Get id and flags of the filter class */
11005 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11006 flt_id = lua_tostring(L, -1);
11007 lua_pop(L, 1);
11008 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11009 flt_flags = lua_tointeger(L, -1);
11010 lua_pop(L, 1);
11011
11012 /* Create the filter config */
11013 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011014 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011015 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011016 conf->reg = reg_flt;
11017
11018 /* duplicate args */
11019 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11020 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011021 if (!conf->args)
11022 goto error;
11023 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011024 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011025 if (!conf->args[pos])
11026 goto error;
11027 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011028 conf->args[pos] = NULL;
11029 *cur_arg += pos + 1;
11030
Christopher Fauletc86bb872021-08-13 08:33:57 +020011031 if (flt_id) {
11032 fconf->id = strdup(flt_id);
11033 if (!fconf->id)
11034 goto error;
11035 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011036 fconf->flags = flt_flags;
11037 fconf->conf = conf;
11038 fconf->ops = hlua_flt_ops;
11039
11040 lua_settop(L, 0);
11041 return 0;
11042
11043 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011044 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011045 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011046 if (conf && conf->args) {
11047 for (pos = 0; conf->args[pos]; pos++)
11048 free(conf->args[pos]);
11049 free(conf->args);
11050 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011051 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011052 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011053 lua_settop(L, 0);
11054 return -1;
11055}
11056
Christopher Fauletc404f112020-02-26 15:03:09 +010011057__LJMP static int hlua_register_data_filter(lua_State *L)
11058{
11059 struct filter *filter;
11060 struct channel *chn;
11061
11062 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11063 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11064 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11065
11066 lua_getfield(L, 1, "__filter");
11067 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11068 filter = lua_touserdata (L, -1);
11069 lua_pop(L, 1);
11070
11071 register_data_filter(chn_strm(chn), chn, filter);
11072 return 1;
11073}
11074
11075__LJMP static int hlua_unregister_data_filter(lua_State *L)
11076{
11077 struct filter *filter;
11078 struct channel *chn;
11079
11080 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11081 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11082 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11083
11084 lua_getfield(L, 1, "__filter");
11085 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11086 filter = lua_touserdata (L, -1);
11087 lua_pop(L, 1);
11088
11089 unregister_data_filter(chn_strm(chn), chn, filter);
11090 return 1;
11091}
11092
Christopher Faulet69c581a2021-05-31 08:54:04 +020011093/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011094 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011095 * parse configuration arguments.
11096 */
11097__LJMP static int hlua_register_filter(lua_State *L)
11098{
11099 struct buffer *trash;
11100 struct flt_kw_list *fkl;
11101 struct flt_kw *fkw;
11102 const char *name;
11103 struct hlua_reg_filter *reg_flt= NULL;
11104 int flt_ref, fun_ref;
11105 int len;
11106
11107 MAY_LJMP(check_args(L, 3, "register_filter"));
11108
11109 /* First argument : filter name. */
11110 name = MAY_LJMP(luaL_checkstring(L, 1));
11111
11112 /* Second argument : The filter class */
11113 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11114
11115 /* Third argument : lua function. */
11116 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11117
11118 trash = get_trash_chunk();
11119 chunk_printf(trash, "lua.%s", name);
11120 fkw = flt_find_kw(trash->area);
11121 if (fkw != NULL) {
11122 reg_flt = fkw->private;
11123 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11124 ha_warning("Trying to register filter 'lua.%s' more than once. "
11125 "This will become a hard error in version 2.5.\n", name);
11126 }
11127 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11128 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11129 return 0;
11130 }
11131
11132 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11133 if (!fkl)
11134 goto alloc_error;
11135 fkl->scope = "HLUA";
11136
11137 reg_flt = new_hlua_reg_filter(name);
11138 if (!reg_flt)
11139 goto alloc_error;
11140
11141 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11142 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11143
11144 /* The filter keyword */
11145 len = strlen("lua.") + strlen(name) + 1;
11146 fkl->kw[0].kw = calloc(1, len);
11147 if (!fkl->kw[0].kw)
11148 goto alloc_error;
11149
11150 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11151
11152 fkl->kw[0].parse = hlua_filter_parse_fct;
11153 fkl->kw[0].private = reg_flt;
11154 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11155
11156 /* Register this new filter */
11157 flt_register_keywords(fkl);
11158
11159 return 0;
11160
11161 alloc_error:
11162 release_hlua_reg_filter(reg_flt);
11163 ha_free(&fkl);
11164 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11165 return 0; /* Never reached */
11166}
11167
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011168static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011169 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011170 char **err, unsigned int *timeout)
11171{
11172 const char *error;
11173
11174 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011175 if (error == PARSE_TIME_OVER) {
11176 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11177 args[1], args[0]);
11178 return -1;
11179 }
11180 else if (error == PARSE_TIME_UNDER) {
11181 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11182 args[1], args[0]);
11183 return -1;
11184 }
11185 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011186 memprintf(err, "%s: invalid timeout", args[0]);
11187 return -1;
11188 }
11189 return 0;
11190}
11191
11192static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011193 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011194 char **err)
11195{
11196 return hlua_read_timeout(args, section_type, curpx, defpx,
11197 file, line, err, &hlua_timeout_session);
11198}
11199
11200static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011201 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011202 char **err)
11203{
11204 return hlua_read_timeout(args, section_type, curpx, defpx,
11205 file, line, err, &hlua_timeout_task);
11206}
11207
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011208static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011209 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011210 char **err)
11211{
11212 return hlua_read_timeout(args, section_type, curpx, defpx,
11213 file, line, err, &hlua_timeout_applet);
11214}
11215
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011216static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011217 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011218 char **err)
11219{
11220 char *error;
11221
11222 hlua_nb_instruction = strtoll(args[1], &error, 10);
11223 if (*error != '\0') {
11224 memprintf(err, "%s: invalid number", args[0]);
11225 return -1;
11226 }
11227 return 0;
11228}
11229
Willy Tarreau32f61e22015-03-18 17:54:59 +010011230static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011231 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011232 char **err)
11233{
11234 char *error;
11235
11236 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011237 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011238 return -1;
11239 }
11240 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11241 if (*error != '\0') {
11242 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11243 return -1;
11244 }
11245 return 0;
11246}
11247
11248
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011249/* This function is called by the main configuration key "lua-load". It loads and
11250 * execute an lua file during the parsing of the HAProxy configuration file. It is
11251 * the main lua entry point.
11252 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011253 * This function runs with the HAProxy keywords API. It returns -1 if an error
11254 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011255 *
11256 * In some error case, LUA set an error message in top of the stack. This function
11257 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011258 *
11259 * This function can fail with an abort() due to an Lua critical error.
11260 * We are in the configuration parsing process of HAProxy, this abort() is
11261 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011262 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011263static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011264{
11265 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011266 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011267
11268 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011269 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011270 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011271 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011272 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011273 return -1;
11274 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011275
11276 /* Push args in the Lua stack, except the first one which is the filename */
11277 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011278 /* Check stack size. */
11279 if (!lua_checkstack(L, 1)) {
11280 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11281 return -1;
11282 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011283 lua_pushstring(L, args[nargs]);
11284 }
11285 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011286
11287 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011288 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011289 switch (error) {
11290 case LUA_OK:
11291 break;
11292 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011293 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011294 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011295 return -1;
11296 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011297 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011298 return -1;
11299 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011300 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011301 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011302 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011303#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011304 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011305 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011306 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011307 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011308#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011309 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011310 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011311 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011312 return -1;
11313 }
11314
11315 return 0;
11316}
11317
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011318static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011319 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011320 char **err)
11321{
11322 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011323 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011324 return -1;
11325 }
11326
Thierry Fournier59f11be2020-11-29 00:37:41 +010011327 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011328 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011329 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011330 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011331}
11332
Thierry Fournier59f11be2020-11-29 00:37:41 +010011333static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011334 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011335 char **err)
11336{
11337 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011338 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011339
11340 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011341 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011342 return -1;
11343 }
11344
11345 if (per_thread_load == NULL) {
11346 /* allocate the first entry large enough to store the final NULL */
11347 per_thread_load = calloc(1, sizeof(*per_thread_load));
11348 if (per_thread_load == NULL) {
11349 memprintf(err, "out of memory error");
11350 return -1;
11351 }
11352 }
11353
11354 /* count used entries */
11355 for (len = 0; per_thread_load[len] != NULL; len++)
11356 ;
11357
11358 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11359 if (per_thread_load == NULL) {
11360 memprintf(err, "out of memory error");
11361 return -1;
11362 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011363 per_thread_load[len + 1] = NULL;
11364
Thierry Fournierae6b5682022-09-19 09:04:16 +020011365 /* count args excepting the first, allocate array and copy args */
11366 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011367 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011368 if (per_thread_load[len] == NULL) {
11369 memprintf(err, "out of memory error");
11370 return -1;
11371 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011372 for (i = 1; *(args[i]) != 0; i++) {
11373 per_thread_load[len][i - 1] = strdup(args[i]);
11374 if (per_thread_load[len][i - 1] == NULL) {
11375 memprintf(err, "out of memory error");
11376 return -1;
11377 }
11378 }
11379 per_thread_load[len][i - 1] = strdup("");
11380 if (per_thread_load[len][i - 1] == NULL) {
11381 memprintf(err, "out of memory error");
11382 return -1;
11383 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011384
11385 /* loading for thread 1 only */
11386 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011387 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011388 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011389}
11390
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011391/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11392 * in the given <ctx>.
11393 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011394static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011395{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011396 lua_getglobal(L, "package"); /* push package variable */
11397 lua_pushstring(L, path); /* push given path */
11398 lua_pushstring(L, ";"); /* push semicolon */
11399 lua_getfield(L, -3, type); /* push old path */
11400 lua_concat(L, 3); /* concatenate to new path */
11401 lua_setfield(L, -2, type); /* store new path */
11402 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011403
11404 return 0;
11405}
11406
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011407static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011408 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011409 char **err)
11410{
11411 char *path;
11412 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011413 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011414 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011415
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011416 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011417 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011418 }
11419
11420 if (!(*args[1])) {
11421 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011422 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011423 }
11424 path = args[1];
11425
11426 if (*args[2]) {
11427 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11428 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011429 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011430 }
11431 type = args[2];
11432 }
11433
Thierry Fournier59f11be2020-11-29 00:37:41 +010011434 p = calloc(1, sizeof(*p));
11435 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011436 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011437 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011438 }
11439 p->path = strdup(path);
11440 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011441 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011442 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011443 }
11444 p->type = strdup(type);
11445 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011446 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011447 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011448 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011449 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011450
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011451 /* Handle the global state and the per-thread state for the first
11452 * thread. The remaining threads will be initialized based on
11453 * prepend_path_list.
11454 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011455 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011456 lua_State *L = hlua_states[i];
11457 const char *error;
11458
11459 if (setjmp(safe_ljmp_env) != 0) {
11460 lua_atpanic(L, hlua_panic_safe);
11461 if (lua_type(L, -1) == LUA_TSTRING)
11462 error = lua_tostring(L, -1);
11463 else
11464 error = "critical error";
11465 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11466 exit(1);
11467 } else {
11468 lua_atpanic(L, hlua_panic_ljmp);
11469 }
11470
11471 hlua_prepend_path(L, type, path);
11472
11473 lua_atpanic(L, hlua_panic_safe);
11474 }
11475
Thierry Fournier59f11be2020-11-29 00:37:41 +010011476 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011477
11478err2:
11479 free(p->type);
11480 free(p->path);
11481err:
11482 free(p);
11483 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011484}
11485
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011486/* configuration keywords declaration */
11487static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011488 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011489 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011490 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011491 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11492 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011493 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011494 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011495 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011496 { 0, NULL, NULL },
11497}};
11498
Willy Tarreau0108d902018-11-25 19:14:37 +010011499INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11500
William Lallemand52139182022-03-30 15:05:42 +020011501#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011502
William Lallemand30fcca12022-03-30 12:03:12 +020011503/*
11504 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11505 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11506 * difference is that the yield in lua and for the CLI is not handled the same
11507 * way.
11508 */
11509__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11510{
11511 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11512 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11513 struct ckch_inst *ckchi = *lua_ckchi;
11514 struct ckch_store *old_ckchs = lua_ckchs[0];
11515 struct ckch_store *new_ckchs = lua_ckchs[1];
11516 struct hlua *hlua;
11517 char *err = NULL;
11518 int y = 1;
11519
11520 hlua = hlua_gethlua(L);
11521
11522 /* get the first ckchi to copy */
11523 if (ckchi == NULL)
11524 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11525
11526 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11527 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11528 struct ckch_inst *new_inst;
11529
11530 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11531 if (y % 10 == 0) {
11532
11533 *lua_ckchi = ckchi;
11534
11535 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11536 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11537 }
11538
11539 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11540 goto error;
11541
11542 /* link the new ckch_inst to the duplicate */
11543 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11544 y++;
11545 }
11546
11547 /* The generation is finished, we can insert everything */
11548 ckch_store_replace(old_ckchs, new_ckchs);
11549
11550 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11551
11552 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11553
11554 return 0;
11555
11556error:
11557 ckch_store_free(new_ckchs);
11558 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11559 WILL_LJMP(luaL_error(L, "%s", err));
11560 free(err);
11561
11562 return 0;
11563}
11564
11565/*
11566 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11567 * from the table in parameter.
11568 *
11569 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11570 * means it does not need to have a transaction since everything is done in the
11571 * same function.
11572 *
11573 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11574 *
11575 */
11576__LJMP static int hlua_ckch_set(lua_State *L)
11577{
11578 struct hlua *hlua;
11579 struct ckch_inst **lua_ckchi;
11580 struct ckch_store **lua_ckchs;
11581 struct ckch_store *old_ckchs = NULL;
11582 struct ckch_store *new_ckchs = NULL;
11583 int errcode = 0;
11584 char *err = NULL;
11585 struct cert_exts *cert_ext = NULL;
11586 char *filename;
11587 struct cert_key_and_chain *ckch;
11588 int ret;
11589
11590 if (lua_type(L, -1) != LUA_TTABLE)
11591 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11592
11593 hlua = hlua_gethlua(L);
11594
11595 /* FIXME: this should not return an error but should come back later */
11596 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11597 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11598
11599 ret = lua_getfield(L, -1, "filename");
11600 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011601 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011602 errcode |= ERR_ALERT | ERR_FATAL;
11603 goto end;
11604 }
11605 filename = (char *)lua_tostring(L, -1);
11606
11607
11608 /* look for the filename in the tree */
11609 old_ckchs = ckchs_lookup(filename);
11610 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011611 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011612 errcode |= ERR_ALERT | ERR_FATAL;
11613 goto end;
11614 }
11615 /* TODO: handle extra_files_noext */
11616
11617 new_ckchs = ckchs_dup(old_ckchs);
11618 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011619 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011620 errcode |= ERR_ALERT | ERR_FATAL;
11621 goto end;
11622 }
11623
11624 ckch = new_ckchs->ckch;
11625
11626 /* loop on the field in the table, which have the same name as the
11627 * possible extensions of files */
11628 lua_pushnil(L);
11629 while (lua_next(L, 1)) {
11630 int i;
11631 const char *field = lua_tostring(L, -2);
11632 char *payload = (char *)lua_tostring(L, -1);
11633
11634 if (!field || strcmp(field, "filename") == 0) {
11635 lua_pop(L, 1);
11636 continue;
11637 }
11638
11639 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11640 if (strcmp(field, cert_exts[i].ext) == 0) {
11641 cert_ext = &cert_exts[i];
11642 break;
11643 }
11644 }
11645
11646 /* this is the default type, the field is not supported */
11647 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011648 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011649 errcode |= ERR_ALERT | ERR_FATAL;
11650 goto end;
11651 }
11652
11653 /* appply the change on the duplicate */
William Lallemandd8c195a2022-05-26 11:20:13 +020011654 if (cert_ext->load(filename, payload, ckch, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011655 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011656 errcode |= ERR_ALERT | ERR_FATAL;
11657 goto end;
11658 }
11659 lua_pop(L, 1);
11660 }
11661
11662 /* store the pointers on the lua stack */
11663 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11664 lua_ckchs[0] = old_ckchs;
11665 lua_ckchs[1] = new_ckchs;
11666 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11667 *lua_ckchi = NULL;
11668
11669 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11670 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11671
11672end:
11673 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11674
11675 if (errcode & ERR_CODE) {
11676 ckch_store_free(new_ckchs);
11677 WILL_LJMP(luaL_error(L, "%s", err));
11678 }
11679 free(err);
11680
11681 return 0;
11682}
11683
William Lallemand52139182022-03-30 15:05:42 +020011684#else
11685
11686__LJMP static int hlua_ckch_set(lua_State *L)
11687{
11688 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11689
11690 return 0;
11691}
11692#endif /* ! USE_OPENSSL */
11693
11694
11695
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011696/* This function can fail with an abort() due to an Lua critical error.
11697 * We are in the initialisation process of HAProxy, this abort() is
11698 * tolerated.
11699 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011700int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011701{
11702 struct hlua_init_function *init;
11703 const char *msg;
11704 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011705 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011706 const char *kind;
11707 const char *trace;
11708 int return_status = 1;
11709#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11710 int nres;
11711#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011712
Willy Tarreaucdb53462020-12-02 12:12:00 +010011713 /* disable memory limit checks if limit is not set */
11714 if (!hlua_global_allocator.limit)
11715 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11716
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011717 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011718 if (setjmp(safe_ljmp_env) != 0) {
11719 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011720 if (lua_type(L, -1) == LUA_TSTRING)
11721 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011722 else
11723 error = "critical error";
11724 fprintf(stderr, "Lua post-init: %s.\n", error);
11725 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011726 } else {
11727 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011728 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011729
Thierry Fournierb8cef172020-11-28 15:37:17 +010011730 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011731
Thierry Fournierc7492592020-11-28 23:57:24 +010011732 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011733 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011734
11735#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011736 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011737#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011738 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011739#endif
11740 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011741 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011742
11743 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011744 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011745 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011746
11747 case LUA_ERRERR:
11748 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011749 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011750 case LUA_ERRRUN:
11751 if (!kind)
11752 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011753 msg = lua_tostring(L, -1);
11754 lua_settop(L, 0); /* Empty the stack. */
11755 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011756 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011757 if (msg)
11758 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11759 else
11760 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11761 return_status = 0;
11762 break;
11763
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011764 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011765 /* Unknown error */
11766 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011767 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011768 case LUA_YIELD:
11769 /* yield is not configured at this step, this state doesn't happen */
11770 if (!kind)
11771 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011772 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011773 case LUA_ERRMEM:
11774 if (!kind)
11775 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011776 lua_settop(L, 0);
11777 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011778 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011779 ha_alert("Lua init: %s: %s\n", kind, trace);
11780 return_status = 0;
11781 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011782 }
Thierry Fournier670db242020-11-28 10:49:59 +010011783 if (!return_status)
11784 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011785 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011786
11787 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011788 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011789}
11790
Thierry Fournierb8cef172020-11-28 15:37:17 +010011791int hlua_post_init()
11792{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011793 int ret;
11794 int i;
11795 int errors;
11796 char *err = NULL;
11797 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011798 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011799
Willy Tarreaub1310492021-08-30 09:35:18 +020011800#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011801 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011802 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011803 int saved_used_backed = global.ssl_used_backend;
11804 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011805 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011806 global.ssl_used_backend = saved_used_backed;
11807 }
11808#endif
11809
Thierry Fournierc7492592020-11-28 23:57:24 +010011810 /* Perform post init of common thread */
11811 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011812 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011813 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11814 if (ret == 0)
11815 return 0;
11816
11817 /* init remaining lua states and load files */
11818 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11819
11820 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011821 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011822
11823 /* Init lua state */
11824 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11825
11826 /* Load lua files */
11827 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11828 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11829 if (ret != 0) {
11830 ha_alert("Lua init: %s\n", err);
11831 return 0;
11832 }
11833 }
11834 }
11835
11836 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011837 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011838
11839 /* Execute post init for all states */
11840 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11841
11842 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011843 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011844
11845 /* run post init */
11846 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11847 if (ret == 0)
11848 return 0;
11849 }
11850
11851 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011852 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011853
11854 /* control functions registering. Each function must have:
11855 * - only the function_ref[0] set positive and all other to -1
11856 * - only the function_ref[0] set to -1 and all other positive
11857 * This ensure a same reference is not used both in shared
11858 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011859 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011860 * complicated to found for the end user.
11861 */
11862 errors = 0;
11863 list_for_each_entry(fcn, &referenced_functions, l) {
11864 ret = 0;
11865 for (i = 1; i < global.nbthread + 1; i++) {
11866 if (fcn->function_ref[i] == -1)
11867 ret--;
11868 else
11869 ret++;
11870 }
11871 if (abs(ret) != global.nbthread) {
11872 ha_alert("Lua function '%s' is not referenced in all thread. "
11873 "Expect function in all thread or in none thread.\n", fcn->name);
11874 errors++;
11875 continue;
11876 }
11877
11878 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011879 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11880 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011881 "exclusive.\n", fcn->name);
11882 errors++;
11883 }
11884 }
11885
Christopher Faulet69c581a2021-05-31 08:54:04 +020011886 /* Do the same with registered filters */
11887 list_for_each_entry(reg_flt, &referenced_filters, l) {
11888 ret = 0;
11889 for (i = 1; i < global.nbthread + 1; i++) {
11890 if (reg_flt->flt_ref[i] == -1)
11891 ret--;
11892 else
11893 ret++;
11894 }
11895 if (abs(ret) != global.nbthread) {
11896 ha_alert("Lua filter '%s' is not referenced in all thread. "
11897 "Expect function in all thread or in none thread.\n", reg_flt->name);
11898 errors++;
11899 continue;
11900 }
11901
11902 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11903 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11904 "and per-thread Lua context (through lua-load-per-thread). these two context "
11905 "exclusive.\n", fcn->name);
11906 errors++;
11907 }
11908 }
11909
11910
Thierry Fournier59f11be2020-11-29 00:37:41 +010011911 if (errors > 0)
11912 return 0;
11913
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011914 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011915 * -1 in order to have probably a segfault if someone use it
11916 */
11917 hlua_state_id = -1;
11918
11919 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011920}
11921
Willy Tarreau32f61e22015-03-18 17:54:59 +010011922/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11923 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11924 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011925 * allocation. <nsize> is the requested new size. A new allocation is
11926 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011927 * zero. This one verifies that the limits are respected but is optimized
11928 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011929 *
11930 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11931 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11932 * that and will simply allocate zero as if it were the result of malloc(0),
11933 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11934 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011935 */
11936static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11937{
11938 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011939 size_t limit, old, new;
11940
11941 /* a limit of ~0 means unlimited and boot complete, so there's no need
11942 * for accounting anymore.
11943 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011944 if (likely(~zone->limit == 0)) {
11945 if (!nsize)
11946 ha_free(&ptr);
11947 else
11948 ptr = realloc(ptr, nsize);
11949 return ptr;
11950 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011951
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011952 if (!ptr)
11953 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011954
Willy Tarreaucdb53462020-12-02 12:12:00 +010011955 /* enforce strict limits across all threads */
11956 limit = zone->limit;
11957 old = _HA_ATOMIC_LOAD(&zone->allocated);
11958 do {
11959 new = old + nsize - osize;
11960 if (unlikely(nsize && limit && new > limit))
11961 return NULL;
11962 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011963
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011964 if (!nsize)
11965 ha_free(&ptr);
11966 else
11967 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011968
11969 if (unlikely(!ptr && nsize)) // failed
11970 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11971
11972 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011973 return ptr;
11974}
11975
Thierry Fournierecb83c22020-11-28 15:49:44 +010011976/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011977 * We are in the initialisation process of HAProxy, this abort() is
11978 * tolerated.
11979 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011980lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011981{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011982 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011983 int idx;
11984 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011985 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011986 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011987 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011988 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011989 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011990 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011991
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011992 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011993 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011994
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011995 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011996 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011997 *context = NULL;
11998
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011999 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012000 * the Lua function can fail with an abort. We are in the initialisation
12001 * process of HAProxy, this abort() is tolerated.
12002 */
12003
Thierry Fournier3c539322020-11-28 16:05:05 +010012004 /* Call post initialisation function in safe environment. */
12005 if (setjmp(safe_ljmp_env) != 0) {
12006 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012007 if (lua_type(L, -1) == LUA_TSTRING)
12008 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012009 else
12010 error_msg = "critical error";
12011 fprintf(stderr, "Lua init: %s.\n", error_msg);
12012 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012013 } else {
12014 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012015 }
12016
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012017 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012018 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012019#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12020#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12021#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012022 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012023#endif
12024#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012025 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012026#endif
12027#undef HLUA_PREPEND_PATH_TOSTRING
12028#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012029
Thierry Fournier59f11be2020-11-29 00:37:41 +010012030 /* Apply configured prepend path */
12031 list_for_each_entry(pp, &prepend_path_list, l)
12032 hlua_prepend_path(L, pp->type, pp->path);
12033
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012034 /*
12035 *
12036 * Create "core" object.
12037 *
12038 */
12039
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012040 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012041 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012042
Thierry Fournierecb83c22020-11-28 15:49:44 +010012043 /* set the thread id */
12044 hlua_class_const_int(L, "thread", thread_num);
12045
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012046 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012047 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012048 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012049
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012050 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012051 hlua_class_function(L, "register_init", hlua_register_init);
12052 hlua_class_function(L, "register_task", hlua_register_task);
12053 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12054 hlua_class_function(L, "register_converters", hlua_register_converters);
12055 hlua_class_function(L, "register_action", hlua_register_action);
12056 hlua_class_function(L, "register_service", hlua_register_service);
12057 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012058 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012059 hlua_class_function(L, "yield", hlua_yield);
12060 hlua_class_function(L, "set_nice", hlua_set_nice);
12061 hlua_class_function(L, "sleep", hlua_sleep);
12062 hlua_class_function(L, "msleep", hlua_msleep);
12063 hlua_class_function(L, "add_acl", hlua_add_acl);
12064 hlua_class_function(L, "del_acl", hlua_del_acl);
12065 hlua_class_function(L, "set_map", hlua_set_map);
12066 hlua_class_function(L, "del_map", hlua_del_map);
12067 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012068 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012069 hlua_class_function(L, "log", hlua_log);
12070 hlua_class_function(L, "Debug", hlua_log_debug);
12071 hlua_class_function(L, "Info", hlua_log_info);
12072 hlua_class_function(L, "Warning", hlua_log_warning);
12073 hlua_class_function(L, "Alert", hlua_log_alert);
12074 hlua_class_function(L, "done", hlua_done);
12075 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012076
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012077 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012078
12079 /*
12080 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012081 * Create "act" object.
12082 *
12083 */
12084
12085 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012087
12088 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012089 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12090 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12091 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12092 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12093 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12094 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12095 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12096 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012097
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012098 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012099
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012100 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012101
12102 /*
12103 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012104 * Create "Filter" object.
12105 *
12106 */
12107
12108 /* This table entry is the object "filter" base. */
12109 lua_newtable(L);
12110
12111 /* push flags and constants */
12112 hlua_class_const_int(L, "CONTINUE", 1);
12113 hlua_class_const_int(L, "WAIT", 0);
12114 hlua_class_const_int(L, "ERROR", -1);
12115
12116 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12117
Christopher Fauletc404f112020-02-26 15:03:09 +010012118 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12119 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12120 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12121
Christopher Faulet69c581a2021-05-31 08:54:04 +020012122 lua_setglobal(L, "filter");
12123
12124 /*
12125 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012126 * Register class Map
12127 *
12128 */
12129
12130 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012131 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012132
12133 /* register pattern types. */
12134 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012135 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012136 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012137 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012138 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012139 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012140
12141 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012142 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012143
12144 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012145 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012146
Ilya Shipitsind4259502020-04-08 01:07:56 +050012147 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012148 lua_pushstring(L, "__index");
12149 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012150
12151 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012152 hlua_class_function(L, "lookup", hlua_map_lookup);
12153 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012154
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012155 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012156
Thierry Fournier45e78d72016-02-19 18:34:46 +010012157 /* Register previous table in the registry with reference and named entry.
12158 * The function hlua_register_metatable() pops the stack, so we
12159 * previously create a copy of the table.
12160 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012161 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12162 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012163
12164 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012165 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012166
12167 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012168 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012169
12170 /*
12171 *
William Lallemand30fcca12022-03-30 12:03:12 +020012172 * Register "CertCache" class
12173 *
12174 */
12175
12176 /* Create and fill the metatable. */
12177 lua_newtable(L);
12178 /* Register */
12179 hlua_class_function(L, "set", hlua_ckch_set);
12180 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12181
12182 /*
12183 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012184 * Register class Channel
12185 *
12186 */
12187
12188 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012189 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012190
Ilya Shipitsind4259502020-04-08 01:07:56 +050012191 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012192 lua_pushstring(L, "__index");
12193 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012194
12195 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012196 hlua_class_function(L, "data", hlua_channel_get_data);
12197 hlua_class_function(L, "line", hlua_channel_get_line);
12198 hlua_class_function(L, "set", hlua_channel_set_data);
12199 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012201 hlua_class_function(L, "prepend", hlua_channel_prepend);
12202 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012203 hlua_class_function(L, "send", hlua_channel_send);
12204 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012205 hlua_class_function(L, "input", hlua_channel_get_in_len);
12206 hlua_class_function(L, "output", hlua_channel_get_out_len);
12207 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012208 hlua_class_function(L, "is_full", hlua_channel_is_full);
12209 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012210
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012211 /* Deprecated API */
12212 hlua_class_function(L, "get", hlua_channel_get);
12213 hlua_class_function(L, "dup", hlua_channel_dup);
12214 hlua_class_function(L, "getline", hlua_channel_getline);
12215 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12216 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12217
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012218 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012219
12220 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012221 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012222
12223 /*
12224 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012225 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012226 *
12227 */
12228
12229 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012230 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012231
Ilya Shipitsind4259502020-04-08 01:07:56 +050012232 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012233 lua_pushstring(L, "__index");
12234 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012235
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012236 /* Browse existing fetches and create the associated
12237 * object method.
12238 */
12239 sf = NULL;
12240 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012241 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12242 * by an underscore.
12243 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012244 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012245 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012246 if (*p == '.' || *p == '-' || *p == '+')
12247 *p = '_';
12248
12249 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012250 lua_pushstring(L, trash.area);
12251 lua_pushlightuserdata(L, sf);
12252 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12253 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012254 }
12255
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012256 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012257
12258 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012259 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012260
12261 /*
12262 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012263 * Register class Converters
12264 *
12265 */
12266
12267 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012268 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012269
12270 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012271 lua_pushstring(L, "__index");
12272 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012273
12274 /* Browse existing converters and create the associated
12275 * object method.
12276 */
12277 sc = NULL;
12278 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012279 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12280 * by an underscore.
12281 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012282 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012283 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012284 if (*p == '.' || *p == '-' || *p == '+')
12285 *p = '_';
12286
12287 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012288 lua_pushstring(L, trash.area);
12289 lua_pushlightuserdata(L, sc);
12290 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12291 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012292 }
12293
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012294 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012295
12296 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012297 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012298
12299 /*
12300 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012301 * Register class HTTP
12302 *
12303 */
12304
12305 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012306 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012307
Ilya Shipitsind4259502020-04-08 01:07:56 +050012308 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012309 lua_pushstring(L, "__index");
12310 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012311
12312 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012313 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12314 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12315 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12316 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12317 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12318 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12319 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12320 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12321 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12322 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012323
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012324 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12325 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12326 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12327 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12328 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12329 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12330 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012331
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012332 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012333
12334 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012335 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012336
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012337 /*
12338 *
12339 * Register class HTTPMessage
12340 *
12341 */
12342
12343 /* Create and fill the metatable. */
12344 lua_newtable(L);
12345
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012346 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012347 lua_pushstring(L, "__index");
12348 lua_newtable(L);
12349
12350 /* Register Lua functions. */
12351 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12352 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12353 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12354 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12355 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12356 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12357 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12358 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12359 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12360 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12361 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12362 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12363 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12364 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12365 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12366 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12367 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12368 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12369
12370 hlua_class_function(L, "body", hlua_http_msg_get_body);
12371 hlua_class_function(L, "set", hlua_http_msg_set_data);
12372 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12373 hlua_class_function(L, "append", hlua_http_msg_append);
12374 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12375 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12376 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12377 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12378
12379 hlua_class_function(L, "send", hlua_http_msg_send);
12380 hlua_class_function(L, "forward", hlua_http_msg_forward);
12381
12382 lua_rawset(L, -3);
12383
12384 /* Register previous table in the registry with reference and named entry. */
12385 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012386
12387 /*
12388 *
12389 * Register class HTTPClient
12390 *
12391 */
12392
12393 /* Create and fill the metatable. */
12394 lua_newtable(L);
12395 lua_pushstring(L, "__index");
12396 lua_newtable(L);
12397 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012398 hlua_class_function(L, "head", hlua_httpclient_head);
12399 hlua_class_function(L, "put", hlua_httpclient_put);
12400 hlua_class_function(L, "post", hlua_httpclient_post);
12401 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012402 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012403 /* Register the garbage collector entry. */
12404 lua_pushstring(L, "__gc");
12405 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12406 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12407
William Lallemand3956c4e2021-09-21 16:25:15 +020012408
12409
12410 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012411 /*
12412 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012413 * Register class AppletTCP
12414 *
12415 */
12416
12417 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012418 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012419
Ilya Shipitsind4259502020-04-08 01:07:56 +050012420 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012421 lua_pushstring(L, "__index");
12422 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012423
12424 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012425 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12426 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12427 hlua_class_function(L, "send", hlua_applet_tcp_send);
12428 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12429 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12430 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12431 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12432 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012433
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012434 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012435
12436 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012437 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012438
12439 /*
12440 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012441 * Register class AppletHTTP
12442 *
12443 */
12444
12445 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012446 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012447
Ilya Shipitsind4259502020-04-08 01:07:56 +050012448 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012449 lua_pushstring(L, "__index");
12450 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012451
12452 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012453 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12454 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12455 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12456 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12457 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12458 hlua_class_function(L, "getline", hlua_applet_http_getline);
12459 hlua_class_function(L, "receive", hlua_applet_http_recv);
12460 hlua_class_function(L, "send", hlua_applet_http_send);
12461 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12462 hlua_class_function(L, "set_status", hlua_applet_http_status);
12463 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012464
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012465 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012466
12467 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012468 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012469
12470 /*
12471 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012472 * Register class TXN
12473 *
12474 */
12475
12476 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012477 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012478
Ilya Shipitsind4259502020-04-08 01:07:56 +050012479 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012480 lua_pushstring(L, "__index");
12481 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012482
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012483 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012484 hlua_class_function(L, "set_priv", hlua_set_priv);
12485 hlua_class_function(L, "get_priv", hlua_get_priv);
12486 hlua_class_function(L, "set_var", hlua_set_var);
12487 hlua_class_function(L, "unset_var", hlua_unset_var);
12488 hlua_class_function(L, "get_var", hlua_get_var);
12489 hlua_class_function(L, "done", hlua_txn_done);
12490 hlua_class_function(L, "reply", hlua_txn_reply_new);
12491 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12492 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12493 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12494 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12495 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12496 hlua_class_function(L, "deflog", hlua_txn_deflog);
12497 hlua_class_function(L, "log", hlua_txn_log);
12498 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12499 hlua_class_function(L, "Info", hlua_txn_log_info);
12500 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12501 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012502
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012503 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012504
12505 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012506 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012507
12508 /*
12509 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012510 * Register class reply
12511 *
12512 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012513 lua_newtable(L);
12514 lua_pushstring(L, "__index");
12515 lua_newtable(L);
12516 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12517 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12518 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12519 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12520 lua_settable(L, -3); /* Sets the __index entry. */
12521 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012522
12523
12524 /*
12525 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012526 * Register class Socket
12527 *
12528 */
12529
12530 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012531 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012532
Ilya Shipitsind4259502020-04-08 01:07:56 +050012533 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012534 lua_pushstring(L, "__index");
12535 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012536
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012537#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012538 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012539#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012540 hlua_class_function(L, "connect", hlua_socket_connect);
12541 hlua_class_function(L, "send", hlua_socket_send);
12542 hlua_class_function(L, "receive", hlua_socket_receive);
12543 hlua_class_function(L, "close", hlua_socket_close);
12544 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12545 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12546 hlua_class_function(L, "setoption", hlua_socket_setoption);
12547 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012548
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012549 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012550
12551 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012552 lua_pushstring(L, "__gc");
12553 lua_pushcclosure(L, hlua_socket_gc, 0);
12554 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012555
12556 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012557 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012558
Thierry Fournieraafc7772020-12-04 11:47:47 +010012559 lua_atpanic(L, hlua_panic_safe);
12560
12561 return L;
12562}
12563
12564void hlua_init(void) {
12565 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012566 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012567#ifdef USE_OPENSSL
12568 struct srv_kw *kw;
12569 int tmp_error;
12570 char *error;
12571 char *args[] = { /* SSL client configuration. */
12572 "ssl",
12573 "verify",
12574 "none",
12575 NULL
12576 };
12577#endif
12578
12579 /* Init post init function list head */
12580 for (i = 0; i < MAX_THREADS + 1; i++)
12581 LIST_INIT(&hlua_init_functions[i]);
12582
12583 /* Init state for common/shared lua parts */
12584 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012585 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012586 hlua_states[0] = hlua_init_state(0);
12587
12588 /* Init state 1 for thread 0. We have at least one thread. */
12589 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012590 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012591 hlua_states[1] = hlua_init_state(1);
12592
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012593 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012594 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012595 if (!socket_proxy) {
12596 fprintf(stderr, "Lua init: %s\n", errmsg);
12597 exit(1);
12598 }
12599 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012600
12601 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012602 socket_tcp = new_server(socket_proxy);
12603 if (!socket_tcp) {
12604 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12605 exit(1);
12606 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012607
12608#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012609 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012610 socket_ssl = new_server(socket_proxy);
12611 if (!socket_ssl) {
12612 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12613 exit(1);
12614 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012615
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012616 socket_ssl->use_ssl = 1;
12617 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012618
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012619 for (i = 0; args[i] != NULL; i++) {
12620 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012621 /*
12622 *
12623 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012624 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012625 * features like client certificates and ssl_verify.
12626 *
12627 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012628 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012629 if (tmp_error != 0) {
12630 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12631 abort(); /* This must be never arrives because the command line
12632 not editable by the user. */
12633 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012634 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012635 }
12636 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012637#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012638
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012639}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012640
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012641static void hlua_deinit()
12642{
Willy Tarreau186f3762020-12-04 11:48:12 +010012643 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012644 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12645
12646 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12647 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012648
12649 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12650 if (hlua_states[thr])
12651 lua_close(hlua_states[thr]);
12652 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012653
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012654 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012655
Willy Tarreau0f143af2021-03-05 10:41:48 +010012656#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012657 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012658#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012659
12660 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012661}
12662
12663REGISTER_POST_DEINIT(hlua_deinit);
12664
Willy Tarreau80713382018-11-26 10:19:54 +010012665static void hlua_register_build_options(void)
12666{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012667 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012668
Willy Tarreaubb57d942016-12-21 19:04:56 +010012669 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12670 hap_register_build_opts(ptr, 1);
12671}
Willy Tarreau80713382018-11-26 10:19:54 +010012672
12673INITCALL0(STG_REGISTER, hlua_register_build_options);