blob: 5a0a78c386947ca6452acee1533158d7c4f77825 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020054#include <haproxy/sc_strm.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010055#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020056#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020057#include <haproxy/ssl_ckch.h>
58#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020059#include <haproxy/stats-t.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020060#include <haproxy/stconn.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
Thierry Fournierae6b5682022-09-19 09:04:16 +0200148static char ***per_thread_load = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +0100149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Christopher Fauletd09cc512021-03-24 14:48:45 +0100501__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200502{
503 lua_Debug ar;
504 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200505 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200508 /* Fill fields:
509 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
510 * 'l': fills in the field currentline;
511 * 'n': fills in the field name and namewhat;
512 * 't': fills in the field istailcall;
513 */
514 lua_getinfo(L, "Slnt", &ar);
515
Willy Tarreau5c143402022-06-19 17:35:53 +0200516 /* skip these empty entries, usually they come from deep C functions */
517 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
518 continue;
519
520 /* Add separator */
521 if (b_data(msg))
522 chunk_appendf(msg, "%s", sep);
523
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200524 /* Append code localisation */
525 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100526 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200527 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100528 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200529
530 /*
531 * Get function name
532 *
533 * if namewhat is no empty, name is defined.
534 * what contains "Lua" for Lua function, "C" for C function,
535 * or "main" for main code.
536 */
537 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100538 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200539
540 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100541 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200542
543 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100544 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200545
546 else /* nothing left... */
547 chunk_appendf(msg, "?");
548
549
550 /* Display tailed call */
551 if (ar.istailcall)
552 chunk_appendf(msg, " ...");
553 }
554
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200555 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200556}
557
558
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100559/* This function check the number of arguments available in the
560 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500561 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100562 */
563__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
564{
565 if (lua_gettop(L) == nb)
566 return;
567 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
568}
569
Mark Lakes22154b42018-01-29 14:38:40 -0800570/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100571 * and the line number where the error is encountered.
572 */
573static int hlua_pusherror(lua_State *L, const char *fmt, ...)
574{
575 va_list argp;
576 va_start(argp, fmt);
577 luaL_where(L, 1);
578 lua_pushvfstring(L, fmt, argp);
579 va_end(argp);
580 lua_concat(L, 2);
581 return 1;
582}
583
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584/* This functions is used with sample fetch and converters. It
585 * converts the HAProxy configuration argument in a lua stack
586 * values.
587 *
588 * It takes an array of "arg", and each entry of the array is
589 * converted and pushed in the LUA stack.
590 */
591static int hlua_arg2lua(lua_State *L, const struct arg *arg)
592{
593 switch (arg->type) {
594 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 case ARGT_TIME:
596 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100597 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 break;
599
600 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200601 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case ARGT_IPV4:
605 case ARGT_IPV6:
606 case ARGT_MSK4:
607 case ARGT_MSK6:
608 case ARGT_FE:
609 case ARGT_BE:
610 case ARGT_TAB:
611 case ARGT_SRV:
612 case ARGT_USR:
613 case ARGT_MAP:
614 default:
615 lua_pushnil(L);
616 break;
617 }
618 return 1;
619}
620
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500621/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500623 * with sample fetch wrappers. The input arguments are given to the
624 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100625 */
626static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
627{
628 switch (lua_type(L, ud)) {
629
630 case LUA_TNUMBER:
631 case LUA_TBOOLEAN:
632 arg->type = ARGT_SINT;
633 arg->data.sint = lua_tointeger(L, ud);
634 break;
635
636 case LUA_TSTRING:
637 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200638 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200639 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200640 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200641 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643
644 case LUA_TUSERDATA:
645 case LUA_TNIL:
646 case LUA_TTABLE:
647 case LUA_TFUNCTION:
648 case LUA_TTHREAD:
649 case LUA_TLIGHTUSERDATA:
650 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200651 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 break;
653 }
654 return 1;
655}
656
657/* the following functions are used to convert a struct sample
658 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500659 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100660 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100661static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200663 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100665 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200666 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 break;
668
669 case SMP_T_BIN:
670 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200671 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 break;
673
674 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200675 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
677 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
678 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
679 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
680 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
681 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
682 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
683 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
684 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200685 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100686 break;
687 default:
688 lua_pushnil(L);
689 break;
690 }
691 break;
692
693 case SMP_T_IPV4:
694 case SMP_T_IPV6:
695 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200696 if (sample_casts[smp->data.type][SMP_T_STR] &&
697 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200698 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100699 else
700 lua_pushnil(L);
701 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100702 default:
703 lua_pushnil(L);
704 break;
705 }
706 return 1;
707}
708
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100709/* the following functions are used to convert a struct sample
710 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500711 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100712 */
713static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
714{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200715 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716
717 case SMP_T_BIN:
718 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200719 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100720 break;
721
722 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200723 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100724 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
725 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
726 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
727 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
728 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
729 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
730 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
731 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
732 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200733 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100734 break;
735 default:
736 lua_pushstring(L, "");
737 break;
738 }
739 break;
740
741 case SMP_T_SINT:
742 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100743 case SMP_T_IPV4:
744 case SMP_T_IPV6:
745 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 if (sample_casts[smp->data.type][SMP_T_STR] &&
747 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100749 else
750 lua_pushstring(L, "");
751 break;
752 default:
753 lua_pushstring(L, "");
754 break;
755 }
756 return 1;
757}
758
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100759/* the following functions are used to convert an Lua type in a
760 * struct sample. This is useful to provide data from a converter
761 * to the LUA code.
762 */
763static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
764{
765 switch (lua_type(L, ud)) {
766
767 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200768 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200769 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770 break;
771
772
773 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200774 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200775 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 break;
777
778 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200779 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200781 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200782 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200783 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200784 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786
787 case LUA_TUSERDATA:
788 case LUA_TNIL:
789 case LUA_TTABLE:
790 case LUA_TFUNCTION:
791 case LUA_TTHREAD:
792 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200793 case LUA_TNONE:
794 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200795 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200796 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100797 break;
798 }
799 return 1;
800}
801
Ilya Shipitsind4259502020-04-08 01:07:56 +0500802/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800803 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100805 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500806 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200807 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100808 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100809__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100810 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811{
812 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200813 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100814 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200815 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200816 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200817 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200818 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100819
820 idx = 0;
821 min_arg = ARGM(mask);
822 mask >>= ARGM_BITS;
823
824 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200825 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 /* Check for mandatory arguments. */
828 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100829 if (idx < min_arg) {
830
831 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 if (idx > 0) {
833 msg = "Mandatory argument expected";
834 goto error;
835 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836
837 /* If first argument have a certain type, some default values
838 * may be used. See the function smp_resolve_args().
839 */
840 switch (mask & ARGT_MASK) {
841
842 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 if (!(p->cap & PR_CAP_FE)) {
844 msg = "Mandatory argument expected";
845 goto error;
846 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 argp[idx].data.prx = p;
848 argp[idx].type = ARGT_FE;
849 argp[idx+1].type = ARGT_STOP;
850 break;
851
852 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200853 if (!(p->cap & PR_CAP_BE)) {
854 msg = "Mandatory argument expected";
855 goto error;
856 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100857 argp[idx].data.prx = p;
858 argp[idx].type = ARGT_BE;
859 argp[idx+1].type = ARGT_STOP;
860 break;
861
862 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +0200863 if (!p->table) {
864 msg = "Mandatory argument expected";
865 goto error;
866 }
867 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 argp[idx].type = ARGT_TAB;
869 argp[idx+1].type = ARGT_STOP;
870 break;
871
872 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200873 msg = "Mandatory argument expected";
874 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100875 break;
876 }
877 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200878 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879 }
880
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500881 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 if ((mask & ARGT_MASK) == ARGT_STOP &&
883 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200884 msg = "Last argument expected";
885 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100886 }
887
888 if ((mask & ARGT_MASK) == ARGT_STOP &&
889 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100891 }
892
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 /* Convert some argument types. All string in argp[] are for not
894 * duplicated yet.
895 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100896 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100897 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200898 if (argp[idx].type != ARGT_SINT) {
899 msg = "integer expected";
900 goto error;
901 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100902 argp[idx].type = ARGT_SINT;
903 break;
904
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200906 if (argp[idx].type != ARGT_SINT) {
907 msg = "integer expected";
908 goto error;
909 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200910 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100911 break;
912
913 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200914 if (argp[idx].type != ARGT_SINT) {
915 msg = "integer expected";
916 goto error;
917 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200918 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100919 break;
920
921 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200922 if (argp[idx].type != ARGT_STR) {
923 msg = "string expected";
924 goto error;
925 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200926 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200927 if (!argp[idx].data.prx) {
928 msg = "frontend doesn't exist";
929 goto error;
930 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100931 argp[idx].type = ARGT_FE;
932 break;
933
934 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200935 if (argp[idx].type != ARGT_STR) {
936 msg = "string expected";
937 goto error;
938 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200939 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200940 if (!argp[idx].data.prx) {
941 msg = "backend doesn't exist";
942 goto error;
943 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100944 argp[idx].type = ARGT_BE;
945 break;
946
947 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200948 if (argp[idx].type != ARGT_STR) {
949 msg = "string expected";
950 goto error;
951 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200952 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200953 if (!argp[idx].data.t) {
954 msg = "table doesn't exist";
955 goto error;
956 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100957 argp[idx].type = ARGT_TAB;
958 break;
959
960 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200961 if (argp[idx].type != ARGT_STR) {
962 msg = "string expected";
963 goto error;
964 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200965 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100966 if (sname) {
967 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200969 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200970 if (!px) {
971 msg = "backend doesn't exist";
972 goto error;
973 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100974 }
975 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200976 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100978 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100979 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200980 if (!argp[idx].data.srv) {
981 msg = "server doesn't exist";
982 goto error;
983 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100984 argp[idx].type = ARGT_SRV;
985 break;
986
987 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200988 if (argp[idx].type != ARGT_STR) {
989 msg = "string expected";
990 goto error;
991 }
992 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
993 msg = "invalid IPv4 address";
994 goto error;
995 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100996 argp[idx].type = ARGT_IPV4;
997 break;
998
999 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001000 if (argp[idx].type == ARGT_SINT)
1001 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1002 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001003 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1004 msg = "invalid IPv4 mask";
1005 goto error;
1006 }
1007 }
1008 else {
1009 msg = "integer or string expected";
1010 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001011 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001012 argp[idx].type = ARGT_MSK4;
1013 break;
1014
1015 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001016 if (argp[idx].type != ARGT_STR) {
1017 msg = "string expected";
1018 goto error;
1019 }
1020 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1021 msg = "invalid IPv6 address";
1022 goto error;
1023 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 argp[idx].type = ARGT_IPV6;
1025 break;
1026
1027 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001028 if (argp[idx].type == ARGT_SINT)
1029 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1030 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001031 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1032 msg = "invalid IPv6 mask";
1033 goto error;
1034 }
1035 }
1036 else {
1037 msg = "integer or string expected";
1038 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001039 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001040 argp[idx].type = ARGT_MSK6;
1041 break;
1042
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001043 case ARGT_REG:
1044 if (argp[idx].type != ARGT_STR) {
1045 msg = "string expected";
1046 goto error;
1047 }
1048 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1049 if (!reg) {
1050 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1051 argp[idx].data.str.area, err);
1052 free(err);
1053 goto error;
1054 }
1055 argp[idx].type = ARGT_REG;
1056 argp[idx].data.reg = reg;
1057 break;
1058
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001059 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001060 if (argp[idx].type != ARGT_STR) {
1061 msg = "string expected";
1062 goto error;
1063 }
1064 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001065 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001066 ul = p->uri_auth->userlist;
1067 else
1068 ul = auth_find_userlist(argp[idx].data.str.area);
1069
1070 if (!ul) {
1071 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1072 goto error;
1073 }
1074 argp[idx].type = ARGT_USR;
1075 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001076 break;
1077
1078 case ARGT_STR:
1079 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1080 msg = "unable to duplicate string arg";
1081 goto error;
1082 }
1083 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001084 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001085
Christopher Fauletd25d9262020-08-06 11:04:46 +02001086 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001087 msg = "type not yet supported";
1088 goto error;
1089 break;
1090
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001091 }
1092
1093 /* Check for type of argument. */
1094 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001095 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1096 arg_type_names[(mask & ARGT_MASK)],
1097 arg_type_names[argp[idx].type & ARGT_MASK]);
1098 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001099 }
1100
1101 /* Next argument. */
1102 mask >>= ARGT_BITS;
1103 idx++;
1104 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001105 return 0;
1106
1107 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001108 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001109 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001110 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1111 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001112}
1113
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001115 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001116 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117 *
1118 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 * - hlua_sethlua : create the association between hlua context and lua_state.
1120 */
1121static inline struct hlua *hlua_gethlua(lua_State *L)
1122{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001123 struct hlua **hlua = lua_getextraspace(L);
1124 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125}
1126static inline void hlua_sethlua(struct hlua *hlua)
1127{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001128 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1129 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001130}
1131
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001132/* Will return a non-NULL string indicating the Lua call trace if the caller
1133 * currently is executing from within a Lua function. One line per entry will
1134 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1135 * Lua function is not detected, NULL is returned.
1136 */
1137const char *hlua_show_current_location(const char *pfx)
1138{
1139 lua_State *L;
1140 lua_Debug ar;
1141
1142 /* global or per-thread stack initializing ? */
1143 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1144 return hlua_traceback(L, pfx);
1145
1146 /* per-thread stack running ? */
1147 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1148 return hlua_traceback(L, pfx);
1149
1150 /* global stack running ? */
1151 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1152 return hlua_traceback(L, pfx);
1153
1154 return NULL;
1155}
1156
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001157/* This function is used to send logs. It try to send on screen (stderr)
1158 * and on the default syslog server.
1159 */
1160static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1161{
1162 struct tm tm;
1163 char *p;
1164
1165 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001166 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001167 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001168 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001169 /* Break the message if exceed the buffer size. */
1170 *(p-4) = ' ';
1171 *(p-3) = '.';
1172 *(p-2) = '.';
1173 *(p-1) = '.';
1174 break;
1175 }
Willy Tarreau90807112020-02-25 08:16:33 +01001176 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001177 *p = *msg;
1178 else
1179 *p = '.';
1180 }
1181 *p = '\0';
1182
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001183 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001184 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001185 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1186 return;
1187
Willy Tarreaua678b432015-08-28 10:14:59 +02001188 get_localtime(date.tv_sec, &tm);
1189 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001190 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001191 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001192 fflush(stderr);
1193 }
1194}
1195
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196/* This function just ensure that the yield will be always
1197 * returned with a timeout and permit to set some flags
1198 */
1199__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001200 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001201{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001202 struct hlua *hlua;
1203
1204 /* Get hlua struct, or NULL if we execute from main lua state */
1205 hlua = hlua_gethlua(L);
1206 if (!hlua) {
1207 return;
1208 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001209
1210 /* Set the wake timeout. If timeout is required, we set
1211 * the expiration time.
1212 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001213 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001214
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001215 hlua->flags |= flags;
1216
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001217 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001218 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001219}
1220
Willy Tarreau87b09662015-04-03 00:22:06 +02001221/* This function initialises the Lua environment stored in the stream.
1222 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001223 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001224 *
1225 * This function is particular. it initialises a new Lua thread. If the
1226 * initialisation fails (example: out of memory error), the lua function
1227 * throws an error (longjmp).
1228 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001229 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001230 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001231 * threads appear, the safe environment set a lock to ensure only one
1232 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001233 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001234 *
1235 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001236 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001237 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001238 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001239 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001240 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001241 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001242 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001243int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001244{
1245 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001246 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001247 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001248 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001249 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001250 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001251 MT_LIST_INIT(&lua->hc_list);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001252 if (!already_safe) {
1253 if (!SET_SAFE_LJMP_PARENT(lua)) {
1254 lua->Tref = LUA_REFNIL;
1255 return 0;
1256 }
1257 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001258 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001259 if (!lua->T) {
1260 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001261 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001262 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001263 return 0;
1264 }
1265 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001266 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001267 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001268 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001269 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001270 return 1;
1271}
1272
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001273/* kill all associated httpclient to this hlua task
1274 * We must take extra precautions as we're manipulating lua-exposed
1275 * objects without the main lua lock.
1276 */
William Lallemandbb581422022-10-20 10:57:28 +02001277static void hlua_httpclient_destroy_all(struct hlua *hlua)
1278{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001279 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001280
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001281 /* use thread-safe accessors for hc_list since GC cycle initiated by
1282 * another thread sharing the same main lua stack (lua coroutine)
1283 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1284 * in parallel: Lua GC applies on the main stack, it is not limited to
1285 * a single coroutine stack, see Github issue #2037 for reference.
1286 * Remember, coroutines created using lua_newthread() are not meant to
1287 * be thread safe in Lua. (From lua co-author:
1288 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1289 *
1290 * This security measure is superfluous when 'lua-load-per-thread' is used
1291 * since in this case coroutines exclusively run on the same thread
1292 * (main stack is not shared between OS threads).
1293 */
1294 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1295 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001296 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001297 }
1298}
1299
1300
Willy Tarreau87b09662015-04-03 00:22:06 +02001301/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001302 * is destroyed. The destroy also the memory context. The struct "lua"
1303 * is not freed.
1304 */
1305void hlua_ctx_destroy(struct hlua *lua)
1306{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001307 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001308 return;
1309
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001310 if (!lua->T)
1311 goto end;
1312
William Lallemandbb581422022-10-20 10:57:28 +02001313 /* clean all running httpclient */
1314 hlua_httpclient_destroy_all(lua);
1315
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001316 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001317 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001318
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001319 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001320 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001321 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001322 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001323
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001324 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001325 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001326 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001327 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001328 /* Forces a garbage collecting process. If the Lua program is finished
1329 * without error, we run the GC on the thread pointer. Its freed all
1330 * the unused memory.
1331 * If the thread is finnish with an error or is currently yielded,
1332 * it seems that the GC applied on the thread doesn't clean anything,
1333 * so e run the GC on the main thread.
1334 * NOTE: maybe this action locks all the Lua threads untiml the en of
1335 * the garbage collection.
1336 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001337 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001338 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001339 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001340 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001341 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001342 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001343
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001344 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001345
1346end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001347 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001348}
1349
1350/* This function is used to restore the Lua context when a coroutine
1351 * fails. This function copy the common memory between old coroutine
1352 * and the new coroutine. The old coroutine is destroyed, and its
1353 * replaced by the new coroutine.
1354 * If the flag "keep_msg" is set, the last entry of the old is assumed
1355 * as string error message and it is copied in the new stack.
1356 */
1357static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1358{
1359 lua_State *T;
1360 int new_ref;
1361
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001362 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001363 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001364 if (!T)
1365 return 0;
1366
1367 /* Copy last error message. */
1368 if (keep_msg)
1369 lua_xmove(lua->T, T, 1);
1370
1371 /* Copy data between the coroutines. */
1372 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1373 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001374 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001375
1376 /* Destroy old data. */
1377 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1378
1379 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001380 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001381
1382 /* Fill the struct with the new coroutine values. */
1383 lua->Mref = new_ref;
1384 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001385 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001386
1387 /* Set context. */
1388 hlua_sethlua(lua);
1389
1390 return 1;
1391}
1392
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001393void hlua_hook(lua_State *L, lua_Debug *ar)
1394{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001395 struct hlua *hlua;
1396
1397 /* Get hlua struct, or NULL if we execute from main lua state */
1398 hlua = hlua_gethlua(L);
1399 if (!hlua)
1400 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001401
1402 /* Lua cannot yield when its returning from a function,
1403 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001404 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001405 */
1406 if (lua_gethookmask(L) & LUA_MASKRET) {
1407 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1408 return;
1409 }
1410
1411 /* restore the interrupt condition. */
1412 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1413
1414 /* If we interrupt the Lua processing in yieldable state, we yield.
1415 * If the state is not yieldable, trying yield causes an error.
1416 */
1417 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001418 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001419
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001420 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001421 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001422 hlua->run_time += now_ms - hlua->start_time;
1423 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001424 lua_pushfstring(L, "execution timeout");
1425 WILL_LJMP(lua_error(L));
1426 }
1427
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001428 /* Update the start time. */
1429 hlua->start_time = now_ms;
1430
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001431 /* Try to interrupt the process at the end of the current
1432 * unyieldable function.
1433 */
1434 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001435}
1436
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001437/* This function start or resumes the Lua stack execution. If the flag
1438 * "yield_allowed" if no set and the LUA stack execution returns a yield
1439 * The function return an error.
1440 *
1441 * The function can returns 4 values:
1442 * - HLUA_E_OK : The execution is terminated without any errors.
1443 * - HLUA_E_AGAIN : The execution must continue at the next associated
1444 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001445 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001446 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001447 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001448 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001449 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001450 * LUA code.
1451 */
1452static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1453{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001454#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1455 int nres;
1456#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001457 int ret;
1458 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001459 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001460
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001461 /* Initialise run time counter. */
1462 if (!HLUA_IS_RUNNING(lua))
1463 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001464
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001465 /* Lock the whole Lua execution. This lock must be before the
1466 * label "resume_execution".
1467 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001468 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001469 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001470
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001471resume_execution:
1472
1473 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1474 * instructions. it is used for preventing infinite loops.
1475 */
1476 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1477
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001478 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001479 HLUA_SET_RUN(lua);
1480 HLUA_CLR_CTRLYIELD(lua);
1481 HLUA_CLR_WAKERESWR(lua);
1482 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001483 HLUA_CLR_NOYIELD(lua);
1484 if (!yield_allowed)
1485 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001486
Christopher Fauletbc275a92020-02-26 14:55:16 +01001487 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001488 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001489 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001490
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001492#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001493 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001494#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001495 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001496#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001497 switch (ret) {
1498
1499 case LUA_OK:
1500 ret = HLUA_E_OK;
1501 break;
1502
1503 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001504 /* Check if the execution timeout is expired. It it is the case, we
1505 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001506 */
Willy Tarreau55542642021-10-08 09:33:24 +02001507 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001508 lua->run_time += now_ms - lua->start_time;
1509 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001510 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001511 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001512 break;
1513 }
1514 /* Process the forced yield. if the general yield is not allowed or
1515 * if no task were associated this the current Lua execution
1516 * coroutine, we resume the execution. Else we want to return in the
1517 * scheduler and we want to be waked up again, to continue the
1518 * current Lua execution. So we schedule our own task.
1519 */
1520 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001521 if (!yield_allowed || !lua->task)
1522 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001523 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001524 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001525 if (!yield_allowed) {
1526 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001527 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001528 break;
1529 }
1530 ret = HLUA_E_AGAIN;
1531 break;
1532
1533 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001534
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001535 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001536 * because the errors ares the only one mean to return immediately
1537 * from and lua execution.
1538 */
1539 if (lua->flags & HLUA_EXIT) {
1540 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001541 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001542 break;
1543 }
1544
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001545 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001546 if (!lua_checkstack(lua->T, 1)) {
1547 ret = HLUA_E_ERR;
1548 break;
1549 }
1550 msg = lua_tostring(lua->T, -1);
1551 lua_settop(lua->T, 0); /* Empty the stack. */
1552 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001553 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001554 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001555 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001556 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001557 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001558 ret = HLUA_E_ERRMSG;
1559 break;
1560
1561 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001562 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001563 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001564 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001565 break;
1566
1567 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001568 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001569 if (!lua_checkstack(lua->T, 1)) {
1570 ret = HLUA_E_ERR;
1571 break;
1572 }
1573 msg = lua_tostring(lua->T, -1);
1574 lua_settop(lua->T, 0); /* Empty the stack. */
1575 lua_pop(lua->T, 1);
1576 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001577 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001578 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001579 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001580 ret = HLUA_E_ERRMSG;
1581 break;
1582
1583 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001584 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001585 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001586 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001587 break;
1588 }
1589
1590 switch (ret) {
1591 case HLUA_E_AGAIN:
1592 break;
1593
1594 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001595 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001596 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001597 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001598 break;
1599
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001600 case HLUA_E_ETMOUT:
1601 case HLUA_E_NOMEM:
1602 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001603 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001604 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001605 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001606 hlua_ctx_renew(lua, 0);
1607 break;
1608
1609 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001610 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001611 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001612 break;
1613 }
1614
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001615 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001616 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001617 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001618
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001619 return ret;
1620}
1621
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001622/* This function exit the current code. */
1623__LJMP static int hlua_done(lua_State *L)
1624{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001625 struct hlua *hlua;
1626
1627 /* Get hlua struct, or NULL if we execute from main lua state */
1628 hlua = hlua_gethlua(L);
1629 if (!hlua)
1630 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001631
1632 hlua->flags |= HLUA_EXIT;
1633 WILL_LJMP(lua_error(L));
1634
1635 return 0;
1636}
1637
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001638/* This function is an LUA binding. It provides a function
1639 * for deleting ACL from a referenced ACL file.
1640 */
1641__LJMP static int hlua_del_acl(lua_State *L)
1642{
1643 const char *name;
1644 const char *key;
1645 struct pat_ref *ref;
1646
1647 MAY_LJMP(check_args(L, 2, "del_acl"));
1648
1649 name = MAY_LJMP(luaL_checkstring(L, 1));
1650 key = MAY_LJMP(luaL_checkstring(L, 2));
1651
1652 ref = pat_ref_lookup(name);
1653 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001654 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001655
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001656 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001657 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001658 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001659 return 0;
1660}
1661
1662/* This function is an LUA binding. It provides a function
1663 * for deleting map entry from a referenced map file.
1664 */
1665static int hlua_del_map(lua_State *L)
1666{
1667 const char *name;
1668 const char *key;
1669 struct pat_ref *ref;
1670
1671 MAY_LJMP(check_args(L, 2, "del_map"));
1672
1673 name = MAY_LJMP(luaL_checkstring(L, 1));
1674 key = MAY_LJMP(luaL_checkstring(L, 2));
1675
1676 ref = pat_ref_lookup(name);
1677 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001678 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001679
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001680 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001681 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001682 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001683 return 0;
1684}
1685
1686/* This function is an LUA binding. It provides a function
1687 * for adding ACL pattern from a referenced ACL file.
1688 */
1689static int hlua_add_acl(lua_State *L)
1690{
1691 const char *name;
1692 const char *key;
1693 struct pat_ref *ref;
1694
1695 MAY_LJMP(check_args(L, 2, "add_acl"));
1696
1697 name = MAY_LJMP(luaL_checkstring(L, 1));
1698 key = MAY_LJMP(luaL_checkstring(L, 2));
1699
1700 ref = pat_ref_lookup(name);
1701 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001702 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001703
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001704 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001705 if (pat_ref_find_elt(ref, key) == NULL)
1706 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001707 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001708 return 0;
1709}
1710
1711/* This function is an LUA binding. It provides a function
1712 * for setting map pattern and sample from a referenced map
1713 * file.
1714 */
1715static int hlua_set_map(lua_State *L)
1716{
1717 const char *name;
1718 const char *key;
1719 const char *value;
1720 struct pat_ref *ref;
1721
1722 MAY_LJMP(check_args(L, 3, "set_map"));
1723
1724 name = MAY_LJMP(luaL_checkstring(L, 1));
1725 key = MAY_LJMP(luaL_checkstring(L, 2));
1726 value = MAY_LJMP(luaL_checkstring(L, 3));
1727
1728 ref = pat_ref_lookup(name);
1729 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001730 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001731
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001732 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001733 if (pat_ref_find_elt(ref, key) != NULL)
1734 pat_ref_set(ref, key, value, NULL);
1735 else
1736 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001737 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001738 return 0;
1739}
1740
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001741/* A class is a lot of memory that contain data. This data can be a table,
1742 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001743 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001744 * the name of the object (_G[<name>] = <metable> ).
1745 *
1746 * A metable is a table that modify the standard behavior of a standard
1747 * access to the associated data. The entries of this new metatable are
1748 * defined as is:
1749 *
1750 * http://lua-users.org/wiki/MetatableEvents
1751 *
1752 * __index
1753 *
1754 * we access an absent field in a table, the result is nil. This is
1755 * true, but it is not the whole truth. Actually, such access triggers
1756 * the interpreter to look for an __index metamethod: If there is no
1757 * such method, as usually happens, then the access results in nil;
1758 * otherwise, the metamethod will provide the result.
1759 *
1760 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1761 * the key does not appear in the table, but the metatable has an __index
1762 * property:
1763 *
1764 * - if the value is a function, the function is called, passing in the
1765 * table and the key; the return value of that function is returned as
1766 * the result.
1767 *
1768 * - if the value is another table, the value of the key in that table is
1769 * asked for and returned (and if it doesn't exist in that table, but that
1770 * table's metatable has an __index property, then it continues on up)
1771 *
1772 * - Use "rawget(myTable,key)" to skip this metamethod.
1773 *
1774 * http://www.lua.org/pil/13.4.1.html
1775 *
1776 * __newindex
1777 *
1778 * Like __index, but control property assignment.
1779 *
1780 * __mode - Control weak references. A string value with one or both
1781 * of the characters 'k' and 'v' which specifies that the the
1782 * keys and/or values in the table are weak references.
1783 *
1784 * __call - Treat a table like a function. When a table is followed by
1785 * parenthesis such as "myTable( 'foo' )" and the metatable has
1786 * a __call key pointing to a function, that function is invoked
1787 * (passing any specified arguments) and the return value is
1788 * returned.
1789 *
1790 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1791 * called, if the metatable for myTable has a __metatable
1792 * key, the value of that key is returned instead of the
1793 * actual metatable.
1794 *
1795 * __tostring - Control string representation. When the builtin
1796 * "tostring( myTable )" function is called, if the metatable
1797 * for myTable has a __tostring property set to a function,
1798 * that function is invoked (passing myTable to it) and the
1799 * return value is used as the string representation.
1800 *
1801 * __len - Control table length. When the table length is requested using
1802 * the length operator ( '#' ), if the metatable for myTable has
1803 * a __len key pointing to a function, that function is invoked
1804 * (passing myTable to it) and the return value used as the value
1805 * of "#myTable".
1806 *
1807 * __gc - Userdata finalizer code. When userdata is set to be garbage
1808 * collected, if the metatable has a __gc field pointing to a
1809 * function, that function is first invoked, passing the userdata
1810 * to it. The __gc metamethod is not called for tables.
1811 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1812 *
1813 * Special metamethods for redefining standard operators:
1814 * http://www.lua.org/pil/13.1.html
1815 *
1816 * __add "+"
1817 * __sub "-"
1818 * __mul "*"
1819 * __div "/"
1820 * __unm "!"
1821 * __pow "^"
1822 * __concat ".."
1823 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001824 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001825 * http://www.lua.org/pil/13.2.html
1826 *
1827 * __eq "=="
1828 * __lt "<"
1829 * __le "<="
1830 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831
1832/*
1833 *
1834 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001835 * Class Map
1836 *
1837 *
1838 */
1839
1840/* Returns a struct hlua_map if the stack entry "ud" is
1841 * a class session, otherwise it throws an error.
1842 */
1843__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1844{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001845 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001846}
1847
1848/* This function is the map constructor. It don't need
1849 * the class Map object. It creates and return a new Map
1850 * object. It must be called only during "body" or "init"
1851 * context because it process some filesystem accesses.
1852 */
1853__LJMP static int hlua_map_new(struct lua_State *L)
1854{
1855 const char *fn;
1856 int match = PAT_MATCH_STR;
1857 struct sample_conv conv;
1858 const char *file = "";
1859 int line = 0;
1860 lua_Debug ar;
1861 char *err = NULL;
1862 struct arg args[2];
1863
1864 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1865 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1866
1867 fn = MAY_LJMP(luaL_checkstring(L, 1));
1868
1869 if (lua_gettop(L) >= 2) {
1870 match = MAY_LJMP(luaL_checkinteger(L, 2));
1871 if (match < 0 || match >= PAT_MATCH_NUM)
1872 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1873 }
1874
1875 /* Get Lua filename and line number. */
1876 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1877 lua_getinfo(L, "Sl", &ar); /* get info about it */
1878 if (ar.currentline > 0) { /* is there info? */
1879 file = ar.short_src;
1880 line = ar.currentline;
1881 }
1882 }
1883
1884 /* fill fake sample_conv struct. */
1885 conv.kw = ""; /* unused. */
1886 conv.process = NULL; /* unused. */
1887 conv.arg_mask = 0; /* unused. */
1888 conv.val_args = NULL; /* unused. */
1889 conv.out_type = SMP_T_STR;
1890 conv.private = (void *)(long)match;
1891 switch (match) {
1892 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1893 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1894 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1895 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1896 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1897 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1898 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001899 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001900 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1901 default:
1902 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1903 }
1904
1905 /* fill fake args. */
1906 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001907 args[0].data.str.area = strdup(fn);
1908 args[0].data.str.data = strlen(fn);
1909 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001910 args[1].type = ARGT_STOP;
1911
1912 /* load the map. */
1913 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001914 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001915 * free the err variable.
1916 */
1917 luaL_where(L, 1);
1918 lua_pushfstring(L, "'new': %s.", err);
1919 lua_concat(L, 2);
1920 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001921 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001922 WILL_LJMP(lua_error(L));
1923 }
1924
1925 /* create the lua object. */
1926 lua_newtable(L);
1927 lua_pushlightuserdata(L, args[0].data.map);
1928 lua_rawseti(L, -2, 0);
1929
1930 /* Pop a class Map metatable and affect it to the userdata. */
1931 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1932 lua_setmetatable(L, -2);
1933
1934
1935 return 1;
1936}
1937
1938__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1939{
1940 struct map_descriptor *desc;
1941 struct pattern *pat;
1942 struct sample smp;
1943
1944 MAY_LJMP(check_args(L, 2, "lookup"));
1945 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001946 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001947 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001948 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001949 }
1950 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001951 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001952 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001953 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 +01001954 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001955 }
1956
1957 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001958 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001959 if (str)
1960 lua_pushstring(L, "");
1961 else
1962 lua_pushnil(L);
1963 return 1;
1964 }
1965
1966 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001967 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001968 return 1;
1969}
1970
1971__LJMP static int hlua_map_lookup(struct lua_State *L)
1972{
1973 return _hlua_map_lookup(L, 0);
1974}
1975
1976__LJMP static int hlua_map_slookup(struct lua_State *L)
1977{
1978 return _hlua_map_lookup(L, 1);
1979}
1980
1981/*
1982 *
1983 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 * Class Socket
1985 *
1986 *
1987 */
1988
1989__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1990{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001991 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992}
1993
1994/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001995 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996 * received.
1997 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001998static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999{
Willy Tarreau5321da92022-05-06 11:57:34 +02002000 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002001 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002
Christopher Faulet31572222023-03-31 11:13:48 +02002003 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
2004 notification_wake(&ctx->wake_on_read);
2005 notification_wake(&ctx->wake_on_write);
2006 return;
2007 }
2008
Willy Tarreau5321da92022-05-06 11:57:34 +02002009 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002010 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002011 notification_wake(&ctx->wake_on_read);
2012 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002013 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002014 }
2015
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002016 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002017 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002018 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002019
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002020 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002021 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002022 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002023
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002024 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002025 * to be notified whenever the connection completes.
2026 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002027 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002028 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002029 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002030 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002031 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002032 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002033
2034 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002035 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002036
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002037 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002038 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002039 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002040
2041 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002042 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002043 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002044
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002045 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002046 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002047 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002048 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002049 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002050}
2051
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002052static int hlua_socket_init(struct appctx *appctx)
2053{
2054 struct hlua_csk_ctx *ctx = appctx->svcctx;
2055 struct stream *s;
2056
2057 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2058 goto error;
2059
2060 s = appctx_strm(appctx);
2061
Willy Tarreau4596fe22022-05-17 19:07:51 +02002062 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002063 * and retrieve data from the server. The connection is initialized
2064 * with the "struct server".
2065 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002066 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002067
2068 /* Force destination server. */
2069 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2070 s->target = &socket_tcp->obj_type;
2071
2072 ctx->appctx = appctx;
2073 return 0;
2074
2075 error:
2076 return -1;
2077}
2078
Willy Tarreau87b09662015-04-03 00:22:06 +02002079/* This function is called when the "struct stream" is destroyed.
2080 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081 * Wake all the pending signals.
2082 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002083static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084{
Willy Tarreau5321da92022-05-06 11:57:34 +02002085 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002086 struct xref *peer;
2087
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002088 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002089 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002090 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002091 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002092
2093 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002094 notification_wake(&ctx->wake_on_read);
2095 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002096}
2097
2098/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002099 * uses this object. If the stream does not exists, just quit.
2100 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101 * pending signal can rest in the read and write lists. destroy
2102 * it.
2103 */
2104__LJMP static int hlua_socket_gc(lua_State *L)
2105{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002106 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002107 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002108 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002109
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002110 MAY_LJMP(check_args(L, 1, "__gc"));
2111
2112 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002113 peer = xref_get_peer_and_lock(&socket->xref);
2114 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002115 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002116
2117 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002119 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002120 ctx->die = 1;
2121 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002123 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002124 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002125 return 0;
2126}
2127
2128/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002129 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130 */
sada05ed3302018-05-11 11:48:18 -07002131__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002132{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002133 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002134 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002135 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002136 struct hlua *hlua;
2137
2138 /* Get hlua struct, or NULL if we execute from main lua state */
2139 hlua = hlua_gethlua(L);
2140 if (!hlua)
2141 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002143 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002144
2145 /* Check if we run on the same thread than the xreator thread.
2146 * We cannot access to the socket if the thread is different.
2147 */
2148 if (socket->tid != tid)
2149 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2150
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002151 peer = xref_get_peer_and_lock(&socket->xref);
2152 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002153 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002154
2155 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002156 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002158 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002159 ctx->die = 1;
2160 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002162 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002163 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 return 0;
2165}
2166
sada05ed3302018-05-11 11:48:18 -07002167/* The close function calls close_helper.
2168 */
2169__LJMP static int hlua_socket_close(lua_State *L)
2170{
2171 MAY_LJMP(check_args(L, 1, "close"));
2172 return hlua_socket_close_helper(L);
2173}
2174
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175/* This Lua function assumes that the stack contain three parameters.
2176 * 1 - USERDATA containing a struct socket
2177 * 2 - INTEGER with values of the macro defined below
2178 * If the integer is -1, we must read at most one line.
2179 * If the integer is -2, we ust read all the data until the
2180 * end of the stream.
2181 * If the integer is positive value, we must read a number of
2182 * bytes corresponding to this value.
2183 */
2184#define HLSR_READ_LINE (-1)
2185#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002186__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187{
2188 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2189 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002190 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002191 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002193 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002195 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002196 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002197 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002198 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002199 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002200 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002201 struct stream *s;
2202 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002203 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002205 /* Get hlua struct, or NULL if we execute from main lua state */
2206 hlua = hlua_gethlua(L);
2207
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208 /* Check if this lua stack is schedulable. */
2209 if (!hlua || !hlua->task)
2210 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2211 "'frontend', 'backend' or 'task'"));
2212
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002213 /* Check if we run on the same thread than the xreator thread.
2214 * We cannot access to the socket if the thread is different.
2215 */
2216 if (socket->tid != tid)
2217 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2218
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002219 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002220 peer = xref_get_peer_and_lock(&socket->xref);
2221 if (!peer)
2222 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002223
2224 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2225 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002226 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002228 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002231 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002232 if (nblk < 0) /* Connection close. */
2233 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002234 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002236
2237 /* remove final \r\n. */
2238 if (nblk == 1) {
2239 if (blk1[len1-1] == '\n') {
2240 len1--;
2241 skip_at_end++;
2242 if (blk1[len1-1] == '\r') {
2243 len1--;
2244 skip_at_end++;
2245 }
2246 }
2247 }
2248 else {
2249 if (blk2[len2-1] == '\n') {
2250 len2--;
2251 skip_at_end++;
2252 if (blk2[len2-1] == '\r') {
2253 len2--;
2254 skip_at_end++;
2255 }
2256 }
2257 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258 }
2259
2260 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002262 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263 if (nblk < 0) /* Connection close. */
2264 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002265 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266 goto connection_empty;
2267 }
2268
2269 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002271 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002272 if (nblk < 0) /* Connection close. */
2273 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002274 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 goto connection_empty;
2276
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002277 missing_bytes = wanted - socket->b.n;
2278 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002280 len1 = missing_bytes;
2281 } if (nblk == 2 && len1 + len2 > missing_bytes)
2282 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283 }
2284
2285 len = len1;
2286
2287 luaL_addlstring(&socket->b, blk1, len1);
2288 if (nblk == 2) {
2289 len += len2;
2290 luaL_addlstring(&socket->b, blk2, len2);
2291 }
2292
2293 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002294 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295
2296 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002297 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298
2299 /* If the pattern reclaim to read all the data
2300 * in the connection, got out.
2301 */
2302 if (wanted == HLSR_READ_ALL)
2303 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002304 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305 goto connection_empty;
2306
2307 /* Return result. */
2308 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002309 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 return 1;
2311
2312connection_closed:
2313
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002314 xref_unlock(&socket->xref, peer);
2315
2316no_peer:
2317
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318 /* If the buffer containds data. */
2319 if (socket->b.n > 0) {
2320 luaL_pushresult(&socket->b);
2321 return 1;
2322 }
2323 lua_pushnil(L);
2324 lua_pushstring(L, "connection closed.");
2325 return 2;
2326
2327connection_empty:
2328
Willy Tarreau5321da92022-05-06 11:57:34 +02002329 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002330 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002332 }
2333 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002334 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335 return 0;
2336}
2337
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002338/* This Lua function gets two parameters. The first one can be string
2339 * or a number. If the string is "*l", the user requires one line. If
2340 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341 * If the value is a number, the user require a number of bytes equal
2342 * to the value. The default value is "*l" (a line).
2343 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002344 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 * integer takes this values:
2346 * -1 : read a line
2347 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002348 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002350 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 * concatenated with the read data.
2352 */
2353__LJMP static int hlua_socket_receive(struct lua_State *L)
2354{
2355 int wanted = HLSR_READ_LINE;
2356 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002357 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 char *error;
2359 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002360 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361
2362 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2363 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2364
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002365 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002367 /* Check if we run on the same thread than the xreator thread.
2368 * We cannot access to the socket if the thread is different.
2369 */
2370 if (socket->tid != tid)
2371 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2372
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 /* check for pattern. */
2374 if (lua_gettop(L) >= 2) {
2375 type = lua_type(L, 2);
2376 if (type == LUA_TSTRING) {
2377 pattern = lua_tostring(L, 2);
2378 if (strcmp(pattern, "*a") == 0)
2379 wanted = HLSR_READ_ALL;
2380 else if (strcmp(pattern, "*l") == 0)
2381 wanted = HLSR_READ_LINE;
2382 else {
2383 wanted = strtoll(pattern, &error, 10);
2384 if (*error != '\0')
2385 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2386 }
2387 }
2388 else if (type == LUA_TNUMBER) {
2389 wanted = lua_tointeger(L, 2);
2390 if (wanted < 0)
2391 WILL_LJMP(luaL_error(L, "Unsupported size."));
2392 }
2393 }
2394
2395 /* Set pattern. */
2396 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002397
2398 /* Check if we would replace the top by itself. */
2399 if (lua_gettop(L) != 2)
2400 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002401
Christopher Fauletc31b2002021-05-03 10:11:13 +02002402 /* Save index of the top of the stack because since buffers are used, it
2403 * may change
2404 */
2405 lastarg = lua_gettop(L);
2406
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002407 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408 luaL_buffinit(L, &socket->b);
2409
2410 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002411 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 if (lua_type(L, 3) != LUA_TSTRING)
2413 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2414 pattern = lua_tolstring(L, 3, &len);
2415 luaL_addlstring(&socket->b, pattern, len);
2416 }
2417
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002418 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419}
2420
2421/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002422 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002423 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002424static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002425{
2426 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002427 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002428 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002429 struct appctx *appctx;
2430 size_t buf_len;
2431 const char *buf;
2432 int len;
2433 int send_len;
2434 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002435 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002436 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002437 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002439 /* Get hlua struct, or NULL if we execute from main lua state */
2440 hlua = hlua_gethlua(L);
2441
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002442 /* Check if this lua stack is schedulable. */
2443 if (!hlua || !hlua->task)
2444 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2445 "'frontend', 'backend' or 'task'"));
2446
2447 /* Get object */
2448 socket = MAY_LJMP(hlua_checksocket(L, 1));
2449 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002450 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002452 /* Check if we run on the same thread than the xreator thread.
2453 * We cannot access to the socket if the thread is different.
2454 */
2455 if (socket->tid != tid)
2456 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2457
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002458 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002459 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002460 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002461 lua_pushinteger(L, -1);
2462 return 1;
2463 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002464
2465 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2466 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002467 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002468 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002469
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002471 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002472 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002473 lua_pushinteger(L, -1);
2474 return 1;
2475 }
2476
2477 /* Update the input buffer data. */
2478 buf += sent;
2479 send_len = buf_len - sent;
2480
2481 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002482 if (sent >= buf_len) {
2483 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002484 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002485 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002487 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002488 * the request buffer if its not required.
2489 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002490 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002491 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002492 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002493 }
2494
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002495 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002496 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002497 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002498 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002499 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500
2501 /* send data */
2502 if (len < send_len)
2503 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002504 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505
2506 /* "Not enough space" (-1), "Buffer too little to contain
2507 * the data" (-2) are not expected because the available length
2508 * is tested.
2509 * Other unknown error are also not expected.
2510 */
2511 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002512 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002513 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002514
sada05ed3302018-05-11 11:48:18 -07002515 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002517 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002518 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519 return 1;
2520 }
2521
2522 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002523 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002524
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 /* Update length sent. */
2526 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002527 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528
2529 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002530 if (sent + len >= buf_len) {
2531 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002532 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002533 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002534
2535hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002536 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002537 xref_unlock(&socket->xref, peer);
2538 WILL_LJMP(luaL_error(L, "out of memory"));
2539 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002540 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002541 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542 return 0;
2543}
2544
2545/* This function initiate the send of data. It just check the input
2546 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002547 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002548 * "hlua_socket_write_yield" that can yield.
2549 *
2550 * The Lua function gets between 3 and 4 parameters. The first one is
2551 * the associated object. The second is a string buffer. The third is
2552 * a facultative integer that represents where is the buffer position
2553 * of the start of the data that can send. The first byte is the
2554 * position "1". The default value is "1". The fourth argument is a
2555 * facultative integer that represents where is the buffer position
2556 * of the end of the data that can send. The default is the last byte.
2557 */
2558static int hlua_socket_send(struct lua_State *L)
2559{
2560 int i;
2561 int j;
2562 const char *buf;
2563 size_t buf_len;
2564
2565 /* Check number of arguments. */
2566 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2567 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2568
2569 /* Get the string. */
2570 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2571
2572 /* Get and check j. */
2573 if (lua_gettop(L) == 4) {
2574 j = MAY_LJMP(luaL_checkinteger(L, 4));
2575 if (j < 0)
2576 j = buf_len + j + 1;
2577 if (j > buf_len)
2578 j = buf_len + 1;
2579 lua_pop(L, 1);
2580 }
2581 else
2582 j = buf_len;
2583
2584 /* Get and check i. */
2585 if (lua_gettop(L) == 3) {
2586 i = MAY_LJMP(luaL_checkinteger(L, 3));
2587 if (i < 0)
2588 i = buf_len + i + 1;
2589 if (i > buf_len)
2590 i = buf_len + 1;
2591 lua_pop(L, 1);
2592 } else
2593 i = 1;
2594
2595 /* Check bth i and j. */
2596 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002597 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598 return 1;
2599 }
2600 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002601 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002602 return 1;
2603 }
2604 if (i == 0)
2605 i = 1;
2606 if (j == 0)
2607 j = 1;
2608
2609 /* Pop the string. */
2610 lua_pop(L, 1);
2611
2612 /* Update the buffer length. */
2613 buf += i - 1;
2614 buf_len = j - i + 1;
2615 lua_pushlstring(L, buf, buf_len);
2616
2617 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002618 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002620 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002621}
2622
Willy Tarreau22b0a682015-06-17 19:43:49 +02002623#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002624__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002625{
2626 static char buffer[SOCKET_INFO_MAX_LEN];
2627 int ret;
2628 int len;
2629 char *p;
2630
2631 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2632 if (ret <= 0) {
2633 lua_pushnil(L);
2634 return 1;
2635 }
2636
2637 if (ret == AF_UNIX) {
2638 lua_pushstring(L, buffer+1);
2639 return 1;
2640 }
2641 else if (ret == AF_INET6) {
2642 buffer[0] = '[';
2643 len = strlen(buffer);
2644 buffer[len] = ']';
2645 len++;
2646 buffer[len] = ':';
2647 len++;
2648 p = buffer;
2649 }
2650 else if (ret == AF_INET) {
2651 p = buffer + 1;
2652 len = strlen(p);
2653 p[len] = ':';
2654 len++;
2655 }
2656 else {
2657 lua_pushnil(L);
2658 return 1;
2659 }
2660
2661 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2662 lua_pushnil(L);
2663 return 1;
2664 }
2665
2666 lua_pushstring(L, p);
2667 return 1;
2668}
2669
2670/* Returns information about the peer of the connection. */
2671__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2672{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002673 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002674 struct xref *peer;
2675 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002676 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002677 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002678 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002679
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680 MAY_LJMP(check_args(L, 1, "getpeername"));
2681
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002682 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002683
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002684 /* Check if we run on the same thread than the xreator thread.
2685 * We cannot access to the socket if the thread is different.
2686 */
2687 if (socket->tid != tid)
2688 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2689
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002690 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002691 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002692 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002693 lua_pushnil(L);
2694 return 1;
2695 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002696
2697 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002698 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002699 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002700 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002701 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002702 lua_pushnil(L);
2703 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002704 }
2705
Christopher Faulet16f16af2021-10-27 09:34:56 +02002706 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002707 xref_unlock(&socket->xref, peer);
2708 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002709}
2710
2711/* Returns information about my connection side. */
2712static int hlua_socket_getsockname(struct lua_State *L)
2713{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002714 struct hlua_socket *socket;
2715 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002716 struct appctx *appctx;
2717 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002718 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002719 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002720
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002721 MAY_LJMP(check_args(L, 1, "getsockname"));
2722
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002723 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002724
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002725 /* Check if we run on the same thread than the xreator thread.
2726 * We cannot access to the socket if the thread is different.
2727 */
2728 if (socket->tid != tid)
2729 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2730
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002731 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002732 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002733 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002734 lua_pushnil(L);
2735 return 1;
2736 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002737
2738 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002739 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002740
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002741 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002742 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002743 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002744 lua_pushnil(L);
2745 return 1;
2746 }
2747
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002748 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002749 xref_unlock(&socket->xref, peer);
2750 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002751}
2752
2753/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002754static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002755 .obj_type = OBJ_TYPE_APPLET,
2756 .name = "<LUA_TCP>",
2757 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002758 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002759 .release = hlua_socket_release,
2760};
2761
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002762__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002763{
2764 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002765 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002766 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002767 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002768 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002769 struct stream *s;
2770
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002771 /* Get hlua struct, or NULL if we execute from main lua state */
2772 hlua = hlua_gethlua(L);
2773 if (!hlua)
2774 return 0;
2775
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002776 /* Check if we run on the same thread than the xreator thread.
2777 * We cannot access to the socket if the thread is different.
2778 */
2779 if (socket->tid != tid)
2780 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2781
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002782 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002783 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002784 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002785 lua_pushnil(L);
2786 lua_pushstring(L, "Can't connect");
2787 return 2;
2788 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002789
2790 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2791 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002792 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002793
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002794 /* Check if we run on the same thread than the xreator thread.
2795 * We cannot access to the socket if the thread is different.
2796 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002797 if (socket->tid != tid) {
2798 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002799 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002800 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002801
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002802 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002803 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002804 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002805 lua_pushnil(L);
2806 lua_pushstring(L, "Can't connect");
2807 return 2;
2808 }
2809
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002810 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002811
2812 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002813 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002814 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002815 lua_pushinteger(L, 1);
2816 return 1;
2817 }
2818
Willy Tarreau5321da92022-05-06 11:57:34 +02002819 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002820 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002821 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002822 }
2823 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002824 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002825 return 0;
2826}
2827
2828/* This function fail or initite the connection. */
2829__LJMP static int hlua_socket_connect(struct lua_State *L)
2830{
2831 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002832 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002833 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002834 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002835 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002836 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002837 int low, high;
2838 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002839 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002840 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002841 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002842
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002843 if (lua_gettop(L) < 2)
2844 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002845
2846 /* Get args. */
2847 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002848
2849 /* Check if we run on the same thread than the xreator thread.
2850 * We cannot access to the socket if the thread is different.
2851 */
2852 if (socket->tid != tid)
2853 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2854
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002855 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002856 if (lua_gettop(L) >= 3) {
2857 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002858 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002859
Tim Duesterhus6edab862018-01-06 19:04:45 +01002860 /* Force the ip to end with a colon, to support IPv6 addresses
2861 * that are not enclosed within square brackets.
2862 */
2863 if (port > 0) {
2864 luaL_buffinit(L, &b);
2865 luaL_addstring(&b, ip);
2866 luaL_addchar(&b, ':');
2867 luaL_pushresult(&b);
2868 ip = lua_tolstring(L, lua_gettop(L), NULL);
2869 }
2870 }
2871
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002872 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002873 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002874 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002875 lua_pushnil(L);
2876 return 1;
2877 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002878
2879 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002880 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 +02002881 if (!addr) {
2882 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002883 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002884 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002885
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002886 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002887 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002888 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002889 if (port == -1) {
2890 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002891 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002892 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002893 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2894 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002895 if (port == -1) {
2896 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002897 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002898 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002899 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002900 }
2901 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002902
Willy Tarreau5321da92022-05-06 11:57:34 +02002903 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2904 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002905 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002906 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002907
Willy Tarreau3e7be362022-05-27 10:35:27 +02002908 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002909 xref_unlock(&socket->xref, peer);
2910 WILL_LJMP(luaL_error(L, "connect: internal error"));
2911 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002912
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002913 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002914 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002915 if (!hlua)
2916 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002917
2918 /* inform the stream that we want to be notified whenever the
2919 * connection completes.
2920 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002921 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002922 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002923 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002924
Willy Tarreauf31af932020-01-14 09:59:38 +01002925 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002926
Willy Tarreau5321da92022-05-06 11:57:34 +02002927 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002928 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002929 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002930 }
2931 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002932
2933 task_wakeup(s->task, TASK_WOKEN_INIT);
2934 /* Return yield waiting for connection. */
2935
Willy Tarreau9635e032018-10-16 17:52:55 +02002936 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002937
2938 return 0;
2939}
2940
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002941#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002942__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2943{
2944 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002945 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002946 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002947
2948 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2949 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002950
2951 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002952 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002953 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002954 lua_pushnil(L);
2955 return 1;
2956 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002957
Willy Tarreau0698c802022-05-11 14:09:57 +02002958 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002959
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002960 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002961 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002962 return MAY_LJMP(hlua_socket_connect(L));
2963}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002964#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002965
2966__LJMP static int hlua_socket_setoption(struct lua_State *L)
2967{
2968 return 0;
2969}
2970
2971__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2972{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002973 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002974 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002975 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002976 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002977 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002978
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002979 MAY_LJMP(check_args(L, 2, "settimeout"));
2980
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002981 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002982
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002983 /* convert the timeout to millis */
2984 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002985
Thierry Fournier17a921b2018-03-08 09:59:02 +01002986 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002987 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002988 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2989
Mark Lakes56cc1252018-03-27 09:48:06 +02002990 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002991 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002992
2993 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002994 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002995 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002996
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002997 /* Check if we run on the same thread than the xreator thread.
2998 * We cannot access to the socket if the thread is different.
2999 */
3000 if (socket->tid != tid)
3001 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3002
Mark Lakes56cc1252018-03-27 09:48:06 +02003003 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003004 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003005 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003006 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3007 WILL_LJMP(lua_error(L));
3008 return 0;
3009 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003010
Willy Tarreau0698c802022-05-11 14:09:57 +02003011 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003012
Cyril Bonté7bb63452018-08-17 23:51:02 +02003013 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003014 s->scf->ioto = tmout;
3015 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003016
3017 s->task->expire = tick_add_ifset(now_ms, tmout);
3018 task_queue(s->task);
3019
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003020 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021
Thierry Fourniere9636f12018-03-08 09:54:32 +01003022 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003023 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003024}
3025
3026__LJMP static int hlua_socket_new(lua_State *L)
3027{
3028 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003029 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003030 struct appctx *appctx;
3031
3032 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003033 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003034 hlua_pusherror(L, "socket: full stack");
3035 goto out_fail_conf;
3036 }
3037
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003038 /* Create the object: obj[0] = userdata. */
3039 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003040 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003041 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003042 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003043 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003044
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003045 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003046 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003047 hlua_pusherror(L, "socket: uninitialized pools.");
3048 goto out_fail_conf;
3049 }
3050
Willy Tarreau87b09662015-04-03 00:22:06 +02003051 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003052 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3053 lua_setmetatable(L, -2);
3054
Willy Tarreaud420a972015-04-06 00:39:18 +02003055 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003056 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003057 if (!appctx) {
3058 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003059 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003060 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003061 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3062 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003063 ctx->die = 0;
3064 LIST_INIT(&ctx->wake_on_write);
3065 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003066
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003067 if (appctx_init(appctx) == -1) {
3068 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003069 goto out_fail_appctx;
3070 }
3071
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003072 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003073 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003074 return 1;
3075
Christopher Faulet13a35e52021-12-20 15:34:16 +01003076 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003077 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003078 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003079 WILL_LJMP(lua_error(L));
3080 return 0;
3081}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003082
3083/*
3084 *
3085 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003086 * Class Channel
3087 *
3088 *
3089 */
3090
3091/* Returns the struct hlua_channel join to the class channel in the
3092 * stack entry "ud" or throws an argument error.
3093 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003094__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003095{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003096 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097}
3098
Willy Tarreau47860ed2015-03-10 14:07:50 +01003099/* Pushes the channel onto the top of the stack. If the stask does not have a
3100 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003102static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003103{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003104 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003105 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003106 return 0;
3107
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003108 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003109 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003110 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003111
3112 /* Pop a class sesison metatable and affect it to the userdata. */
3113 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3114 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003115 return 1;
3116}
3117
Christopher Faulet9f55a502020-02-25 15:21:02 +01003118/* Helper function returning a filter attached to a channel at the position <ud>
3119 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003120 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003121 * initialized.
3122 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003123static 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 +01003124{
3125 struct filter *filter = NULL;
3126
3127 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3128 struct hlua_flt_ctx *flt_ctx;
3129
3130 filter = lua_touserdata (L, -1);
3131 flt_ctx = filter->ctx;
3132 if (hlua_filter_from_payload(filter)) {
3133 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3134 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3135 }
3136 }
3137
3138 lua_pop(L, 1);
3139 return filter;
3140}
3141
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003142/* Copies <len> bytes of data present in the channel's buffer, starting at the
3143* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003144* responsibility to ensure <len> and <offset> are valid. It always return the
3145* length of the built string. <len> may be 0, in this case, an empty string is
3146* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003147*/
3148static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003149{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003150 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003151 luaL_Buffer b;
3152
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003153 block1 = len;
3154 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3155 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3156 block2 = len - block1;
3157
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003158 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003159 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3160 if (block2)
3161 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003162 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003163 return len;
3164}
3165
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003166/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3167 * function returns -1 if data cannot be copied. Otherwise, it returns the
3168 * number of bytes copied.
3169 */
3170static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3171{
3172 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003173
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003174 /* Nothing to do, just return */
3175 if (unlikely(istlen(str) == 0))
3176 goto end;
3177
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003178 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003179 ret = -1;
3180 goto end;
3181 }
3182 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3183
3184 end:
3185 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003186}
3187
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003188/* Removes <len> bytes of data at the absolute position <offset>.
3189 */
3190static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3191{
3192 size_t end = offset + len;
3193
3194 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3195 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3196 b_data(&chn->buf) - end, -len);
3197 b_sub(&chn->buf, len);
3198}
3199
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003200/* Copies input data in the channel's buffer. It is possible to set a specific
3201 * offset (0 by default) and a length (all remaining input data starting for the
3202 * offset by default). If there is not enough input data and more data can be
3203 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003204 *
3205 * From an action, All input data are considered. For a filter, the offset and
3206 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003207 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003208__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003209{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003210 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003211 struct filter *filter;
3212 size_t input, output;
3213 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003214
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003215 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003216
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003217 output = co_data(chn);
3218 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003219
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003220 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3221 if (filter && !hlua_filter_from_payload(filter))
3222 WILL_LJMP(lua_error(L));
3223
3224 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003225 if (lua_gettop(L) > 1) {
3226 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3227 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003228 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003229 offset += output;
3230 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003231 lua_pushfstring(L, "offset out of range.");
3232 WILL_LJMP(lua_error(L));
3233 }
3234 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003235 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003236 if (lua_gettop(L) == 3) {
3237 len = MAY_LJMP(luaL_checkinteger(L, 3));
3238 if (!len)
3239 goto dup;
3240 if (len == -1)
3241 len = global.tune.bufsize;
3242 if (len < 0) {
3243 lua_pushfstring(L, "length out of range.");
3244 WILL_LJMP(lua_error(L));
3245 }
3246 }
3247
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003248 /* Wait for more data if possible if no length was specified and there
3249 * is no data or not enough data was received.
3250 */
3251 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003252 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3253 /* Yield waiting for more data, as requested */
3254 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3255 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003256
3257 /* Return 'nil' if there is no data and the channel can't receive more data */
3258 if (!len) {
3259 lua_pushnil(L);
3260 return -1;
3261 }
3262
3263 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003264 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003265 }
3266
3267 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003268 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003269 return 1;
3270}
3271
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003272/* Copies the first line (including the trailing LF) of input data in the
3273 * channel's buffer. It is possible to set a specific offset (0 by default) and
3274 * a length (all remaining input data starting for the offset by default). If
3275 * there is not enough input data and more data can be received, the function
3276 * yields. If a length is explicitly specified, no more data are
3277 * copied. Otherwise, if no LF is found and more data can be received, this
3278 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003279 *
3280 * From an action, All input data are considered. For a filter, the offset and
3281 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003282 */
3283__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003284{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003285 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003286 struct filter *filter;
3287 size_t l, input, output;
3288 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003289
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003290 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003291 output = co_data(chn);
3292 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003293
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003294 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3295 if (filter && !hlua_filter_from_payload(filter))
3296 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003297
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003298 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003299 if (lua_gettop(L) > 1) {
3300 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3301 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003302 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003303 offset += output;
3304 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003305 lua_pushfstring(L, "offset out of range.");
3306 WILL_LJMP(lua_error(L));
3307 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003308 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003309
3310 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003311 if (lua_gettop(L) == 3) {
3312 len = MAY_LJMP(luaL_checkinteger(L, 3));
3313 if (!len)
3314 goto dup;
3315 if (len == -1)
3316 len = global.tune.bufsize;
3317 if (len < 0) {
3318 lua_pushfstring(L, "length out of range.");
3319 WILL_LJMP(lua_error(L));
3320 }
3321 }
3322
3323 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003324 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003325 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003326 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003327 len = l+1;
3328 goto dup;
3329 }
3330 }
3331
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003332 /* Wait for more data if possible if no line is found and no length was
3333 * specified or not enough data was received.
3334 */
3335 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003336 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3337 /* Yield waiting for more data */
3338 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3339 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003340
3341 /* Return 'nil' if there is no data and the channel can't receive more data */
3342 if (!len) {
3343 lua_pushnil(L);
3344 return -1;
3345 }
3346
3347 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003348 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003349 }
3350
3351 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003352 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354}
3355
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003356/* [ DEPRECATED ]
3357 *
3358 * Duplicate all input data foud in the channel's buffer. The data are not
3359 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003360 *
3361 * From an action, All input data are considered. For a filter, the offset and
3362 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003363 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003364__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003365{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003366 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003367 struct filter *filter;
3368 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003369
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003370 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003371 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003372 if (IS_HTX_STRM(chn_strm(chn))) {
3373 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3374 WILL_LJMP(lua_error(L));
3375 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003376
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003377 offset = co_data(chn);
3378 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003379
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003380 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3381 if (filter && !hlua_filter_from_payload(filter))
3382 WILL_LJMP(lua_error(L));
3383
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003384 if (!ci_data(chn) && channel_input_closed(chn)) {
3385 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003386 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003387 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003388
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003389 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003390 return 1;
3391}
3392
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003393/* [ DEPRECATED ]
3394 *
3395 * Get all input data foud in the channel's buffer. The data are removed from
3396 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3397 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003398 *
3399 * From an action, All input data are considered. For a filter, the offset and
3400 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003401 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003402__LJMP static int hlua_channel_get(lua_State *L)
3403{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003404 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003405 struct filter *filter;
3406 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003407 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003408
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003409 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003410 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3411 if (IS_HTX_STRM(chn_strm(chn))) {
3412 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3413 WILL_LJMP(lua_error(L));
3414 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003415
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003416 offset = co_data(chn);
3417 len = ci_data(chn);
3418
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003419 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3420 if (filter && !hlua_filter_from_payload(filter))
3421 WILL_LJMP(lua_error(L));
3422
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003423 if (!ci_data(chn) && channel_input_closed(chn)) {
3424 lua_pushnil(L);
3425 return 1;
3426 }
3427
3428 ret = _hlua_channel_dup(chn, L, offset, len);
3429 _hlua_channel_delete(chn, offset, ret);
3430 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003431}
3432
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003433/* This functions consumes and returns one line. If the channel is closed,
3434 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003435 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003436 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003437 *
3438 * From an action, All input data are considered. For a filter, the offset and
3439 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003440 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003441__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003442{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003443 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003444 struct filter *filter;
3445 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003446 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003447
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003448 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003449
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003450 offset = co_data(chn);
3451 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003452
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003453 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3454 if (filter && !hlua_filter_from_payload(filter))
3455 WILL_LJMP(lua_error(L));
3456
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003457 if (!ci_data(chn) && channel_input_closed(chn)) {
3458 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003459 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003460 }
3461
3462 for (l = 0; l < len; l++) {
3463 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3464 len = l+1;
3465 goto dup;
3466 }
3467 }
3468
3469 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3470 /* Yield waiting for more data */
3471 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3472 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003473
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003474 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003475 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003476 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003477 return 1;
3478}
3479
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003480/* [ DEPRECATED ]
3481 *
3482 * Check arguments for the function "hlua_channel_getline_yield".
3483 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003484__LJMP static int hlua_channel_getline(lua_State *L)
3485{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003486 struct channel *chn;
3487
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003488 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003489 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3490 if (IS_HTX_STRM(chn_strm(chn))) {
3491 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3492 WILL_LJMP(lua_error(L));
3493 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003494 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3495}
3496
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003497/* Retrieves a given amount of input data at the given offset. By default all
3498 * available input data are returned. The offset may be negactive to start from
3499 * the end of input data. The length may be -1 to set it to the maximum buffer
3500 * size.
3501 */
3502__LJMP static int hlua_channel_get_data(lua_State *L)
3503{
3504 struct channel *chn;
3505
3506 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3507 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3508 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3509 if (IS_HTX_STRM(chn_strm(chn))) {
3510 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3511 WILL_LJMP(lua_error(L));
3512 }
3513 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3514}
3515
3516/* Retrieves a given amount of input data at the given offset. By default all
3517 * available input data are returned. The offset may be negactive to start from
3518 * the end of input data. The length may be -1 to set it to the maximum buffer
3519 * size.
3520 */
3521__LJMP static int hlua_channel_get_line(lua_State *L)
3522{
3523 struct channel *chn;
3524
3525 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3526 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3527 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3528 if (IS_HTX_STRM(chn_strm(chn))) {
3529 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3530 WILL_LJMP(lua_error(L));
3531 }
3532 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3533}
3534
3535/* Appends a string into the input side of channel. It returns the length of the
3536 * written string, or -1 if the channel is closed or if the buffer size is too
3537 * little for the data. 0 may be returned if nothing is copied. This function
3538 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539 *
3540 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003541 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003542__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003543{
Christopher Faulet23976d92021-08-06 09:59:49 +02003544 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003545 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003546 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003547 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003548 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003549
3550 MAY_LJMP(check_args(L, 2, "append"));
3551 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003552 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003553 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003554 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003555 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003556 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003557
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003558 offset = co_data(chn);
3559 len = ci_data(chn);
3560
3561 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3562 if (filter && !hlua_filter_from_payload(filter))
3563 WILL_LJMP(lua_error(L));
3564
3565 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3566 if (ret > 0 && filter) {
3567 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3568
3569 flt_update_offsets(filter, chn, ret);
3570 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3571 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003572 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003573 return 1;
3574}
3575
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003576/* Prepends a string into the input side of channel. It returns the length of the
3577 * written string, or -1 if the channel is closed or if the buffer size is too
3578 * little for the data. 0 may be returned if nothing is copied. This function
3579 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003580 *
3581 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003582 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003583__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003584{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003585 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003586 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003587 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003588 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003589 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003590
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003591 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003592 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003593 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3594 if (IS_HTX_STRM(chn_strm(chn))) {
3595 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3596 WILL_LJMP(lua_error(L));
3597 }
3598
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003599 offset = co_data(chn);
3600 len = ci_data(chn);
3601
3602 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3603 if (filter && !hlua_filter_from_payload(filter))
3604 WILL_LJMP(lua_error(L));
3605
3606 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3607 if (ret > 0 && filter) {
3608 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3609
3610 flt_update_offsets(filter, chn, ret);
3611 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3612 }
3613
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003614 lua_pushinteger(L, ret);
3615 return 1;
3616}
3617
3618/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003619 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003620 * returns the length of the written string, or -1 if the channel is closed or
3621 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003622 *
3623 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624 */
3625__LJMP static int hlua_channel_insert_data(lua_State *L)
3626{
3627 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003628 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003629 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003630 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003631 int ret, offset;
3632
3633 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3634 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3635 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3636 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003637
3638 output = co_data(chn);
3639 input = ci_data(chn);
3640
3641 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3642 if (filter && !hlua_filter_from_payload(filter))
3643 WILL_LJMP(lua_error(L));
3644
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003645 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003646 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003647 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003648 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003649 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003650 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003651 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 lua_pushfstring(L, "offset out of range.");
3653 WILL_LJMP(lua_error(L));
3654 }
3655 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003656 if (IS_HTX_STRM(chn_strm(chn))) {
3657 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3658 WILL_LJMP(lua_error(L));
3659 }
3660
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003661 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3662 if (ret > 0 && filter) {
3663 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003664
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003665 flt_update_offsets(filter, chn, ret);
3666 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003667 }
3668
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003669 lua_pushinteger(L, ret);
3670 return 1;
3671}
3672/* Replaces a given amount of input data at the given offset by a string
3673 * content. By default all remaining data are removed (offset = 0 and len =
3674 * -1). It returns the length of the written string, or -1 if the channel is
3675 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003676 *
3677 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003678 */
3679__LJMP static int hlua_channel_set_data(lua_State *L)
3680{
3681 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003682 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003683 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003684 size_t sz, input, output;
3685 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003686
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003687 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3688 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3689 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3690 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003691
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003692 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003693 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003694 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003695 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003696
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003697 output = co_data(chn);
3698 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003699
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003700 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3701 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003702 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003703
3704 offset = output;
3705 if (lua_gettop(L) > 2) {
3706 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3707 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003708 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003709 offset += output;
3710 if (offset < output || offset > input + output) {
3711 lua_pushfstring(L, "offset out of range.");
3712 WILL_LJMP(lua_error(L));
3713 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003714 }
3715
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003716 len = output + input - offset;
3717 if (lua_gettop(L) == 4) {
3718 len = MAY_LJMP(luaL_checkinteger(L, 4));
3719 if (!len)
3720 goto set;
3721 if (len == -1)
3722 len = output + input - offset;
3723 if (len < 0 || offset + len > output + input) {
3724 lua_pushfstring(L, "length out of range.");
3725 WILL_LJMP(lua_error(L));
3726 }
3727 }
3728
3729 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003730 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003731 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003732 lua_pushinteger(L, -1);
3733 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003734 _hlua_channel_delete(chn, offset, len);
3735 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3736 if (filter) {
3737 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3738
3739 len -= (ret > 0 ? ret : 0);
3740 flt_update_offsets(filter, chn, -len);
3741 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3742 }
3743
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003744 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003745 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003746 return 1;
3747}
3748
3749/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003750 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003751 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003752 *
3753 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003754 */
3755__LJMP static int hlua_channel_del_data(lua_State *L)
3756{
3757 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 struct filter *filter;
3759 size_t input, output;
3760 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003761
3762 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3763 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3764 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003765
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003766 if (IS_HTX_STRM(chn_strm(chn))) {
3767 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3768 WILL_LJMP(lua_error(L));
3769 }
3770
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003771 output = co_data(chn);
3772 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003773
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003774 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3775 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003776 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003777
3778 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003779 if (lua_gettop(L) > 1) {
3780 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003781 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003782 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003783 offset += output;
3784 if (offset < output || offset > input + output) {
3785 lua_pushfstring(L, "offset out of range.");
3786 WILL_LJMP(lua_error(L));
3787 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003788 }
3789
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003790 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003791 if (lua_gettop(L) == 3) {
3792 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003793 if (!len)
3794 goto end;
3795 if (len == -1)
3796 len = output + input - offset;
3797 if (len < 0 || offset + len > output + input) {
3798 lua_pushfstring(L, "length out of range.");
3799 WILL_LJMP(lua_error(L));
3800 }
3801 }
3802
3803 _hlua_channel_delete(chn, offset, len);
3804 if (filter) {
3805 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3806
3807 flt_update_offsets(filter, chn, -len);
3808 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3809 }
3810
3811 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003812 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003813 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003814}
3815
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003816/* Append data in the output side of the buffer. This data is immediately
3817 * sent. The function returns the amount of data written. If the buffer
3818 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003819 * if the channel is closed.
3820 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003821__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003822{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003823 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003824 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003825 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003826 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003827 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003828 struct hlua *hlua;
3829
3830 /* Get hlua struct, or NULL if we execute from main lua state */
3831 hlua = hlua_gethlua(L);
3832 if (!hlua) {
3833 lua_pushnil(L);
3834 return 1;
3835 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003836
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003837 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3838 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3839 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003840
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003841 offset = co_data(chn);
3842 len = ci_data(chn);
3843
3844 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3845 if (filter && !hlua_filter_from_payload(filter))
3846 WILL_LJMP(lua_error(L));
3847
3848
Willy Tarreau47860ed2015-03-10 14:07:50 +01003849 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003850 lua_pushinteger(L, -1);
3851 return 1;
3852 }
3853
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003854 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003855 if (len > sz -l) {
3856 if (filter) {
3857 lua_pushinteger(L, -1);
3858 return 1;
3859 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003860 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003861 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003862
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003863 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003864 if (ret == -1) {
3865 lua_pop(L, 1);
3866 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003867 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003868 }
3869 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003870 if (filter) {
3871 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3872
3873
3874 flt_update_offsets(filter, chn, ret);
3875 FLT_OFF(filter, chn) += ret;
3876 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3877 }
3878 else
3879 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003880
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003881 l += ret;
3882 lua_pop(L, 1);
3883 lua_pushinteger(L, l);
3884 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003885
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003886 if (l < sz) {
3887 /* Yield only if the channel's output is not empty.
3888 * Otherwise it means we cannot add more data. */
3889 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003890 return 1;
3891
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003892 /* If we are waiting for space in the response buffer, we
3893 * must set the flag WAKERESWR. This flag required the task
3894 * wake up if any activity is detected on the response buffer.
3895 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003896 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003897 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003898 else
3899 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003900 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003901 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902
3903 return 1;
3904}
3905
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003906/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907 * yield the LUA process, and resume it without checking the
3908 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003909 *
3910 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003911 */
3912__LJMP static int hlua_channel_send(lua_State *L)
3913{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003914 struct channel *chn;
3915
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003916 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003917 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3918 if (IS_HTX_STRM(chn_strm(chn))) {
3919 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3920 WILL_LJMP(lua_error(L));
3921 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003922 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003923 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003924}
3925
3926/* This function forward and amount of butes. The data pass from
3927 * the input side of the buffer to the output side, and can be
3928 * forwarded. This function never fails.
3929 *
3930 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003931 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003932 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003933__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003934{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003935 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003936 struct filter *filter;
3937 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003938 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003939 struct hlua *hlua;
3940
3941 /* Get hlua struct, or NULL if we execute from main lua state */
3942 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003943 if (!hlua) {
3944 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003945 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003946 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003947
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003948 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003949 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003950 l = MAY_LJMP(luaL_checkinteger(L, -1));
3951
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003952 offset = co_data(chn);
3953 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003954
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003955 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3956 if (filter && !hlua_filter_from_payload(filter))
3957 WILL_LJMP(lua_error(L));
3958
3959 max = fwd - l;
3960 if (max > len)
3961 max = len;
3962
3963 if (filter) {
3964 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3965
3966 FLT_OFF(filter, chn) += max;
3967 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3968 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3969 }
3970 else
3971 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003972
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003973 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003974 lua_pop(L, 1);
3975 lua_pushinteger(L, l);
3976
3977 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003978 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003979 /* The the input channel or the output channel are closed, we
3980 * must return the amount of data forwarded.
3981 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003982 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003983 return 1;
3984
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003985 /* If we are waiting for space data in the response buffer, we
3986 * must set the flag WAKERESWR. This flag required the task
3987 * wake up if any activity is detected on the response buffer.
3988 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003989 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003990 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003991 else
3992 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003993
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003994 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003995 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003996 }
3997
3998 return 1;
3999}
4000
4001/* Just check the input and prepare the stack for the previous
4002 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004003 *
4004 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004005 */
4006__LJMP static int hlua_channel_forward(lua_State *L)
4007{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004008 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004009
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004010 MAY_LJMP(check_args(L, 2, "forward"));
4011 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4012 if (IS_HTX_STRM(chn_strm(chn))) {
4013 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4014 WILL_LJMP(lua_error(L));
4015 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004016 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004017 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004018}
4019
4020/* Just returns the number of bytes available in the input
4021 * side of the buffer. This function never fails.
4022 */
4023__LJMP static int hlua_channel_get_in_len(lua_State *L)
4024{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004025 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004026 struct filter *filter;
4027 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004028
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004029 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004030 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004031
4032 output = co_data(chn);
4033 input = ci_data(chn);
4034 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4035 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4036 lua_pushinteger(L, input);
4037 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004038 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004039
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004040 lua_pushinteger(L, htx->data - co_data(chn));
4041 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004042 return 1;
4043}
4044
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004045/* Returns true if the channel is full. */
4046__LJMP static int hlua_channel_is_full(lua_State *L)
4047{
4048 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004049
4050 MAY_LJMP(check_args(L, 1, "is_full"));
4051 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004052 /* ignore the reserve, we are not on a producer side (ie in an
4053 * applet).
4054 */
4055 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004056 return 1;
4057}
4058
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004059/* Returns true if the channel may still receive data. */
4060__LJMP static int hlua_channel_may_recv(lua_State *L)
4061{
4062 struct channel *chn;
4063
4064 MAY_LJMP(check_args(L, 1, "may_recv"));
4065 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4066 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4067 return 1;
4068}
4069
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004070/* Returns true if the channel is the response channel. */
4071__LJMP static int hlua_channel_is_resp(lua_State *L)
4072{
4073 struct channel *chn;
4074
4075 MAY_LJMP(check_args(L, 1, "is_resp"));
4076 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4077
4078 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4079 return 1;
4080}
4081
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004082/* Just returns the number of bytes available in the output
4083 * side of the buffer. This function never fails.
4084 */
4085__LJMP static int hlua_channel_get_out_len(lua_State *L)
4086{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004087 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004088 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004089
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004090 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004091 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004092
4093 output = co_data(chn);
4094 input = ci_data(chn);
4095 hlua_channel_filter(L, 1, chn, &output, &input);
4096
4097 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004098 return 1;
4099}
4100
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004101/*
4102 *
4103 *
4104 * Class Fetches
4105 *
4106 *
4107 */
4108
4109/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004110 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004111 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004112__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004113{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004114 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004115}
4116
4117/* This function creates and push in the stack a fetch object according
4118 * with a current TXN.
4119 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004120static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004121{
Willy Tarreau7073c472015-04-06 11:15:40 +02004122 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004123
4124 /* Check stack size. */
4125 if (!lua_checkstack(L, 3))
4126 return 0;
4127
4128 /* Create the object: obj[0] = userdata.
4129 * Note that the base of the Fetches object is the
4130 * transaction object.
4131 */
4132 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004133 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004134 lua_rawseti(L, -2, 0);
4135
Willy Tarreau7073c472015-04-06 11:15:40 +02004136 hsmp->s = txn->s;
4137 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004138 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004139 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004140
4141 /* Pop a class sesison metatable and affect it to the userdata. */
4142 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4143 lua_setmetatable(L, -2);
4144
4145 return 1;
4146}
4147
4148/* This function is an LUA binding. It is called with each sample-fetch.
4149 * It uses closure argument to store the associated sample-fetch. It
4150 * returns only one argument or throws an error. An error is thrown
4151 * only if an error is encountered during the argument parsing. If
4152 * the "sample-fetch" function fails, nil is returned.
4153 */
4154__LJMP static int hlua_run_sample_fetch(lua_State *L)
4155{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004156 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004157 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004158 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004159 int i;
4160 struct sample smp;
4161
4162 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004163 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004164
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004165 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004166 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004167
Thierry FOURNIERca988662015-12-20 18:43:03 +01004168 /* Check execution authorization. */
4169 if (f->use & SMP_USE_HTTP_ANY &&
4170 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4171 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4172 "is not available in Lua services", f->kw);
4173 WILL_LJMP(lua_error(L));
4174 }
4175
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004176 /* Get extra arguments. */
4177 for (i = 0; i < lua_gettop(L) - 1; i++) {
4178 if (i >= ARGM_NBARGS)
4179 break;
4180 hlua_lua2arg(L, i + 2, &args[i]);
4181 }
4182 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004183 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004184
4185 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004186 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004187
4188 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004189 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004190 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004191 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004192 }
4193
4194 /* Initialise the sample. */
4195 memset(&smp, 0, sizeof(smp));
4196
4197 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004198 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004199 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004200 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004201 lua_pushstring(L, "");
4202 else
4203 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004204 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004205 }
4206
4207 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004208 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004209 hlua_smp2lua_str(L, &smp);
4210 else
4211 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004212
4213 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004214 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004215 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004216
4217 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004218 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004219 WILL_LJMP(lua_error(L));
4220 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004221}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004222
4223/*
4224 *
4225 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004226 * Class Converters
4227 *
4228 *
4229 */
4230
4231/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004232 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004233 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004234__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004235{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004236 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004237}
4238
4239/* This function creates and push in the stack a Converters object
4240 * according with a current TXN.
4241 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004242static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004243{
Willy Tarreau7073c472015-04-06 11:15:40 +02004244 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004245
4246 /* Check stack size. */
4247 if (!lua_checkstack(L, 3))
4248 return 0;
4249
4250 /* Create the object: obj[0] = userdata.
4251 * Note that the base of the Converters object is the
4252 * same than the TXN object.
4253 */
4254 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004255 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004256 lua_rawseti(L, -2, 0);
4257
Willy Tarreau7073c472015-04-06 11:15:40 +02004258 hsmp->s = txn->s;
4259 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004260 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004261 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004262
Willy Tarreau87b09662015-04-03 00:22:06 +02004263 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004264 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4265 lua_setmetatable(L, -2);
4266
4267 return 1;
4268}
4269
4270/* This function is an LUA binding. It is called with each converter.
4271 * It uses closure argument to store the associated converter. It
4272 * returns only one argument or throws an error. An error is thrown
4273 * only if an error is encountered during the argument parsing. If
4274 * the converter function function fails, nil is returned.
4275 */
4276__LJMP static int hlua_run_sample_conv(lua_State *L)
4277{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004278 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004279 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004280 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004281 int i;
4282 struct sample smp;
4283
4284 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004285 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004286
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004287 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004288 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004289
4290 /* Get extra arguments. */
4291 for (i = 0; i < lua_gettop(L) - 2; i++) {
4292 if (i >= ARGM_NBARGS)
4293 break;
4294 hlua_lua2arg(L, i + 3, &args[i]);
4295 }
4296 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004297 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004298
4299 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004300 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004301
4302 /* Run the special args checker. */
4303 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4304 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004305 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004306 }
4307
4308 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004309 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004310 if (!hlua_lua2smp(L, 2, &smp)) {
4311 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004312 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004313 }
4314
Willy Tarreau1777ea62016-03-10 16:15:46 +01004315 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4316
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004317 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004318 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004319 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004320 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004321 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004322 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004323 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4324 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004325 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004326 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004327 }
4328
4329 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004330 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004331 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004332 lua_pushstring(L, "");
4333 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004334 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004335 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004336 }
4337
4338 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004339 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004340 hlua_smp2lua_str(L, &smp);
4341 else
4342 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004343 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004344 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004345 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004346
4347 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004348 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004349 WILL_LJMP(lua_error(L));
4350 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004351}
4352
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004353/*
4354 *
4355 *
4356 * Class AppletTCP
4357 *
4358 *
4359 */
4360
4361/* Returns a struct hlua_txn if the stack entry "ud" is
4362 * a class stream, otherwise it throws an error.
4363 */
4364__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4365{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004366 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004367}
4368
4369/* This function creates and push in the stack an Applet object
4370 * according with a current TXN.
4371 */
4372static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4373{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004374 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004375 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004376 struct proxy *p;
4377
4378 ALREADY_CHECKED(s);
4379 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004380
4381 /* Check stack size. */
4382 if (!lua_checkstack(L, 3))
4383 return 0;
4384
4385 /* Create the object: obj[0] = userdata.
4386 * Note that the base of the Converters object is the
4387 * same than the TXN object.
4388 */
4389 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004390 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004391 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004392 luactx->appctx = ctx;
4393 luactx->htxn.s = s;
4394 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004395
4396 /* Create the "f" field that contains a list of fetches. */
4397 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004398 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004399 return 0;
4400 lua_settable(L, -3);
4401
4402 /* Create the "sf" field that contains a list of stringsafe fetches. */
4403 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004404 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004405 return 0;
4406 lua_settable(L, -3);
4407
4408 /* Create the "c" field that contains a list of converters. */
4409 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004410 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004411 return 0;
4412 lua_settable(L, -3);
4413
4414 /* Create the "sc" field that contains a list of stringsafe converters. */
4415 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004416 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004417 return 0;
4418 lua_settable(L, -3);
4419
4420 /* Pop a class stream metatable and affect it to the table. */
4421 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4422 lua_setmetatable(L, -2);
4423
4424 return 1;
4425}
4426
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004427__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4428{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004429 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004430 struct stream *s;
4431 const char *name;
4432 size_t len;
4433 struct sample smp;
4434
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004435 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4436 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004437
4438 /* It is useles to retrieve the stream, but this function
4439 * runs only in a stream context.
4440 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004441 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004442 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004443 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004444
4445 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004446 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004447 hlua_lua2smp(L, 3, &smp);
4448
4449 /* Store the sample in a variable. */
4450 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004451
4452 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4453 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4454 else
4455 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4456
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004457 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004458}
4459
4460__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4461{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004462 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004463 struct stream *s;
4464 const char *name;
4465 size_t len;
4466 struct sample smp;
4467
4468 MAY_LJMP(check_args(L, 2, "unset_var"));
4469
4470 /* It is useles to retrieve the stream, but this function
4471 * runs only in a stream context.
4472 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004473 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004474 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004475 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004476
4477 /* Unset the variable. */
4478 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004479 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4480 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004481}
4482
4483__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4484{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004485 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004486 struct stream *s;
4487 const char *name;
4488 size_t len;
4489 struct sample smp;
4490
4491 MAY_LJMP(check_args(L, 2, "get_var"));
4492
4493 /* It is useles to retrieve the stream, but this function
4494 * runs only in a stream context.
4495 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004496 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004497 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004498 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004499
4500 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004501 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004502 lua_pushnil(L);
4503 return 1;
4504 }
4505
4506 return hlua_smp2lua(L, &smp);
4507}
4508
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004509__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4510{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004511 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4512 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004513 struct hlua *hlua;
4514
4515 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004516 if (!s->hlua)
4517 return 0;
4518 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004519
4520 MAY_LJMP(check_args(L, 2, "set_priv"));
4521
4522 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004523 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004524
4525 /* Get and store new value. */
4526 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4527 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4528
4529 return 0;
4530}
4531
4532__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4533{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004534 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4535 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004536 struct hlua *hlua;
4537
4538 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004539 if (!s->hlua) {
4540 lua_pushnil(L);
4541 return 1;
4542 }
4543 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004544
4545 /* Push configuration index in the stack. */
4546 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4547
4548 return 1;
4549}
4550
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004551/* If expected data not yet available, it returns a yield. This function
4552 * consumes the data in the buffer. It returns a string containing the
4553 * data. This string can be empty.
4554 */
4555__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4556{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004557 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004558 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004559 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004560 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004561 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004562 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004563 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004564
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004565 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004566 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004567
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004568 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004569 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004570 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004571 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004572 }
4573
4574 /* End of data: commit the total strings and return. */
4575 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004576 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004577 return 1;
4578 }
4579
4580 /* Ensure that the block 2 length is usable. */
4581 if (ret == 1)
4582 len2 = 0;
4583
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004584 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004585 luaL_addlstring(&luactx->b, blk1, len1);
4586 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004587
4588 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004589 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004590 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004591 return 1;
4592}
4593
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004594/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004595__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4596{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004597 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004598
4599 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004600 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004601
4602 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4603}
4604
4605/* If expected data not yet available, it returns a yield. This function
4606 * consumes the data in the buffer. It returns a string containing the
4607 * data. This string can be empty.
4608 */
4609__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4610{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004611 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004612 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004613 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004614 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004615 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004616 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004617 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004618 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004619
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004620 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004621 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004622
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004623 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004624 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004625 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004626 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004627 }
4628
4629 /* End of data: commit the total strings and return. */
4630 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004631 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004632 return 1;
4633 }
4634
4635 /* Ensure that the block 2 length is usable. */
4636 if (ret == 1)
4637 len2 = 0;
4638
4639 if (len == -1) {
4640
4641 /* If len == -1, catenate all the data avalaile and
4642 * yield because we want to get all the data until
4643 * the end of data stream.
4644 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004645 luaL_addlstring(&luactx->b, blk1, len1);
4646 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004647 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004648 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004649 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004650
4651 } else {
4652
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004653 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004654 if (len1 > len)
4655 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004656 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004657 len -= len1;
4658
4659 /* Copy the second block. */
4660 if (len2 > len)
4661 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004662 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004663 len -= len2;
4664
4665 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004666 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004667
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004668 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004669 if (len > 0) {
4670 lua_pushinteger(L, len);
4671 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004672 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004673 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004674 }
4675
4676 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004677 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004678 return 1;
4679 }
4680
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004681 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004682 hlua_pusherror(L, "Lua: internal error");
4683 WILL_LJMP(lua_error(L));
4684 return 0;
4685}
4686
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004687/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004688__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4689{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004690 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004691 int len = -1;
4692
4693 if (lua_gettop(L) > 2)
4694 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4695 if (lua_gettop(L) >= 2) {
4696 len = MAY_LJMP(luaL_checkinteger(L, 2));
4697 lua_pop(L, 1);
4698 }
4699
4700 /* Confirm or set the required length */
4701 lua_pushinteger(L, len);
4702
4703 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004704 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004705
4706 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4707}
4708
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004709/* Append data in the output side of the buffer. This data is immediately
4710 * sent. The function returns the amount of data written. If the buffer
4711 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004712 * if the channel is closed.
4713 */
4714__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4715{
4716 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004717 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004718 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4719 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004720 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004721 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004722 int max;
4723
4724 /* Get the max amount of data which can write as input in the channel. */
4725 max = channel_recv_max(chn);
4726 if (max > (len - l))
4727 max = len - l;
4728
4729 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004730 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004731
4732 /* update counters. */
4733 l += max;
4734 lua_pop(L, 1);
4735 lua_pushinteger(L, l);
4736
4737 /* If some data is not send, declares the situation to the
4738 * applet, and returns a yield.
4739 */
4740 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004741 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004742 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004743 }
4744
4745 return 1;
4746}
4747
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004748/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004749 * yield the LUA process, and resume it without checking the
4750 * input arguments.
4751 */
4752__LJMP static int hlua_applet_tcp_send(lua_State *L)
4753{
4754 MAY_LJMP(check_args(L, 2, "send"));
4755 lua_pushinteger(L, 0);
4756
4757 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4758}
4759
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004760/*
4761 *
4762 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004763 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004764 *
4765 *
4766 */
4767
4768/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004769 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004770 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004771__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004772{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004773 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004774}
4775
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004776/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004777 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004778 * It relies on the caller to have already reserved the room in ctx->svcctx
4779 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004780 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004781static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004782{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004783 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004784 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004785 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004786 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004787 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004788 struct htx *htx;
4789 struct htx_blk *blk;
4790 struct htx_sl *sl;
4791 struct ist path;
4792 unsigned long long len = 0;
4793 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004794 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004795
4796 /* Check stack size. */
4797 if (!lua_checkstack(L, 3))
4798 return 0;
4799
4800 /* Create the object: obj[0] = userdata.
4801 * Note that the base of the Converters object is the
4802 * same than the TXN object.
4803 */
4804 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004805 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004806 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004807 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004808 http_ctx->status = 200; /* Default status code returned. */
4809 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004810 luactx->htxn.s = s;
4811 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004812
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004813 /* Create the "f" field that contains a list of fetches. */
4814 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004815 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004816 return 0;
4817 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004818
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004819 /* Create the "sf" field that contains a list of stringsafe fetches. */
4820 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004821 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004822 return 0;
4823 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004824
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004825 /* Create the "c" field that contains a list of converters. */
4826 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004827 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004828 return 0;
4829 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004830
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004831 /* Create the "sc" field that contains a list of stringsafe converters. */
4832 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004833 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004834 return 0;
4835 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004836
Christopher Fauleta2097962019-07-15 16:25:33 +02004837 htx = htxbuf(&s->req.buf);
4838 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004839 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004840 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004841
Christopher Fauleta2097962019-07-15 16:25:33 +02004842 /* Stores the request method. */
4843 lua_pushstring(L, "method");
4844 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4845 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004846
Christopher Fauleta2097962019-07-15 16:25:33 +02004847 /* Stores the http version. */
4848 lua_pushstring(L, "version");
4849 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4850 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004851
Christopher Fauleta2097962019-07-15 16:25:33 +02004852 /* creates an array of headers. hlua_http_get_headers() crates and push
4853 * the array on the top of the stack.
4854 */
4855 lua_pushstring(L, "headers");
4856 htxn.s = s;
4857 htxn.p = px;
4858 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004859 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004860 return 0;
4861 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004862
Amaury Denoyellec453f952021-07-06 11:40:12 +02004863 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4864 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004865 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004866 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004867
Christopher Fauleta2097962019-07-15 16:25:33 +02004868 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004869 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004870 q = p;
4871 while (q < end && *q != '?')
4872 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004873
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004874 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004875 lua_pushstring(L, "path");
4876 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004877 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004878
Christopher Fauleta2097962019-07-15 16:25:33 +02004879 /* Stores the query string. */
4880 lua_pushstring(L, "qs");
4881 if (*q == '?')
4882 q++;
4883 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004884 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004885 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004886
Christopher Fauleta2097962019-07-15 16:25:33 +02004887 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4888 struct htx_blk *blk = htx_get_blk(htx, pos);
4889 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004890
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004891 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004892 break;
4893 if (type == HTX_BLK_DATA)
4894 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004895 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01004896 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02004897 len += htx->extra;
4898
4899 /* Stores the request path. */
4900 lua_pushstring(L, "length");
4901 lua_pushinteger(L, len);
4902 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004903
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004904 /* Create an empty array of HTTP request headers. */
4905 lua_pushstring(L, "response");
4906 lua_newtable(L);
4907 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004908
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004909 /* Pop a class stream metatable and affect it to the table. */
4910 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4911 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004912
4913 return 1;
4914}
4915
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004916__LJMP static int hlua_applet_http_set_var(lua_State *L)
4917{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004918 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004919 struct stream *s;
4920 const char *name;
4921 size_t len;
4922 struct sample smp;
4923
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004924 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4925 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004926
4927 /* It is useles to retrieve the stream, but this function
4928 * runs only in a stream context.
4929 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004930 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004931 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004932 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004933
4934 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004935 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004936 hlua_lua2smp(L, 3, &smp);
4937
4938 /* Store the sample in a variable. */
4939 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004940
4941 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4942 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4943 else
4944 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4945
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004946 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004947}
4948
4949__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4950{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004951 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004952 struct stream *s;
4953 const char *name;
4954 size_t len;
4955 struct sample smp;
4956
4957 MAY_LJMP(check_args(L, 2, "unset_var"));
4958
4959 /* It is useles to retrieve the stream, but this function
4960 * runs only in a stream context.
4961 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004962 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004963 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004964 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004965
4966 /* Unset the variable. */
4967 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004968 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4969 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004970}
4971
4972__LJMP static int hlua_applet_http_get_var(lua_State *L)
4973{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004974 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004975 struct stream *s;
4976 const char *name;
4977 size_t len;
4978 struct sample smp;
4979
4980 MAY_LJMP(check_args(L, 2, "get_var"));
4981
4982 /* It is useles to retrieve the stream, but this function
4983 * runs only in a stream context.
4984 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004985 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004986 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004987 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004988
4989 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004990 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004991 lua_pushnil(L);
4992 return 1;
4993 }
4994
4995 return hlua_smp2lua(L, &smp);
4996}
4997
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004998__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4999{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005000 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5001 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005002 struct hlua *hlua;
5003
5004 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005005 if (!s->hlua)
5006 return 0;
5007 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005008
5009 MAY_LJMP(check_args(L, 2, "set_priv"));
5010
5011 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005012 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005013
5014 /* Get and store new value. */
5015 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5016 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5017
5018 return 0;
5019}
5020
5021__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5022{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005023 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5024 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005025 struct hlua *hlua;
5026
5027 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005028 if (!s->hlua) {
5029 lua_pushnil(L);
5030 return 1;
5031 }
5032 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005033
5034 /* Push configuration index in the stack. */
5035 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5036
5037 return 1;
5038}
5039
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005040/* If expected data not yet available, it returns a yield. This function
5041 * consumes the data in the buffer. It returns a string containing the
5042 * data. This string can be empty.
5043 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005044__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005045{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005046 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005047 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005048 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005049 struct htx *htx;
5050 struct htx_blk *blk;
5051 size_t count;
5052 int stop = 0;
5053
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054 htx = htx_from_buf(&req->buf);
5055 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005056 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005057
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005058 while (count && !stop && blk) {
5059 enum htx_blk_type type = htx_get_blk_type(blk);
5060 uint32_t sz = htx_get_blksz(blk);
5061 struct ist v;
5062 uint32_t vlen;
5063 char *nl;
5064
5065 vlen = sz;
5066 if (vlen > count) {
5067 if (type != HTX_BLK_DATA)
5068 break;
5069 vlen = count;
5070 }
5071
5072 switch (type) {
5073 case HTX_BLK_UNUSED:
5074 break;
5075
5076 case HTX_BLK_DATA:
5077 v = htx_get_blk_value(htx, blk);
5078 v.len = vlen;
5079 nl = istchr(v, '\n');
5080 if (nl != NULL) {
5081 stop = 1;
5082 vlen = nl - v.ptr + 1;
5083 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005084 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005085 break;
5086
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005087 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005088 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005089 stop = 1;
5090 break;
5091
5092 default:
5093 break;
5094 }
5095
Willy Tarreau84240042022-02-28 16:51:23 +01005096 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005097 count -= vlen;
5098 if (sz == vlen)
5099 blk = htx_remove_blk(htx, blk);
5100 else {
5101 htx_cut_data_blk(htx, blk, vlen);
5102 break;
5103 }
5104 }
5105
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005106 /* The message was fully consumed and no more data are expected
5107 * (EOM flag set).
5108 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005109 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005110 stop = 1;
5111
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005112 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005113 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005114 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005115 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005116 }
5117
5118 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005119 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005120 return 1;
5121}
5122
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005123
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005124/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005125__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005126{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005127 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005128
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005129 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005130 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005131
Christopher Fauleta2097962019-07-15 16:25:33 +02005132 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005133}
5134
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005135/* If expected data not yet available, it returns a yield. This function
5136 * consumes the data in the buffer. It returns a string containing the
5137 * data. This string can be empty.
5138 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005139__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005140{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005141 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005142 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005143 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005144 struct htx *htx;
5145 struct htx_blk *blk;
5146 size_t count;
5147 int len;
5148
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005149 htx = htx_from_buf(&req->buf);
5150 len = MAY_LJMP(luaL_checkinteger(L, 2));
5151 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005152 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005153 while (count && len && blk) {
5154 enum htx_blk_type type = htx_get_blk_type(blk);
5155 uint32_t sz = htx_get_blksz(blk);
5156 struct ist v;
5157 uint32_t vlen;
5158
5159 vlen = sz;
5160 if (len > 0 && vlen > len)
5161 vlen = len;
5162 if (vlen > count) {
5163 if (type != HTX_BLK_DATA)
5164 break;
5165 vlen = count;
5166 }
5167
5168 switch (type) {
5169 case HTX_BLK_UNUSED:
5170 break;
5171
5172 case HTX_BLK_DATA:
5173 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005174 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005175 break;
5176
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005177 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005178 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005179 len = 0;
5180 break;
5181
5182 default:
5183 break;
5184 }
5185
Willy Tarreau84240042022-02-28 16:51:23 +01005186 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005187 count -= vlen;
5188 if (len > 0)
5189 len -= vlen;
5190 if (sz == vlen)
5191 blk = htx_remove_blk(htx, blk);
5192 else {
5193 htx_cut_data_blk(htx, blk, vlen);
5194 break;
5195 }
5196 }
5197
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005198 /* The message was fully consumed and no more data are expected
5199 * (EOM flag set).
5200 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005201 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005202 len = 0;
5203
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005204 htx_to_buf(htx, &req->buf);
5205
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005206 /* If we are no other data available, yield waiting for new data. */
5207 if (len) {
5208 if (len > 0) {
5209 lua_pushinteger(L, len);
5210 lua_replace(L, 2);
5211 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005212 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005213 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005214 }
5215
5216 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005217 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005218 return 1;
5219}
5220
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005221/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005222__LJMP static int hlua_applet_http_recv(lua_State *L)
5223{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005224 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005225 int len = -1;
5226
5227 /* Check arguments. */
5228 if (lua_gettop(L) > 2)
5229 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5230 if (lua_gettop(L) >= 2) {
5231 len = MAY_LJMP(luaL_checkinteger(L, 2));
5232 lua_pop(L, 1);
5233 }
5234
Christopher Fauleta2097962019-07-15 16:25:33 +02005235 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005236
Christopher Fauleta2097962019-07-15 16:25:33 +02005237 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005238 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005239
Christopher Fauleta2097962019-07-15 16:25:33 +02005240 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005241}
5242
5243/* Append data in the output side of the buffer. This data is immediately
5244 * sent. The function returns the amount of data written. If the buffer
5245 * cannot contain the data, the function yields. The function returns -1
5246 * if the channel is closed.
5247 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005248__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005249{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005250 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005251 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005252 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005253 struct htx *htx = htx_from_buf(&res->buf);
5254 const char *data;
5255 size_t len;
5256 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5257 int max;
5258
Christopher Faulet9060fc02019-07-03 11:39:30 +02005259 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005260 if (!max)
5261 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005262
5263 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5264
5265 /* Get the max amount of data which can write as input in the channel. */
5266 if (max > (len - l))
5267 max = len - l;
5268
5269 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005270 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005271 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005272
5273 /* update counters. */
5274 l += max;
5275 lua_pop(L, 1);
5276 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005277
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005278 /* If some data is not send, declares the situation to the
5279 * applet, and returns a yield.
5280 */
5281 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005282 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005283 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005284 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005285 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005286 }
5287
Christopher Fauleta2097962019-07-15 16:25:33 +02005288 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005289 return 1;
5290}
5291
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005292/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005293 * yield the LUA process, and resume it without checking the
5294 * input arguments.
5295 */
5296__LJMP static int hlua_applet_http_send(lua_State *L)
5297{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005298 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005299 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005300
5301 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005302 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005303 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5304 WILL_LJMP(lua_error(L));
5305 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005306
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005307 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005308 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005309
Christopher Fauleta2097962019-07-15 16:25:33 +02005310 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005311}
5312
5313__LJMP static int hlua_applet_http_addheader(lua_State *L)
5314{
5315 const char *name;
5316 int ret;
5317
5318 MAY_LJMP(hlua_checkapplet_http(L, 1));
5319 name = MAY_LJMP(luaL_checkstring(L, 2));
5320 MAY_LJMP(luaL_checkstring(L, 3));
5321
5322 /* Push in the stack the "response" entry. */
5323 ret = lua_getfield(L, 1, "response");
5324 if (ret != LUA_TTABLE) {
5325 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5326 "is expected as an array. %s found", lua_typename(L, ret));
5327 WILL_LJMP(lua_error(L));
5328 }
5329
5330 /* check if the header is already registered if it is not
5331 * the case, register it.
5332 */
5333 ret = lua_getfield(L, -1, name);
5334 if (ret == LUA_TNIL) {
5335
5336 /* Entry not found. */
5337 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5338
5339 /* Insert the new header name in the array in the top of the stack.
5340 * It left the new array in the top of the stack.
5341 */
5342 lua_newtable(L);
5343 lua_pushvalue(L, 2);
5344 lua_pushvalue(L, -2);
5345 lua_settable(L, -4);
5346
5347 } else if (ret != LUA_TTABLE) {
5348
5349 /* corruption error. */
5350 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5351 "is expected as an array. %s found", name, lua_typename(L, ret));
5352 WILL_LJMP(lua_error(L));
5353 }
5354
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005355 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005356 * the header value as new entry.
5357 */
5358 lua_pushvalue(L, 3);
5359 ret = lua_rawlen(L, -2);
5360 lua_rawseti(L, -2, ret + 1);
5361 lua_pushboolean(L, 1);
5362 return 1;
5363}
5364
5365__LJMP static int hlua_applet_http_status(lua_State *L)
5366{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005367 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005368 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005369 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005370 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005371
5372 if (status < 100 || status > 599) {
5373 lua_pushboolean(L, 0);
5374 return 1;
5375 }
5376
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005377 http_ctx->status = status;
5378 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005379 lua_pushboolean(L, 1);
5380 return 1;
5381}
5382
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005383
Christopher Fauleta2097962019-07-15 16:25:33 +02005384__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005385{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005386 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005387 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005388 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005389 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005390 struct htx *htx;
5391 struct htx_sl *sl;
5392 struct h1m h1m;
5393 const char *status, *reason;
5394 const char *name, *value;
5395 size_t nlen, vlen;
5396 unsigned int flags;
5397
5398 /* Send the message at once. */
5399 htx = htx_from_buf(&res->buf);
5400 h1m_init_res(&h1m);
5401
5402 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005403 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5404 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005405 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005406 reason = http_get_reason(http_ctx->status);
5407 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005408 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5409 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5410 }
5411 else {
5412 flags = HTX_SL_F_IS_RESP;
5413 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5414 }
5415 if (!sl) {
5416 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005417 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005418 WILL_LJMP(lua_error(L));
5419 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005420 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005421
5422 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005423 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5424 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005425 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005426 WILL_LJMP(lua_error(L));
5427 }
5428
5429 /* Browse the list of headers. */
5430 lua_pushnil(L);
5431 while(lua_next(L, -2) != 0) {
5432 /* We expect a string as -2. */
5433 if (lua_type(L, -2) != LUA_TSTRING) {
5434 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005435 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005436 lua_typename(L, lua_type(L, -2)));
5437 WILL_LJMP(lua_error(L));
5438 }
5439 name = lua_tolstring(L, -2, &nlen);
5440
5441 /* We expect an array as -1. */
5442 if (lua_type(L, -1) != LUA_TTABLE) {
5443 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 +02005444 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005445 name,
5446 lua_typename(L, lua_type(L, -1)));
5447 WILL_LJMP(lua_error(L));
5448 }
5449
5450 /* Browse the table who is on the top of the stack. */
5451 lua_pushnil(L);
5452 while(lua_next(L, -2) != 0) {
5453 int id;
5454
5455 /* We expect a number as -2. */
5456 if (lua_type(L, -2) != LUA_TNUMBER) {
5457 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 +02005458 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005459 name,
5460 lua_typename(L, lua_type(L, -2)));
5461 WILL_LJMP(lua_error(L));
5462 }
5463 id = lua_tointeger(L, -2);
5464
5465 /* We expect a string as -2. */
5466 if (lua_type(L, -1) != LUA_TSTRING) {
5467 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 +02005468 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469 name, id,
5470 lua_typename(L, lua_type(L, -1)));
5471 WILL_LJMP(lua_error(L));
5472 }
5473 value = lua_tolstring(L, -1, &vlen);
5474
5475 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005476 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5477 int ret;
5478
5479 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5480 if (ret < 0) {
5481 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5482 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5483 name);
5484 WILL_LJMP(lua_error(L));
5485 }
5486 else if (ret == 0)
5487 goto next; /* Skip it */
5488 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005489 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5490 struct ist v = ist2(value, vlen);
5491 int ret;
5492
5493 ret = h1_parse_cont_len_header(&h1m, &v);
5494 if (ret < 0) {
5495 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005496 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005497 name);
5498 WILL_LJMP(lua_error(L));
5499 }
5500 else if (ret == 0)
5501 goto next; /* Skip it */
5502 }
5503
5504 /* Add a new header */
5505 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5506 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005507 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005508 name);
5509 WILL_LJMP(lua_error(L));
5510 }
5511 next:
5512 /* Remove the array from the stack, and get next element with a remaining string. */
5513 lua_pop(L, 1);
5514 }
5515
5516 /* Remove the array from the stack, and get next element with a remaining string. */
5517 lua_pop(L, 1);
5518 }
5519
5520 if (h1m.flags & H1_MF_CHNK)
5521 h1m.flags &= ~H1_MF_CLEN;
5522 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5523 h1m.flags |= H1_MF_XFER_LEN;
5524
5525 /* Uset HTX start-line flags */
5526 if (h1m.flags & H1_MF_XFER_ENC)
5527 flags |= HTX_SL_F_XFER_ENC;
5528 if (h1m.flags & H1_MF_XFER_LEN) {
5529 flags |= HTX_SL_F_XFER_LEN;
5530 if (h1m.flags & H1_MF_CHNK)
5531 flags |= HTX_SL_F_CHNK;
5532 else if (h1m.flags & H1_MF_CLEN)
5533 flags |= HTX_SL_F_CLEN;
5534 if (h1m.body_len == 0)
5535 flags |= HTX_SL_F_BODYLESS;
5536 }
5537 sl->flags |= flags;
5538
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005539 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005540 * and the status code implies the presence of a message body, we must
5541 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005542 * for the keepalive compliance. If the applet announces a transfer-encoding
5543 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005544 */
5545 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005546 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005547 /* Add a new header */
5548 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5549 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5550 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005551 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005552 WILL_LJMP(lua_error(L));
5553 }
5554 }
5555
5556 /* Finalize headers. */
5557 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5558 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005559 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005560 WILL_LJMP(lua_error(L));
5561 }
5562
5563 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5564 b_reset(&res->buf);
5565 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5566 WILL_LJMP(lua_error(L));
5567 }
5568
5569 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005570 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005571
5572 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005573 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005574 return 0;
5575
5576}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005577/* We will build the status line and the headers of the HTTP response.
5578 * We will try send at once if its not possible, we give back the hand
5579 * waiting for more room.
5580 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005581__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005582{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005583 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005584 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005585 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005586
5587 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005588 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005589 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005590 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005591 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005592}
5593
5594
Christopher Fauleta2097962019-07-15 16:25:33 +02005595__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005596{
Christopher Fauleta2097962019-07-15 16:25:33 +02005597 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005598}
5599
Christopher Fauleta2097962019-07-15 16:25:33 +02005600/*
5601 *
5602 *
5603 * Class HTTP
5604 *
5605 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005606 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005607
5608/* Returns a struct hlua_txn if the stack entry "ud" is
5609 * a class stream, otherwise it throws an error.
5610 */
5611__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005612{
Christopher Fauleta2097962019-07-15 16:25:33 +02005613 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5614}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005615
Christopher Fauleta2097962019-07-15 16:25:33 +02005616/* This function creates and push in the stack a HTTP object
5617 * according with a current TXN.
5618 */
5619static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5620{
5621 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005622
Christopher Fauleta2097962019-07-15 16:25:33 +02005623 /* Check stack size. */
5624 if (!lua_checkstack(L, 3))
5625 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005626
Christopher Fauleta2097962019-07-15 16:25:33 +02005627 /* Create the object: obj[0] = userdata.
5628 * Note that the base of the Converters object is the
5629 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005630 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005631 lua_newtable(L);
5632 htxn = lua_newuserdata(L, sizeof(*htxn));
5633 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005634
5635 htxn->s = txn->s;
5636 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005637 htxn->dir = txn->dir;
5638 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005639
5640 /* Pop a class stream metatable and affect it to the table. */
5641 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5642 lua_setmetatable(L, -2);
5643
5644 return 1;
5645}
5646
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005647/* This function creates and returns an array containing the status-line
5648 * elements. This function does not fails.
5649 */
5650__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5651{
5652 /* Create the table. */
5653 lua_newtable(L);
5654
5655 if (sl->flags & HTX_SL_F_IS_RESP) {
5656 lua_pushstring(L, "version");
5657 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5658 lua_settable(L, -3);
5659 lua_pushstring(L, "code");
5660 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5661 lua_settable(L, -3);
5662 lua_pushstring(L, "reason");
5663 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5664 lua_settable(L, -3);
5665 }
5666 else {
5667 lua_pushstring(L, "method");
5668 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5669 lua_settable(L, -3);
5670 lua_pushstring(L, "uri");
5671 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5672 lua_settable(L, -3);
5673 lua_pushstring(L, "version");
5674 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5675 lua_settable(L, -3);
5676 }
5677 return 1;
5678}
5679
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005680/* This function creates ans returns an array of HTTP headers.
5681 * This function does not fails. It is used as wrapper with the
5682 * 2 following functions.
5683 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005684__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005685{
Christopher Fauleta2097962019-07-15 16:25:33 +02005686 struct htx *htx;
5687 int32_t pos;
5688
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005689 /* Create the table. */
5690 lua_newtable(L);
5691
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005692
Christopher Fauleta2097962019-07-15 16:25:33 +02005693 htx = htxbuf(&msg->chn->buf);
5694 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5695 struct htx_blk *blk = htx_get_blk(htx, pos);
5696 enum htx_blk_type type = htx_get_blk_type(blk);
5697 struct ist n, v;
5698 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005699
Christopher Fauleta2097962019-07-15 16:25:33 +02005700 if (type == HTX_BLK_HDR) {
5701 n = htx_get_blk_name(htx,blk);
5702 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005703 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005704 else if (type == HTX_BLK_EOH)
5705 break;
5706 else
5707 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005708
Christopher Fauleta2097962019-07-15 16:25:33 +02005709 /* Check for existing entry:
5710 * assume that the table is on the top of the stack, and
5711 * push the key in the stack, the function lua_gettable()
5712 * perform the lookup.
5713 */
5714 lua_pushlstring(L, n.ptr, n.len);
5715 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005716
Christopher Fauleta2097962019-07-15 16:25:33 +02005717 switch (lua_type(L, -1)) {
5718 case LUA_TNIL:
5719 /* Table not found, create it. */
5720 lua_pop(L, 1); /* remove the nil value. */
5721 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5722 lua_newtable(L); /* create and push empty table. */
5723 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5724 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5725 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005726 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005727
Christopher Fauleta2097962019-07-15 16:25:33 +02005728 case LUA_TTABLE:
5729 /* Entry found: push the value in the table. */
5730 len = lua_rawlen(L, -1);
5731 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5732 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5733 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5734 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005735
Christopher Fauleta2097962019-07-15 16:25:33 +02005736 default:
5737 /* Other cases are errors. */
5738 hlua_pusherror(L, "internal error during the parsing of headers.");
5739 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005740 }
5741 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005742 return 1;
5743}
5744
5745__LJMP static int hlua_http_req_get_headers(lua_State *L)
5746{
5747 struct hlua_txn *htxn;
5748
5749 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5750 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5751
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005752 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005753 WILL_LJMP(lua_error(L));
5754
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005755 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005756}
5757
5758__LJMP static int hlua_http_res_get_headers(lua_State *L)
5759{
5760 struct hlua_txn *htxn;
5761
5762 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5763 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5764
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005765 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005766 WILL_LJMP(lua_error(L));
5767
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005768 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005769}
5770
5771/* This function replace full header, or just a value in
5772 * the request or in the response. It is a wrapper fir the
5773 * 4 following functions.
5774 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005775__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005776{
5777 size_t name_len;
5778 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5779 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5780 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005781 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005782 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005783
Dragan Dosen26743032019-04-30 15:54:36 +02005784 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005785 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5786
Christopher Fauleta2097962019-07-15 16:25:33 +02005787 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005788 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005789 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005790 return 0;
5791}
5792
5793__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5794{
5795 struct hlua_txn *htxn;
5796
5797 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5798 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5799
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005800 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005801 WILL_LJMP(lua_error(L));
5802
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005803 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005804}
5805
5806__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5807{
5808 struct hlua_txn *htxn;
5809
5810 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5811 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5812
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005813 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005814 WILL_LJMP(lua_error(L));
5815
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005816 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005817}
5818
5819__LJMP static int hlua_http_req_rep_val(lua_State *L)
5820{
5821 struct hlua_txn *htxn;
5822
5823 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5824 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5825
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005826 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005827 WILL_LJMP(lua_error(L));
5828
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005829 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005830}
5831
5832__LJMP static int hlua_http_res_rep_val(lua_State *L)
5833{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005834 struct hlua_txn *htxn;
5835
5836 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5837 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5838
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005839 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005840 WILL_LJMP(lua_error(L));
5841
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005842 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005843}
5844
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005845/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005846 * It is a wrapper for the 2 following functions.
5847 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005848__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005849{
5850 size_t len;
5851 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005852 struct htx *htx = htxbuf(&msg->chn->buf);
5853 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005854
Christopher Fauleta2097962019-07-15 16:25:33 +02005855 ctx.blk = NULL;
5856 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5857 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005858 return 0;
5859}
5860
5861__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5862{
5863 struct hlua_txn *htxn;
5864
5865 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5866 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5867
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005868 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005869 WILL_LJMP(lua_error(L));
5870
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005871 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005872}
5873
5874__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5875{
5876 struct hlua_txn *htxn;
5877
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005878 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005879 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5880
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005881 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005882 WILL_LJMP(lua_error(L));
5883
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005884 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005885}
5886
5887/* This function adds an header. It is a wrapper used by
5888 * the 2 following functions.
5889 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005890__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005891{
5892 size_t name_len;
5893 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5894 size_t value_len;
5895 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005896 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005897
Christopher Fauleta2097962019-07-15 16:25:33 +02005898 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5899 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005900 return 0;
5901}
5902
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005903__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5904{
5905 struct hlua_txn *htxn;
5906
5907 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5908 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5909
5910 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5911 WILL_LJMP(lua_error(L));
5912
5913 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5914}
5915
5916__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5917{
5918 struct hlua_txn *htxn;
5919
5920 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5921 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5922
5923 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5924 WILL_LJMP(lua_error(L));
5925
5926 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5927}
5928
5929static int hlua_http_req_set_hdr(lua_State *L)
5930{
5931 struct hlua_txn *htxn;
5932
5933 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5934 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5935
5936 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5937 WILL_LJMP(lua_error(L));
5938
5939 hlua_http_del_hdr(L, &htxn->s->txn->req);
5940 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5941}
5942
5943static int hlua_http_res_set_hdr(lua_State *L)
5944{
5945 struct hlua_txn *htxn;
5946
5947 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5948 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5949
5950 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5951 WILL_LJMP(lua_error(L));
5952
5953 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5954 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5955}
5956
5957/* This function set the method. */
5958static int hlua_http_req_set_meth(lua_State *L)
5959{
5960 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5961 size_t name_len;
5962 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5963
5964 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5965 WILL_LJMP(lua_error(L));
5966
5967 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5968 return 1;
5969}
5970
5971/* This function set the method. */
5972static int hlua_http_req_set_path(lua_State *L)
5973{
5974 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5975 size_t name_len;
5976 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5977
5978 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5979 WILL_LJMP(lua_error(L));
5980
5981 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5982 return 1;
5983}
5984
5985/* This function set the query-string. */
5986static int hlua_http_req_set_query(lua_State *L)
5987{
5988 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5989 size_t name_len;
5990 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5991
5992 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5993 WILL_LJMP(lua_error(L));
5994
5995 /* Check length. */
5996 if (name_len > trash.size - 1) {
5997 lua_pushboolean(L, 0);
5998 return 1;
5999 }
6000
6001 /* Add the mark question as prefix. */
6002 chunk_reset(&trash);
6003 trash.area[trash.data++] = '?';
6004 memcpy(trash.area + trash.data, name, name_len);
6005 trash.data += name_len;
6006
6007 lua_pushboolean(L,
6008 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6009 return 1;
6010}
6011
6012/* This function set the uri. */
6013static int hlua_http_req_set_uri(lua_State *L)
6014{
6015 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6016 size_t name_len;
6017 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6018
6019 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6020 WILL_LJMP(lua_error(L));
6021
6022 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6023 return 1;
6024}
6025
6026/* This function set the response code & optionally reason. */
6027static int hlua_http_res_set_status(lua_State *L)
6028{
6029 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6030 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6031 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6032 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6033
6034 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6035 WILL_LJMP(lua_error(L));
6036
6037 http_res_set_status(code, reason, htxn->s);
6038 return 0;
6039}
6040
6041/*
6042 *
6043 *
6044 * Class HTTPMessage
6045 *
6046 *
6047 */
6048
6049/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6050 * otherwise it throws an error.
6051 */
6052__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6053{
6054 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6055}
6056
6057/* Creates and pushes on the stack a HTTP object according with a current TXN.
6058 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006059static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006060{
6061 /* Check stack size. */
6062 if (!lua_checkstack(L, 3))
6063 return 0;
6064
6065 lua_newtable(L);
6066 lua_pushlightuserdata(L, msg);
6067 lua_rawseti(L, -2, 0);
6068
6069 /* Create the "channel" field that contains the request channel object. */
6070 lua_pushstring(L, "channel");
6071 if (!hlua_channel_new(L, msg->chn))
6072 return 0;
6073 lua_rawset(L, -3);
6074
6075 /* Pop a class stream metatable and affect it to the table. */
6076 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6077 lua_setmetatable(L, -2);
6078
6079 return 1;
6080}
6081
6082/* Helper function returning a filter attached to the HTTP message at the
6083 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006084 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006085 * filled with output and input length respectively.
6086 */
6087static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6088{
6089 struct channel *chn = msg->chn;
6090 struct htx *htx = htxbuf(&chn->buf);
6091 struct filter *filter = NULL;
6092
6093 *offset = co_data(msg->chn);
6094 *len = htx->data - co_data(msg->chn);
6095
6096 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6097 filter = lua_touserdata (L, -1);
6098 if (msg->msg_state >= HTTP_MSG_DATA) {
6099 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6100
6101 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6102 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6103 }
6104 }
6105
6106 lua_pop(L, 1);
6107 return filter;
6108}
6109
6110/* Returns true if the channel attached to the HTTP message is the response
6111 * channel.
6112 */
6113__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6114{
6115 struct http_msg *msg;
6116
6117 MAY_LJMP(check_args(L, 1, "is_resp"));
6118 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6119
6120 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6121 return 1;
6122}
6123
6124/* Returns an array containing the elements status-line of the HTTP message. It relies
6125 * on hlua_http_get_stline().
6126 */
6127__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6128{
6129 struct http_msg *msg;
6130 struct htx *htx;
6131 struct htx_sl *sl;
6132
6133 MAY_LJMP(check_args(L, 1, "get_stline"));
6134 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6135
6136 if (msg->msg_state > HTTP_MSG_BODY)
6137 WILL_LJMP(lua_error(L));
6138
6139 htx = htxbuf(&msg->chn->buf);
6140 sl = http_get_stline(htx);
6141 if (!sl)
6142 return 0;
6143 return hlua_http_get_stline(L, sl);
6144}
6145
6146/* Returns an array containing all headers of the HTTP message. it relies on
6147 * hlua_http_get_headers().
6148 */
6149__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6150{
6151 struct http_msg *msg;
6152
6153 MAY_LJMP(check_args(L, 1, "get_headers"));
6154 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6155
6156 if (msg->msg_state > HTTP_MSG_BODY)
6157 WILL_LJMP(lua_error(L));
6158
6159 return hlua_http_get_headers(L, msg);
6160}
6161
6162/* Deletes all occurrences of an header in the HTTP message matching on its
6163 * name. It relies on hlua_http_del_hdr().
6164 */
6165__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6166{
6167 struct http_msg *msg;
6168
6169 MAY_LJMP(check_args(L, 2, "del_header"));
6170 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6171
6172 if (msg->msg_state > HTTP_MSG_BODY)
6173 WILL_LJMP(lua_error(L));
6174
6175 return hlua_http_del_hdr(L, msg);
6176}
6177
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006178/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006179 * message given its name against a regex and replaces it if it matches. It
6180 * relies on hlua_http_rep_hdr().
6181 */
6182__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6183{
6184 struct http_msg *msg;
6185
6186 MAY_LJMP(check_args(L, 4, "rep_header"));
6187 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6188
6189 if (msg->msg_state > HTTP_MSG_BODY)
6190 WILL_LJMP(lua_error(L));
6191
6192 return hlua_http_rep_hdr(L, msg, 1);
6193}
6194
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006195/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006196 * message given its name against a regex and replaces it if it matches. It
6197 * relies on hlua_http_rep_hdr().
6198 */
6199__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6200{
6201 struct http_msg *msg;
6202
6203 MAY_LJMP(check_args(L, 4, "rep_value"));
6204 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6205
6206 if (msg->msg_state > HTTP_MSG_BODY)
6207 WILL_LJMP(lua_error(L));
6208
6209 return hlua_http_rep_hdr(L, msg, 0);
6210}
6211
6212/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6213__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6214{
6215 struct http_msg *msg;
6216
6217 MAY_LJMP(check_args(L, 3, "add_header"));
6218 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6219
6220 if (msg->msg_state > HTTP_MSG_BODY)
6221 WILL_LJMP(lua_error(L));
6222
6223 return hlua_http_add_hdr(L, msg);
6224}
6225
6226/* Add an header in the HTTP message removing existing headers with the same
6227 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6228 */
6229__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6230{
6231 struct http_msg *msg;
6232
6233 MAY_LJMP(check_args(L, 3, "set_header"));
6234 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6235
6236 if (msg->msg_state > HTTP_MSG_BODY)
6237 WILL_LJMP(lua_error(L));
6238
6239 hlua_http_del_hdr(L, msg);
6240 return hlua_http_add_hdr(L, msg);
6241}
6242
6243/* Rewrites the request method. It relies on http_req_replace_stline(). */
6244__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6245{
6246 struct stream *s;
6247 struct http_msg *msg;
6248 const char *name;
6249 size_t name_len;
6250
6251 MAY_LJMP(check_args(L, 2, "set_method"));
6252 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6253 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6254
6255 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6256 WILL_LJMP(lua_error(L));
6257
6258 s = chn_strm(msg->chn);
6259 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6260 return 1;
6261}
6262
6263/* Rewrites the request path. It relies on http_req_replace_stline(). */
6264__LJMP static int hlua_http_msg_set_path(lua_State *L)
6265{
6266 struct stream *s;
6267 struct http_msg *msg;
6268 const char *name;
6269 size_t name_len;
6270
6271 MAY_LJMP(check_args(L, 2, "set_path"));
6272 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6273 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6274
6275 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6276 WILL_LJMP(lua_error(L));
6277
6278 s = chn_strm(msg->chn);
6279 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6280 return 1;
6281}
6282
6283/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6284__LJMP static int hlua_http_msg_set_query(lua_State *L)
6285{
6286 struct stream *s;
6287 struct http_msg *msg;
6288 const char *name;
6289 size_t name_len;
6290
6291 MAY_LJMP(check_args(L, 2, "set_query"));
6292 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6293 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6294
6295 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6296 WILL_LJMP(lua_error(L));
6297
6298 /* Check length. */
6299 if (name_len > trash.size - 1) {
6300 lua_pushboolean(L, 0);
6301 return 1;
6302 }
6303
6304 /* Add the mark question as prefix. */
6305 chunk_reset(&trash);
6306 trash.area[trash.data++] = '?';
6307 memcpy(trash.area + trash.data, name, name_len);
6308 trash.data += name_len;
6309
6310 s = chn_strm(msg->chn);
6311 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6312 return 1;
6313}
6314
6315/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6316__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6317{
6318 struct stream *s;
6319 struct http_msg *msg;
6320 const char *name;
6321 size_t name_len;
6322
6323 MAY_LJMP(check_args(L, 2, "set_uri"));
6324 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6325 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6326
6327 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6328 WILL_LJMP(lua_error(L));
6329
6330 s = chn_strm(msg->chn);
6331 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6332 return 1;
6333}
6334
6335/* Rewrites the response status code. It relies on http_res_set_status(). */
6336__LJMP static int hlua_http_msg_set_status(lua_State *L)
6337{
6338 struct http_msg *msg;
6339 unsigned int code;
6340 const char *reason;
6341 size_t reason_len;
6342
6343 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6344 code = MAY_LJMP(luaL_checkinteger(L, 2));
6345 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6346
6347 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6348 WILL_LJMP(lua_error(L));
6349
6350 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6351 return 1;
6352}
6353
6354/* Returns true if the HTTP message is full. */
6355__LJMP static int hlua_http_msg_is_full(lua_State *L)
6356{
6357 struct http_msg *msg;
6358
6359 MAY_LJMP(check_args(L, 1, "is_full"));
6360 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6361 lua_pushboolean(L, channel_full(msg->chn, 0));
6362 return 1;
6363}
6364
6365/* Returns true if the HTTP message may still receive data. */
6366__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6367{
6368 struct http_msg *msg;
6369 struct htx *htx;
6370
6371 MAY_LJMP(check_args(L, 1, "may_recv"));
6372 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6373 htx = htxbuf(&msg->chn->buf);
6374 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6375 return 1;
6376}
6377
6378/* Returns true if the HTTP message EOM was received */
6379__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6380{
6381 struct http_msg *msg;
6382 struct htx *htx;
6383
6384 MAY_LJMP(check_args(L, 1, "may_recv"));
6385 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6386 htx = htxbuf(&msg->chn->buf);
6387 lua_pushboolean(L, !htx_expect_more(htx));
6388 return 1;
6389}
6390
6391/* Returns the number of bytes available in the input side of the HTTP
6392 * message. This function never fails.
6393 */
6394__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6395{
6396 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006397 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006398
6399 MAY_LJMP(check_args(L, 1, "input"));
6400 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006401 hlua_http_msg_filter(L, 1, msg, &output, &input);
6402 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006403 return 1;
6404}
6405
6406/* Returns the number of bytes available in the output side of the HTTP
6407 * message. This function never fails.
6408 */
6409__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6410{
6411 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006412 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006413
6414 MAY_LJMP(check_args(L, 1, "output"));
6415 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006416 hlua_http_msg_filter(L, 1, msg, &output, &input);
6417 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006418 return 1;
6419}
6420
6421/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6422 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006423 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006424 * block. This function is called during the payload filtering, so the headers
6425 * are already scheduled for output (from the filter point of view).
6426 */
6427static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6428{
6429 struct htx *htx = htxbuf(&msg->chn->buf);
6430 struct htx_blk *blk;
6431 struct htx_ret htxret;
6432 luaL_Buffer b;
6433 int ret = 0;
6434
6435 luaL_buffinit(L, &b);
6436 htxret = htx_find_offset(htx, offset);
6437 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6438 enum htx_blk_type type = htx_get_blk_type(blk);
6439 struct ist v;
6440
6441 switch (type) {
6442 case HTX_BLK_UNUSED:
6443 break;
6444
6445 case HTX_BLK_DATA:
6446 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006447 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006448 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006449
6450 luaL_addlstring(&b, v.ptr, v.len);
6451 ret += v.len;
6452 break;
6453
6454 default:
vishnu0af4bd72021-10-24 06:46:24 +05306455 if (!ret)
6456 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006457 goto end;
6458 }
6459 offset = 0;
6460 }
6461
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006462end:
vishnu0af4bd72021-10-24 06:46:24 +05306463 if (!ret && (htx->flags & HTX_FL_EOM))
6464 goto no_data;
6465 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006466 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306467
6468 no_data:
6469 /* Remove the empty string and push nil on the stack */
6470 lua_pop(L, 1);
6471 lua_pushnil(L);
6472 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006473}
6474
6475/* Copies the string <str> to the HTTP message <msg> at the offset
6476 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006477 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006478 * the filter context.
6479 */
6480static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6481{
6482 struct htx *htx = htx_from_buf(&msg->chn->buf);
6483 struct htx_ret htxret;
6484 int /*max, */ret = 0;
6485
6486 /* Nothing to do, just return */
6487 if (unlikely(istlen(str) == 0))
6488 goto end;
6489
6490 if (istlen(str) > htx_free_data_space(htx)) {
6491 ret = -1;
6492 goto end;
6493 }
6494
6495 htxret = htx_find_offset(htx, offset);
6496 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6497 if (!htx_add_last_data(htx, str))
6498 goto end;
6499 }
6500 else {
6501 struct ist v = htx_get_blk_value(htx, htxret.blk);
6502 v.ptr += htxret.ret;
6503 v.len = 0;
6504 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6505 goto end;
6506 }
6507 ret = str.len;
6508 if (ret) {
6509 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6510 flt_update_offsets(filter, msg->chn, ret);
6511 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6512 }
6513
6514 end:
6515 htx_to_buf(htx, &msg->chn->buf);
6516 return ret;
6517}
6518
6519/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6520 * position <offset>. It stops on the first non-DATA HTX block. This function is
6521 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006522 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006523 * update the filter context.
6524 */
6525static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6526{
6527 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6528 struct htx *htx = htx_from_buf(&msg->chn->buf);
6529 struct htx_blk *blk;
6530 struct htx_ret htxret;
6531 size_t ret = 0;
6532
6533 /* Be sure <len> is always the amount of DATA to remove */
6534 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006535 /* When htx tail type == HTX_BLK_DATA, no need to take care
6536 * of special blocks like HTX_BLK_EOT.
6537 * We simply truncate after offset
6538 * (truncate targeted blk and discard the following ones)
6539 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006540 htx_truncate(htx, offset);
6541 ret = len;
6542 goto end;
6543 }
6544
6545 htxret = htx_find_offset(htx, offset);
6546 blk = htxret.blk;
6547 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006548 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006549 struct ist v;
6550
6551 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6552 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006553
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006554 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006555 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006556
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006557 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006558 /* trimming data in blk: discard everything after the offset
6559 * (replace 'v' with 'IST_NULL')
6560 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006561 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006562 if (blk && v.len < len) {
6563 /* In this case, caller wants to keep removing data,
6564 * but we need to spare current blk
6565 * because it was already trimmed
6566 */
6567 blk = htx_get_next_blk(htx, blk);
6568 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006569 len -= v.len;
6570 ret += v.len;
6571 }
6572
6573
6574 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006575 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006576 enum htx_blk_type type = htx_get_blk_type(blk);
6577 uint32_t sz = htx_get_blksz(blk);
6578
6579 switch (type) {
6580 case HTX_BLK_UNUSED:
6581 break;
6582
6583 case HTX_BLK_DATA:
6584 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006585 /* don't discard whole blk, only part of it
6586 * (from the beginning)
6587 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006588 htx_cut_data_blk(htx, blk, len);
6589 ret += len;
6590 goto end;
6591 }
6592 break;
6593
6594 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006595 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006596 goto end;
6597 }
6598
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006599 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006600 len -= sz;
6601 ret += sz;
6602 blk = htx_remove_blk(htx, blk);
6603 }
6604
6605end:
6606 flt_update_offsets(filter, msg->chn, -ret);
6607 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6608 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6609 * to loose the EOM flag if the message is empty.
6610 */
6611}
6612
6613/* Copies input data found in an HTTP message. Unlike the channel function used
6614 * to duplicate raw data, this one can only be called inside a filter, from
6615 * http_payload callback. So it cannot yield. An exception is returned if it is
6616 * called from another callback. If nothing was copied, a nil value is pushed on
6617 * the stack.
6618 */
6619__LJMP static int hlua_http_msg_get_body(lua_State *L)
6620{
6621 struct http_msg *msg;
6622 struct filter *filter;
6623 size_t output, input;
6624 int offset, len;
6625
6626 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6627 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6628 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6629
6630 if (msg->msg_state < HTTP_MSG_DATA)
6631 WILL_LJMP(lua_error(L));
6632
6633 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6634 if (!filter || !hlua_filter_from_payload(filter))
6635 WILL_LJMP(lua_error(L));
6636
6637 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6638 lua_pushnil(L);
6639 return 1;
6640 }
6641
6642 offset = output;
6643 if (lua_gettop(L) > 1) {
6644 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6645 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006646 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006647 offset += output;
6648 if (offset < output || offset > input + output) {
6649 lua_pushfstring(L, "offset out of range.");
6650 WILL_LJMP(lua_error(L));
6651 }
6652 }
6653 len = output + input - offset;
6654 if (lua_gettop(L) == 3) {
6655 len = MAY_LJMP(luaL_checkinteger(L, 3));
6656 if (!len)
6657 goto dup;
6658 if (len == -1)
6659 len = global.tune.bufsize;
6660 if (len < 0) {
6661 lua_pushfstring(L, "length out of range.");
6662 WILL_LJMP(lua_error(L));
6663 }
6664 }
6665
6666 dup:
6667 _hlua_http_msg_dup(msg, L, offset, len);
6668 return 1;
6669}
6670
6671/* Appends a string to the HTTP message, after all existing DATA blocks but
6672 * before the trailers, if any. It returns the amount of data written or -1 if
6673 * nothing was copied. Unlike the channel function used to append data, this one
6674 * can only be called inside a filter, from http_payload callback. So it cannot
6675 * yield. An exception is returned if it is called from another callback.
6676 */
6677__LJMP static int hlua_http_msg_append(lua_State *L)
6678{
6679 struct http_msg *msg;
6680 struct filter *filter;
6681 const char *str;
6682 size_t offset, len, sz;
6683 int ret;
6684
6685 MAY_LJMP(check_args(L, 2, "append"));
6686 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6687
6688 if (msg->msg_state < HTTP_MSG_DATA)
6689 WILL_LJMP(lua_error(L));
6690
6691 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6692 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6693 if (!filter || !hlua_filter_from_payload(filter))
6694 WILL_LJMP(lua_error(L));
6695
6696 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6697 lua_pushinteger(L, ret);
6698 return 1;
6699}
6700
6701/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6702 * returns the amount of data written or -1 if nothing was copied. Unlike the
6703 * channel function used to prepend data, this one can only be called inside a
6704 * filter, from http_payload callback. So it cannot yield. An exception is
6705 * returned if it is called from another callback.
6706 */
6707__LJMP static int hlua_http_msg_prepend(lua_State *L)
6708{
6709 struct http_msg *msg;
6710 struct filter *filter;
6711 const char *str;
6712 size_t offset, len, sz;
6713 int ret;
6714
6715 MAY_LJMP(check_args(L, 2, "prepend"));
6716 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006717
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006718 if (msg->msg_state < HTTP_MSG_DATA)
6719 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006720
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006721 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6722 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6723 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006724 WILL_LJMP(lua_error(L));
6725
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/* Inserts a string to the HTTP message at a given offset. By default the string
6732 * is appended at the end of DATA blocks. It returns the amount of data written
6733 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6734 * this one can only be called inside a filter, from http_payload callback. So
6735 * it cannot yield. An exception is returned if it is called from another
6736 * callback.
6737 */
6738__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006739{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006740 struct http_msg *msg;
6741 struct filter *filter;
6742 const char *str;
6743 size_t input, output, sz;
6744 int offset;
6745 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006746
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006747 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6748 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006749 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006750
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006751 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006752 WILL_LJMP(lua_error(L));
6753
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006754 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006755 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006756 if (!filter || !hlua_filter_from_payload(filter))
6757 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006758
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006759 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006760 if (lua_gettop(L) > 2) {
6761 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6762 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006763 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006764 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006765 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006766 lua_pushfstring(L, "offset out of range.");
6767 WILL_LJMP(lua_error(L));
6768 }
6769 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006770
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006771 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6772 lua_pushinteger(L, ret);
6773 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006774}
6775
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006776/* Removes a given amount of data from the HTTP message at a given offset. By
6777 * default all DATA blocks are removed. It returns the amount of data
6778 * removed. Unlike the channel function used to remove data, this one can only
6779 * be called inside a filter, from http_payload callback. So it cannot yield. An
6780 * exception is returned if it is called from another callback.
6781 */
6782__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006783{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006784 struct http_msg *msg;
6785 struct filter *filter;
6786 size_t input, output;
6787 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006788
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006789 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006790 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006791 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006792
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006793 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006794 WILL_LJMP(lua_error(L));
6795
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006796 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006797 if (!filter || !hlua_filter_from_payload(filter))
6798 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006799
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006800 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006801 if (lua_gettop(L) > 1) {
6802 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006803 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006804 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006805 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006806 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006807 lua_pushfstring(L, "offset out of range.");
6808 WILL_LJMP(lua_error(L));
6809 }
6810 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006811
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006812 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006813 if (lua_gettop(L) == 3) {
6814 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006815 if (!len)
6816 goto end;
6817 if (len == -1)
6818 len = output + input - offset;
6819 if (len < 0 || offset + len > output + input) {
6820 lua_pushfstring(L, "length out of range.");
6821 WILL_LJMP(lua_error(L));
6822 }
6823 }
6824
6825 _hlua_http_msg_delete(msg, filter, offset, len);
6826
6827 end:
6828 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006829 return 1;
6830}
6831
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006832/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006833 * all remaining data are removed, accordingly to the filter context. It returns
6834 * the amount of data written or -1 if nothing was copied. Unlike the channel
6835 * function used to replace data, this one can only be called inside a filter,
6836 * from http_payload callback. So it cannot yield. An exception is returned if
6837 * it is called from another callback.
6838 */
6839__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006840{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006841 struct http_msg *msg;
6842 struct filter *filter;
6843 struct htx *htx;
6844 const char *str;
6845 size_t input, output, sz;
6846 int offset, len;
6847 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006848
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006849 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6850 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6851 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6852
6853 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006854 WILL_LJMP(lua_error(L));
6855
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006856 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6857 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6858 if (!filter || !hlua_filter_from_payload(filter))
6859 WILL_LJMP(lua_error(L));
6860
6861 offset = output;
6862 if (lua_gettop(L) > 2) {
6863 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6864 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006865 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006866 offset += output;
6867 if (offset < output || offset > input + output) {
6868 lua_pushfstring(L, "offset out of range.");
6869 WILL_LJMP(lua_error(L));
6870 }
6871 }
6872
6873 len = output + input - offset;
6874 if (lua_gettop(L) == 4) {
6875 len = MAY_LJMP(luaL_checkinteger(L, 4));
6876 if (!len)
6877 goto set;
6878 if (len == -1)
6879 len = output + input - offset;
6880 if (len < 0 || offset + len > output + input) {
6881 lua_pushfstring(L, "length out of range.");
6882 WILL_LJMP(lua_error(L));
6883 }
6884 }
6885
6886 set:
6887 /* Be sure we can copied the string once input data will be removed. */
6888 htx = htx_from_buf(&msg->chn->buf);
6889 if (sz > htx_free_data_space(htx) + len)
6890 lua_pushinteger(L, -1);
6891 else {
6892 _hlua_http_msg_delete(msg, filter, offset, len);
6893 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6894 lua_pushinteger(L, ret);
6895 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006896 return 1;
6897}
6898
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006899/* Prepends data into an HTTP message and forward it, from the filter point of
6900 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6901 * the channel function used to send data, this one can only be called inside a
6902 * filter, from http_payload callback. So it cannot yield. An exception is
6903 * returned if it is called from another callback.
6904 */
6905__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006906{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006907 struct http_msg *msg;
6908 struct filter *filter;
6909 struct htx *htx;
6910 const char *str;
6911 size_t offset, len, sz;
6912 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006913
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006914 MAY_LJMP(check_args(L, 2, "send"));
6915 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6916
6917 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006918 WILL_LJMP(lua_error(L));
6919
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006920 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6921 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6922 if (!filter || !hlua_filter_from_payload(filter))
6923 WILL_LJMP(lua_error(L));
6924
6925 /* Return an error if the channel's output is closed */
6926 if (unlikely(channel_output_closed(msg->chn))) {
6927 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006928 return 1;
6929 }
6930
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006931 htx = htx_from_buf(&msg->chn->buf);
6932 if (sz > htx_free_data_space(htx)) {
6933 lua_pushinteger(L, -1);
6934 return 1;
6935 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006936
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006937 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6938 if (ret > 0) {
6939 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6940
6941 FLT_OFF(filter, msg->chn) += ret;
6942 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6943 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6944 }
6945
6946 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006947 return 1;
6948}
6949
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006950/* Forwards a given amount of bytes. It return -1 if the channel's output is
6951 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6952 * channel function used to forward data, this one can only be called inside a
6953 * filter, from http_payload callback. So it cannot yield. An exception is
6954 * returned if it is called from another callback. All other functions deal with
6955 * DATA block, this one not.
6956*/
6957__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006958{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006959 struct http_msg *msg;
6960 struct filter *filter;
6961 size_t offset, len;
6962 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006963
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006964 MAY_LJMP(check_args(L, 2, "forward"));
6965 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6966
6967 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006968 WILL_LJMP(lua_error(L));
6969
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006970 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6971 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6972 if (!filter || !hlua_filter_from_payload(filter))
6973 WILL_LJMP(lua_error(L));
6974
6975 /* Nothing to do, just return */
6976 if (!fwd)
6977 goto end;
6978
6979 /* Return an error if the channel's output is closed */
6980 if (unlikely(channel_output_closed(msg->chn))) {
6981 ret = -1;
6982 goto end;
6983 }
6984
6985 ret = fwd;
6986 if (ret > len)
6987 ret = len;
6988
6989 if (ret) {
6990 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6991
6992 FLT_OFF(filter, msg->chn) += ret;
6993 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6994 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6995 }
6996
6997 end:
6998 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006999 return 1;
7000}
7001
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007002/* Set EOM flag on the HTX message.
7003 *
7004 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7005 * really know how to do without this feature.
7006 */
7007__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007008{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007009 struct http_msg *msg;
7010 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007011
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007012 MAY_LJMP(check_args(L, 1, "set_eom"));
7013 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7014 htx = htxbuf(&msg->chn->buf);
7015 htx->flags |= HTX_FL_EOM;
7016 return 0;
7017}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007018
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007019/* Unset EOM flag on the HTX message.
7020 *
7021 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7022 * really know how to do without this feature.
7023 */
7024__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7025{
7026 struct http_msg *msg;
7027 struct htx *htx;
7028
7029 MAY_LJMP(check_args(L, 1, "set_eom"));
7030 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7031 htx = htxbuf(&msg->chn->buf);
7032 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007033 return 0;
7034}
7035
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007036/*
7037 *
7038 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007039 * Class HTTPClient
7040 *
7041 *
7042 */
7043__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7044{
7045 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7046}
7047
William Lallemandf77f1de2021-09-28 19:10:38 +02007048
7049/* stops the httpclient and ask it to kill itself */
7050__LJMP static int hlua_httpclient_gc(lua_State *L)
7051{
7052 struct hlua_httpclient *hlua_hc;
7053
7054 MAY_LJMP(check_args(L, 1, "__gc"));
7055
7056 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7057
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007058 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7059 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007060 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007061 hlua_hc->hc = NULL;
7062 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007063
7064 return 0;
7065}
7066
7067
William Lallemand3956c4e2021-09-21 16:25:15 +02007068__LJMP static int hlua_httpclient_new(lua_State *L)
7069{
7070 struct hlua_httpclient *hlua_hc;
7071 struct hlua *hlua;
7072
7073 /* Get hlua struct, or NULL if we execute from main lua state */
7074 hlua = hlua_gethlua(L);
7075 if (!hlua)
7076 return 0;
7077
7078 /* Check stack size. */
7079 if (!lua_checkstack(L, 3)) {
7080 hlua_pusherror(L, "httpclient: full stack");
7081 goto err;
7082 }
7083 /* Create the object: obj[0] = userdata. */
7084 lua_newtable(L);
7085 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7086 lua_rawseti(L, -2, 0);
7087 memset(hlua_hc, 0, sizeof(*hlua_hc));
7088
7089 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7090 if (!hlua_hc->hc)
7091 goto err;
7092
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007093 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007094
William Lallemand3956c4e2021-09-21 16:25:15 +02007095 /* Pop a class stream metatable and affect it to the userdata. */
7096 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7097 lua_setmetatable(L, -2);
7098
7099 return 1;
7100
7101 err:
7102 WILL_LJMP(lua_error(L));
7103 return 0;
7104}
7105
7106
7107/*
7108 * Callback of the httpclient, this callback wakes the lua task up, once the
7109 * httpclient receives some data
7110 *
7111 */
7112
William Lallemandbd5739e2021-10-28 15:41:38 +02007113static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007114{
7115 struct hlua *hlua = hc->caller;
7116
7117 if (!hlua || !hlua->task)
7118 return;
7119
7120 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7121}
7122
7123/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007124 * Fill the lua stack with headers from the httpclient response
7125 * This works the same way as the hlua_http_get_headers() function
7126 */
7127__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7128{
7129 struct http_hdr *hdr;
7130
7131 lua_newtable(L);
7132
William Lallemandef574b22021-10-05 16:19:31 +02007133 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007134 struct ist n, v;
7135 int len;
7136
7137 n = hdr->n;
7138 v = hdr->v;
7139
7140 /* Check for existing entry:
7141 * assume that the table is on the top of the stack, and
7142 * push the key in the stack, the function lua_gettable()
7143 * perform the lookup.
7144 */
7145
7146 lua_pushlstring(L, n.ptr, n.len);
7147 lua_gettable(L, -2);
7148
7149 switch (lua_type(L, -1)) {
7150 case LUA_TNIL:
7151 /* Table not found, create it. */
7152 lua_pop(L, 1); /* remove the nil value. */
7153 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7154 lua_newtable(L); /* create and push empty table. */
7155 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7156 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7157 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7158 break;
7159
7160 case LUA_TTABLE:
7161 /* Entry found: push the value in the table. */
7162 len = lua_rawlen(L, -1);
7163 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7164 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7165 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7166 break;
7167
7168 default:
7169 /* Other cases are errors. */
7170 hlua_pusherror(L, "internal error during the parsing of headers.");
7171 WILL_LJMP(lua_error(L));
7172 }
7173 }
7174 return 1;
7175}
7176
7177/*
William Lallemand746e6f32021-10-06 10:57:44 +02007178 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7179 *
7180 * Caller must free the result
7181 */
7182struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7183{
7184 struct http_hdr hdrs[global.tune.max_http_hdr];
7185 struct http_hdr *result = NULL;
7186 uint32_t hdr_num = 0;
7187
7188 lua_pushnil(L);
7189 while (lua_next(L, -2) != 0) {
7190 struct ist name, value;
7191 const char *n, *v;
7192 size_t nlen, vlen;
7193
7194 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7195 /* Skip element if the key is not a string or if the value is not a table */
7196 goto next_hdr;
7197 }
7198
7199 n = lua_tolstring(L, -2, &nlen);
7200 name = ist2(n, nlen);
7201
7202 /* Loop on header's values */
7203 lua_pushnil(L);
7204 while (lua_next(L, -2)) {
7205 if (!lua_isstring(L, -1)) {
7206 /* Skip the value if it is not a string */
7207 goto next_value;
7208 }
7209
7210 v = lua_tolstring(L, -1, &vlen);
7211 value = ist2(v, vlen);
7212 name = ist2(n, nlen);
7213
7214 hdrs[hdr_num].n = istdup(name);
7215 hdrs[hdr_num].v = istdup(value);
7216
7217 hdr_num++;
7218
7219 next_value:
7220 lua_pop(L, 1);
7221 }
7222
7223 next_hdr:
7224 lua_pop(L, 1);
7225
7226 }
7227
7228 if (hdr_num) {
7229 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007230 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007231 if (!result)
7232 goto skip_headers;
7233 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7234
7235 result[hdr_num].n = IST_NULL;
7236 result[hdr_num].v = IST_NULL;
7237 }
7238
7239skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007240
7241 return result;
7242}
7243
7244
William Lallemandbd5739e2021-10-28 15:41:38 +02007245/*
7246 * For each yield, checks if there is some data in the httpclient and push them
7247 * in the lua buffer, once the httpclient finished its job, push the result on
7248 * the stack
7249 */
7250__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7251{
7252 struct buffer *tr;
7253 int res;
7254 struct hlua *hlua = hlua_gethlua(L);
7255 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7256
7257
7258 tr = get_trash_chunk();
7259
7260 res = httpclient_res_xfer(hlua_hc->hc, tr);
7261 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7262
7263 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7264
7265 luaL_pushresult(&hlua_hc->b);
7266 lua_settable(L, -3);
7267
7268 lua_pushstring(L, "status");
7269 lua_pushinteger(L, hlua_hc->hc->res.status);
7270 lua_settable(L, -3);
7271
7272
7273 lua_pushstring(L, "reason");
7274 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7275 lua_settable(L, -3);
7276
7277 lua_pushstring(L, "headers");
7278 hlua_httpclient_get_headers(L, hlua_hc);
7279 lua_settable(L, -3);
7280
7281 return 1;
7282 }
7283
7284 if (httpclient_data(hlua_hc->hc))
7285 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7286
7287 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7288
7289 return 0;
7290}
7291
7292/*
7293 * Call this when trying to stream a body during a request
7294 */
7295__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7296{
7297 struct hlua *hlua;
7298 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7299 const char *body_str = NULL;
7300 int ret;
7301 int end = 0;
7302 size_t buf_len;
7303 size_t to_send = 0;
7304
7305 hlua = hlua_gethlua(L);
7306
7307 if (!hlua || !hlua->task)
7308 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7309 "'frontend', 'backend' or 'task'"));
7310
7311 ret = lua_getfield(L, -1, "body");
7312 if (ret != LUA_TSTRING)
7313 goto rcv;
7314
7315 body_str = lua_tolstring(L, -1, &buf_len);
7316 lua_pop(L, 1);
7317
Christopher Fauletfc591292022-01-12 14:46:03 +01007318 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007319
7320 if ((hlua_hc->sent + to_send) >= buf_len)
7321 end = 1;
7322
7323 /* the end flag is always set since we are using the whole remaining size */
7324 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7325
7326 if (buf_len > hlua_hc->sent) {
7327 /* still need to process the buffer */
7328 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7329 } else {
7330 goto rcv;
7331 /* we sent the whole request buffer we can recv */
7332 }
7333 return 0;
7334
7335rcv:
7336
7337 /* we return a "res" object */
7338 lua_newtable(L);
7339
William Lallemandbd5739e2021-10-28 15:41:38 +02007340 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007341 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007342
William Lallemand933fe392021-11-04 09:45:58 +01007343 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007344 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7345
7346 return 1;
7347}
William Lallemand746e6f32021-10-06 10:57:44 +02007348
William Lallemand3956c4e2021-09-21 16:25:15 +02007349/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007350 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007351 */
7352
William Lallemanddc2cc902021-10-26 11:43:26 +02007353__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007354{
7355 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007356 struct http_hdr *hdrs = NULL;
7357 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007358 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007359 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007360 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007361 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007362 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007363
7364 hlua = hlua_gethlua(L);
7365
7366 if (!hlua || !hlua->task)
7367 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7368 "'frontend', 'backend' or 'task'"));
7369
William Lallemand746e6f32021-10-06 10:57:44 +02007370 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7371 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7372
William Lallemand4f4f2b72022-02-17 20:00:23 +01007373 hlua_hc = hlua_checkhttpclient(L, 1);
7374
William Lallemand7177a952022-03-03 15:33:12 +01007375 lua_pushnil(L); /* first key */
7376 while (lua_next(L, 2)) {
7377 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7378 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7379 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007380
William Lallemand7177a952022-03-03 15:33:12 +01007381 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7382 if (lua_type(L, -1) != LUA_TSTRING)
7383 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7384 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007385
William Lallemand7177a952022-03-03 15:33:12 +01007386 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7387 if (lua_type(L, -1) != LUA_TNUMBER)
7388 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7389 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007390
William Lallemand7177a952022-03-03 15:33:12 +01007391 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7392 if (lua_type(L, -1) != LUA_TTABLE)
7393 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7394 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007395
William Lallemand7177a952022-03-03 15:33:12 +01007396 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7397 if (lua_type(L, -1) != LUA_TSTRING)
7398 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7399 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007400
William Lallemand7177a952022-03-03 15:33:12 +01007401 } else {
7402 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7403 }
7404 /* removes 'value'; keeps 'key' for next iteration */
7405 lua_pop(L, 1);
7406 }
William Lallemanddec25c32021-10-25 19:48:37 +02007407
William Lallemand746e6f32021-10-06 10:57:44 +02007408 if (!url_str) {
7409 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7410 return 0;
7411 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007412
William Lallemand10a37362022-03-02 16:18:26 +01007413 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007414
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007415 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007416 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007417 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007418
7419 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007420 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7421 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7422 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007423 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007424
William Lallemandbd5739e2021-10-28 15:41:38 +02007425 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007426 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007427 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7428 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007429
William Lallemandbd5739e2021-10-28 15:41:38 +02007430 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007431
William Lallemand746e6f32021-10-06 10:57:44 +02007432 /* free the temporary headers array */
7433 hdrs_i = hdrs;
7434 while (hdrs_i && isttest(hdrs_i->n)) {
7435 istfree(&hdrs_i->n);
7436 istfree(&hdrs_i->v);
7437 hdrs_i++;
7438 }
7439 ha_free(&hdrs);
7440
7441
William Lallemand6137a9e2021-10-26 15:01:53 +02007442 if (ret != ERR_NONE) {
7443 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7444 return 0;
7445 }
7446
William Lallemandc2d3db42022-04-26 11:46:13 +02007447 if (!httpclient_start(hlua_hc->hc))
7448 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007449
William Lallemandbd5739e2021-10-28 15:41:38 +02007450 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007451
William Lallemand3956c4e2021-09-21 16:25:15 +02007452 return 0;
7453}
7454
7455/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007456 * Sends an HTTP HEAD request and wait for a response
7457 *
7458 * httpclient:head(url, headers, payload)
7459 */
7460__LJMP static int hlua_httpclient_head(lua_State *L)
7461{
7462 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7463}
7464
7465/*
7466 * Send an HTTP GET request and wait for a response
7467 *
7468 * httpclient:get(url, headers, payload)
7469 */
7470__LJMP static int hlua_httpclient_get(lua_State *L)
7471{
7472 return hlua_httpclient_send(L, HTTP_METH_GET);
7473
7474}
7475
7476/*
7477 * Sends an HTTP PUT request and wait for a response
7478 *
7479 * httpclient:put(url, headers, payload)
7480 */
7481__LJMP static int hlua_httpclient_put(lua_State *L)
7482{
7483 return hlua_httpclient_send(L, HTTP_METH_PUT);
7484}
7485
7486/*
7487 * Send an HTTP POST request and wait for a response
7488 *
7489 * httpclient:post(url, headers, payload)
7490 */
7491__LJMP static int hlua_httpclient_post(lua_State *L)
7492{
7493 return hlua_httpclient_send(L, HTTP_METH_POST);
7494}
7495
7496
7497/*
7498 * Sends an HTTP DELETE request and wait for a response
7499 *
7500 * httpclient:delete(url, headers, payload)
7501 */
7502__LJMP static int hlua_httpclient_delete(lua_State *L)
7503{
7504 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7505}
7506
7507/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007508 *
7509 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007510 * Class TXN
7511 *
7512 *
7513 */
7514
7515/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007516 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007517 */
7518__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7519{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007520 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007521}
7522
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007523__LJMP static int hlua_set_var(lua_State *L)
7524{
7525 struct hlua_txn *htxn;
7526 const char *name;
7527 size_t len;
7528 struct sample smp;
7529
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007530 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7531 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007532
7533 /* It is useles to retrieve the stream, but this function
7534 * runs only in a stream context.
7535 */
7536 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7537 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7538
7539 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007540 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007541 hlua_lua2smp(L, 3, &smp);
7542
7543 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007544 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007545
7546 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7547 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7548 else
7549 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7550
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007551 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007552}
7553
Christopher Faulet85d79c92016-11-09 16:54:56 +01007554__LJMP static int hlua_unset_var(lua_State *L)
7555{
7556 struct hlua_txn *htxn;
7557 const char *name;
7558 size_t len;
7559 struct sample smp;
7560
7561 MAY_LJMP(check_args(L, 2, "unset_var"));
7562
7563 /* It is useles to retrieve the stream, but this function
7564 * runs only in a stream context.
7565 */
7566 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7567 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7568
7569 /* Unset the variable. */
7570 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007571 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7572 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007573}
7574
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007575__LJMP static int hlua_get_var(lua_State *L)
7576{
7577 struct hlua_txn *htxn;
7578 const char *name;
7579 size_t len;
7580 struct sample smp;
7581
7582 MAY_LJMP(check_args(L, 2, "get_var"));
7583
7584 /* It is useles to retrieve the stream, but this function
7585 * runs only in a stream context.
7586 */
7587 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7588 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7589
Willy Tarreau7560dd42016-03-10 16:28:58 +01007590 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007591 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007592 lua_pushnil(L);
7593 return 1;
7594 }
7595
7596 return hlua_smp2lua(L, &smp);
7597}
7598
Willy Tarreau59551662015-03-10 14:23:13 +01007599__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007600{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007601 struct hlua *hlua;
7602
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007603 MAY_LJMP(check_args(L, 2, "set_priv"));
7604
Willy Tarreau87b09662015-04-03 00:22:06 +02007605 /* It is useles to retrieve the stream, but this function
7606 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007607 */
7608 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007609
7610 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007611 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007612 if (!hlua)
7613 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007614
7615 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007616 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007617
7618 /* Get and store new value. */
7619 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7620 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7621
7622 return 0;
7623}
7624
Willy Tarreau59551662015-03-10 14:23:13 +01007625__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007626{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007627 struct hlua *hlua;
7628
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007629 MAY_LJMP(check_args(L, 1, "get_priv"));
7630
Willy Tarreau87b09662015-04-03 00:22:06 +02007631 /* It is useles to retrieve the stream, but this function
7632 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007633 */
7634 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007635
7636 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007637 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007638 if (!hlua) {
7639 lua_pushnil(L);
7640 return 1;
7641 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007642
7643 /* Push configuration index in the stack. */
7644 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7645
7646 return 1;
7647}
7648
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007649/* Create stack entry containing a class TXN. This function
7650 * return 0 if the stack does not contains free slots,
7651 * otherwise it returns 1.
7652 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007653static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007654{
Willy Tarreaude491382015-04-06 11:04:28 +02007655 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007656
7657 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007658 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007659 return 0;
7660
7661 /* NOTE: The allocation never fails. The failure
7662 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007663 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007664 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007665 /* Create the object: obj[0] = userdata. */
7666 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007667 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007668 lua_rawseti(L, -2, 0);
7669
Willy Tarreaude491382015-04-06 11:04:28 +02007670 htxn->s = s;
7671 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007672 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007673 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007674
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007675 /* Create the "f" field that contains a list of fetches. */
7676 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007677 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007678 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007679 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007680
7681 /* Create the "sf" field that contains a list of stringsafe fetches. */
7682 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007683 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007684 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007685 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007686
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007687 /* Create the "c" field that contains a list of converters. */
7688 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007689 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007690 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007691 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007692
7693 /* Create the "sc" field that contains a list of stringsafe converters. */
7694 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007695 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007696 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007697 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007698
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007699 /* Create the "req" field that contains the request channel object. */
7700 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007701 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007702 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007703 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007704
7705 /* Create the "res" field that contains the response channel object. */
7706 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007707 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007708 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007709 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007710
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007711 /* Creates the HTTP object is the current proxy allows http. */
7712 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007713 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007714 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007715 return 0;
7716 }
7717 else
7718 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007719 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007720
Christopher Faulet78c35472020-02-26 17:14:08 +01007721 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7722 /* HTTPMessage object are created when a lua TXN is created from
7723 * a filter context only
7724 */
7725
7726 /* Creates the HTTP-Request object is the current proxy allows http. */
7727 lua_pushstring(L, "http_req");
7728 if (p->mode == PR_MODE_HTTP) {
7729 if (!hlua_http_msg_new(L, &s->txn->req))
7730 return 0;
7731 }
7732 else
7733 lua_pushnil(L);
7734 lua_rawset(L, -3);
7735
7736 /* Creates the HTTP-Response object is the current proxy allows http. */
7737 lua_pushstring(L, "http_res");
7738 if (p->mode == PR_MODE_HTTP) {
7739 if (!hlua_http_msg_new(L, &s->txn->rsp))
7740 return 0;
7741 }
7742 else
7743 lua_pushnil(L);
7744 lua_rawset(L, -3);
7745 }
7746
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007747 /* Pop a class sesison metatable and affect it to the userdata. */
7748 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7749 lua_setmetatable(L, -2);
7750
7751 return 1;
7752}
7753
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007754__LJMP static int hlua_txn_deflog(lua_State *L)
7755{
7756 const char *msg;
7757 struct hlua_txn *htxn;
7758
7759 MAY_LJMP(check_args(L, 2, "deflog"));
7760 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7761 msg = MAY_LJMP(luaL_checkstring(L, 2));
7762
7763 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7764 return 0;
7765}
7766
7767__LJMP static int hlua_txn_log(lua_State *L)
7768{
7769 int level;
7770 const char *msg;
7771 struct hlua_txn *htxn;
7772
7773 MAY_LJMP(check_args(L, 3, "log"));
7774 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7775 level = MAY_LJMP(luaL_checkinteger(L, 2));
7776 msg = MAY_LJMP(luaL_checkstring(L, 3));
7777
7778 if (level < 0 || level >= NB_LOG_LEVELS)
7779 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7780
7781 hlua_sendlog(htxn->s->be, level, msg);
7782 return 0;
7783}
7784
7785__LJMP static int hlua_txn_log_debug(lua_State *L)
7786{
7787 const char *msg;
7788 struct hlua_txn *htxn;
7789
7790 MAY_LJMP(check_args(L, 2, "Debug"));
7791 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7792 msg = MAY_LJMP(luaL_checkstring(L, 2));
7793 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7794 return 0;
7795}
7796
7797__LJMP static int hlua_txn_log_info(lua_State *L)
7798{
7799 const char *msg;
7800 struct hlua_txn *htxn;
7801
7802 MAY_LJMP(check_args(L, 2, "Info"));
7803 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7804 msg = MAY_LJMP(luaL_checkstring(L, 2));
7805 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7806 return 0;
7807}
7808
7809__LJMP static int hlua_txn_log_warning(lua_State *L)
7810{
7811 const char *msg;
7812 struct hlua_txn *htxn;
7813
7814 MAY_LJMP(check_args(L, 2, "Warning"));
7815 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7816 msg = MAY_LJMP(luaL_checkstring(L, 2));
7817 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7818 return 0;
7819}
7820
7821__LJMP static int hlua_txn_log_alert(lua_State *L)
7822{
7823 const char *msg;
7824 struct hlua_txn *htxn;
7825
7826 MAY_LJMP(check_args(L, 2, "Alert"));
7827 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7828 msg = MAY_LJMP(luaL_checkstring(L, 2));
7829 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7830 return 0;
7831}
7832
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007833__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7834{
7835 struct hlua_txn *htxn;
7836 int ll;
7837
7838 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7839 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7840 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7841
7842 if (ll < 0 || ll > 7)
7843 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7844
7845 htxn->s->logs.level = ll;
7846 return 0;
7847}
7848
7849__LJMP static int hlua_txn_set_tos(lua_State *L)
7850{
7851 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007852 int tos;
7853
7854 MAY_LJMP(check_args(L, 2, "set_tos"));
7855 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7856 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7857
Willy Tarreau1a18b542018-12-11 16:37:42 +01007858 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007859 return 0;
7860}
7861
7862__LJMP static int hlua_txn_set_mark(lua_State *L)
7863{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007864 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007865 int mark;
7866
7867 MAY_LJMP(check_args(L, 2, "set_mark"));
7868 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7869 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7870
Lukas Tribus579e3e32019-08-11 18:03:45 +02007871 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007872 return 0;
7873}
7874
Patrick Hemmer268a7072018-05-11 12:52:31 -04007875__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7876{
7877 struct hlua_txn *htxn;
7878
7879 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7880 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7881 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7882 return 0;
7883}
7884
7885__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7886{
7887 struct hlua_txn *htxn;
7888
7889 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7890 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7891 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7892 return 0;
7893}
7894
Christopher Faulet700d9e82020-01-31 12:21:52 +01007895/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007896 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007897 * message and terminate the transaction. It returns 1 on success and 0 on
7898 * error. The Reply must be on top of the stack.
7899 */
7900__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7901{
7902 struct htx *htx;
7903 struct htx_sl *sl;
7904 struct h1m h1m;
7905 const char *status, *reason, *body;
7906 size_t status_len, reason_len, body_len;
7907 int ret, code, flags;
7908
7909 code = 200;
7910 status = "200";
7911 status_len = 3;
7912 ret = lua_getfield(L, -1, "status");
7913 if (ret == LUA_TNUMBER) {
7914 code = lua_tointeger(L, -1);
7915 status = lua_tolstring(L, -1, &status_len);
7916 }
7917 lua_pop(L, 1);
7918
7919 reason = http_get_reason(code);
7920 reason_len = strlen(reason);
7921 ret = lua_getfield(L, -1, "reason");
7922 if (ret == LUA_TSTRING)
7923 reason = lua_tolstring(L, -1, &reason_len);
7924 lua_pop(L, 1);
7925
7926 body = NULL;
7927 body_len = 0;
7928 ret = lua_getfield(L, -1, "body");
7929 if (ret == LUA_TSTRING)
7930 body = lua_tolstring(L, -1, &body_len);
7931 lua_pop(L, 1);
7932
7933 /* Prepare the response before inserting the headers */
7934 h1m_init_res(&h1m);
7935 htx = htx_from_buf(&s->res.buf);
7936 channel_htx_truncate(&s->res, htx);
7937 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7938 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7939 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7940 ist2(status, status_len), ist2(reason, reason_len));
7941 }
7942 else {
7943 flags = HTX_SL_F_IS_RESP;
7944 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7945 ist2(status, status_len), ist2(reason, reason_len));
7946 }
7947 if (!sl)
7948 goto fail;
7949 sl->info.res.status = code;
7950
7951 /* Push in the stack the "headers" entry. */
7952 ret = lua_getfield(L, -1, "headers");
7953 if (ret != LUA_TTABLE)
7954 goto skip_headers;
7955
7956 lua_pushnil(L);
7957 while (lua_next(L, -2) != 0) {
7958 struct ist name, value;
7959 const char *n, *v;
7960 size_t nlen, vlen;
7961
7962 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7963 /* Skip element if the key is not a string or if the value is not a table */
7964 goto next_hdr;
7965 }
7966
7967 n = lua_tolstring(L, -2, &nlen);
7968 name = ist2(n, nlen);
7969 if (isteqi(name, ist("content-length"))) {
7970 /* Always skip content-length header. It will be added
7971 * later with the correct len
7972 */
7973 goto next_hdr;
7974 }
7975
7976 /* Loop on header's values */
7977 lua_pushnil(L);
7978 while (lua_next(L, -2)) {
7979 if (!lua_isstring(L, -1)) {
7980 /* Skip the value if it is not a string */
7981 goto next_value;
7982 }
7983
7984 v = lua_tolstring(L, -1, &vlen);
7985 value = ist2(v, vlen);
7986
7987 if (isteqi(name, ist("transfer-encoding")))
7988 h1_parse_xfer_enc_header(&h1m, value);
7989 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7990 goto fail;
7991
7992 next_value:
7993 lua_pop(L, 1);
7994 }
7995
7996 next_hdr:
7997 lua_pop(L, 1);
7998 }
7999 skip_headers:
8000 lua_pop(L, 1);
8001
8002 /* Update h1m flags: CLEN is set if CHNK is not present */
8003 if (!(h1m.flags & H1_MF_CHNK)) {
8004 const char *clen = ultoa(body_len);
8005
8006 h1m.flags |= H1_MF_CLEN;
8007 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8008 goto fail;
8009 }
8010 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8011 h1m.flags |= H1_MF_XFER_LEN;
8012
8013 /* Update HTX start-line flags */
8014 if (h1m.flags & H1_MF_XFER_ENC)
8015 flags |= HTX_SL_F_XFER_ENC;
8016 if (h1m.flags & H1_MF_XFER_LEN) {
8017 flags |= HTX_SL_F_XFER_LEN;
8018 if (h1m.flags & H1_MF_CHNK)
8019 flags |= HTX_SL_F_CHNK;
8020 else if (h1m.flags & H1_MF_CLEN)
8021 flags |= HTX_SL_F_CLEN;
8022 if (h1m.body_len == 0)
8023 flags |= HTX_SL_F_BODYLESS;
8024 }
8025 sl->flags |= flags;
8026
8027
8028 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008029 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008030 goto fail;
8031
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008032 htx->flags |= HTX_FL_EOM;
8033
Christopher Faulet700d9e82020-01-31 12:21:52 +01008034 /* Now, forward the response and terminate the transaction */
8035 s->txn->status = code;
8036 htx_to_buf(htx, &s->res.buf);
8037 if (!http_forward_proxy_resp(s, 1))
8038 goto fail;
8039
8040 return 1;
8041
8042 fail:
8043 channel_htx_truncate(&s->res, htx);
8044 return 0;
8045}
8046
8047/* Terminate a transaction if called from a lua action. For TCP streams,
8048 * processing is just aborted. Nothing is returned to the client and all
8049 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8050 * is forwarded to the client before terminating the transaction. On success,
8051 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8052 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8053 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008054 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008055__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008056{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008057 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008058 struct stream *s;
8059 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008060
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008061 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008062
Christopher Faulet700d9e82020-01-31 12:21:52 +01008063 /* If the flags NOTERM is set, we cannot terminate the session, so we
8064 * just end the execution of the current lua code. */
8065 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008066 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008067
Christopher Faulet700d9e82020-01-31 12:21:52 +01008068 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008069 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008070 struct channel *req = &s->req;
8071 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008072
Christopher Faulet700d9e82020-01-31 12:21:52 +01008073 channel_auto_read(req);
8074 channel_abort(req);
8075 channel_auto_close(req);
8076 channel_erase(req);
8077
Christopher Faulet700d9e82020-01-31 12:21:52 +01008078 channel_auto_read(res);
8079 channel_auto_close(res);
8080 channel_shutr_now(res);
8081
8082 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8083 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008084 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008085
Christopher Faulet700d9e82020-01-31 12:21:52 +01008086 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8087 /* No reply or invalid reply */
8088 s->txn->status = 0;
8089 http_reply_and_close(s, 0, NULL);
8090 }
8091 else {
8092 /* Remove extra args to have the reply on top of the stack */
8093 if (lua_gettop(L) > 2)
8094 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008095
Christopher Faulet700d9e82020-01-31 12:21:52 +01008096 if (!hlua_txn_forward_reply(L, s)) {
8097 if (!(s->flags & SF_ERR_MASK))
8098 s->flags |= SF_ERR_PRXCOND;
8099 lua_pushinteger(L, ACT_RET_ERR);
8100 WILL_LJMP(hlua_done(L));
8101 return 0; /* Never reached */
8102 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008103 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008104
Christopher Faulet700d9e82020-01-31 12:21:52 +01008105 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8106 if (htxn->dir == SMP_OPT_DIR_REQ) {
8107 /* let's log the request time */
8108 s->logs.tv_request = now;
8109 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008110 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008111 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008112
Christopher Faulet700d9e82020-01-31 12:21:52 +01008113 done:
8114 if (!(s->flags & SF_ERR_MASK))
8115 s->flags |= SF_ERR_LOCAL;
8116 if (!(s->flags & SF_FINST_MASK))
8117 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008118
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008119 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8120 lua_pushinteger(L, -1);
8121 else
8122 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008123 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008124 return 0;
8125}
8126
Christopher Faulet700d9e82020-01-31 12:21:52 +01008127/*
8128 *
8129 *
8130 * Class REPLY
8131 *
8132 *
8133 */
8134
8135/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8136 * free slots, the function fails and returns 0;
8137 */
8138static int hlua_txn_reply_new(lua_State *L)
8139{
8140 struct hlua_txn *htxn;
8141 const char *reason, *body = NULL;
8142 int ret, status;
8143
8144 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008145 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008146 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8147 WILL_LJMP(lua_error(L));
8148 }
8149
8150 /* Default value */
8151 status = 200;
8152 reason = http_get_reason(status);
8153
8154 if (lua_istable(L, 2)) {
8155 /* load status and reason from the table argument at index 2 */
8156 ret = lua_getfield(L, 2, "status");
8157 if (ret == LUA_TNIL)
8158 goto reason;
8159 else if (ret != LUA_TNUMBER) {
8160 /* invalid status: ignore the reason */
8161 goto body;
8162 }
8163 status = lua_tointeger(L, -1);
8164
8165 reason:
8166 lua_pop(L, 1); /* restore the stack: remove status */
8167 ret = lua_getfield(L, 2, "reason");
8168 if (ret == LUA_TSTRING)
8169 reason = lua_tostring(L, -1);
8170
8171 body:
8172 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8173 ret = lua_getfield(L, 2, "body");
8174 if (ret == LUA_TSTRING)
8175 body = lua_tostring(L, -1);
8176 lua_pop(L, 1); /* restore the stack: remove body */
8177 }
8178
8179 /* Create the Reply table */
8180 lua_newtable(L);
8181
8182 /* Add status element */
8183 lua_pushstring(L, "status");
8184 lua_pushinteger(L, status);
8185 lua_settable(L, -3);
8186
8187 /* Add reason element */
8188 reason = http_get_reason(status);
8189 lua_pushstring(L, "reason");
8190 lua_pushstring(L, reason);
8191 lua_settable(L, -3);
8192
8193 /* Add body element, nil if undefined */
8194 lua_pushstring(L, "body");
8195 if (body)
8196 lua_pushstring(L, body);
8197 else
8198 lua_pushnil(L);
8199 lua_settable(L, -3);
8200
8201 /* Add headers element */
8202 lua_pushstring(L, "headers");
8203 lua_newtable(L);
8204
8205 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8206 if (lua_istable(L, 2)) {
8207 /* load headers from the table argument at index 2. If it is a table, copy it. */
8208 ret = lua_getfield(L, 2, "headers");
8209 if (ret == LUA_TTABLE) {
8210 /* stack: [ ... <headers:table>, <table> ] */
8211 lua_pushnil(L);
8212 while (lua_next(L, -2) != 0) {
8213 /* stack: [ ... <headers:table>, <table>, k, v] */
8214 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8215 /* invalid value type, skip it */
8216 lua_pop(L, 1);
8217 continue;
8218 }
8219
8220
8221 /* Duplicate the key and swap it with the value. */
8222 lua_pushvalue(L, -2);
8223 lua_insert(L, -2);
8224 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8225
8226 lua_newtable(L);
8227 lua_insert(L, -2);
8228 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8229
8230 if (lua_isstring(L, -1)) {
8231 /* push the value in the inner table */
8232 lua_rawseti(L, -2, 1);
8233 }
8234 else { /* table */
8235 lua_pushnil(L);
8236 while (lua_next(L, -2) != 0) {
8237 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8238 if (!lua_isstring(L, -1)) {
8239 /* invalid value type, skip it*/
8240 lua_pop(L, 1);
8241 continue;
8242 }
8243 /* push the value in the inner table */
8244 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8245 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8246 }
8247 lua_pop(L, 1);
8248 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8249 }
8250
8251 /* push (k,v) on the stack in the headers table:
8252 * stack: [ ... <headers:table>, <table>, k, k, v ]
8253 */
8254 lua_settable(L, -5);
8255 /* stack: [ ... <headers:table>, <table>, k ] */
8256 }
8257 }
8258 lua_pop(L, 1);
8259 }
8260 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8261 lua_settable(L, -3);
8262 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8263
8264 /* Pop a class sesison metatable and affect it to the userdata. */
8265 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8266 lua_setmetatable(L, -2);
8267 return 1;
8268}
8269
8270/* Set the reply status code, and optionally the reason. If no reason is
8271 * provided, the default one corresponding to the status code is used.
8272 */
8273__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8274{
8275 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8276 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8277
8278 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008279 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008280
8281 if (status < 100 || status > 599) {
8282 lua_pushboolean(L, 0);
8283 return 1;
8284 }
8285 if (!reason)
8286 reason = http_get_reason(status);
8287
8288 lua_pushinteger(L, status);
8289 lua_setfield(L, 1, "status");
8290
8291 lua_pushstring(L, reason);
8292 lua_setfield(L, 1, "reason");
8293
8294 lua_pushboolean(L, 1);
8295 return 1;
8296}
8297
8298/* Add a header into the reply object. Each header name is associated to an
8299 * array of values in the "headers" table. If the header name is not found, a
8300 * new entry is created.
8301 */
8302__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8303{
8304 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8305 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8306 int ret;
8307
8308 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008309 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008310
8311 /* Push in the stack the "headers" entry. */
8312 ret = lua_getfield(L, 1, "headers");
8313 if (ret != LUA_TTABLE) {
8314 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8315 WILL_LJMP(lua_error(L));
8316 }
8317
8318 /* check if the header is already registered. If not, register it. */
8319 ret = lua_getfield(L, -1, name);
8320 if (ret == LUA_TNIL) {
8321 /* Entry not found. */
8322 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8323
8324 /* Insert the new header name in the array in the top of the stack.
8325 * It left the new array in the top of the stack.
8326 */
8327 lua_newtable(L);
8328 lua_pushstring(L, name);
8329 lua_pushvalue(L, -2);
8330 lua_settable(L, -4);
8331 }
8332 else if (ret != LUA_TTABLE) {
8333 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8334 WILL_LJMP(lua_error(L));
8335 }
8336
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008337 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008338 * the header value as new entry.
8339 */
8340 lua_pushstring(L, value);
8341 ret = lua_rawlen(L, -2);
8342 lua_rawseti(L, -2, ret + 1);
8343
8344 lua_pushboolean(L, 1);
8345 return 1;
8346}
8347
8348/* Remove all occurrences of a given header name. */
8349__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8350{
8351 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8352 int ret;
8353
8354 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008355 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008356
8357 /* Push in the stack the "headers" entry. */
8358 ret = lua_getfield(L, 1, "headers");
8359 if (ret != LUA_TTABLE) {
8360 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8361 WILL_LJMP(lua_error(L));
8362 }
8363
8364 lua_pushstring(L, name);
8365 lua_pushnil(L);
8366 lua_settable(L, -3);
8367
8368 lua_pushboolean(L, 1);
8369 return 1;
8370}
8371
8372/* Set the reply's body. Overwrite any existing entry. */
8373__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8374{
8375 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8376
8377 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008378 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008379
8380 lua_pushstring(L, payload);
8381 lua_setfield(L, 1, "body");
8382
8383 lua_pushboolean(L, 1);
8384 return 1;
8385}
8386
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008387__LJMP static int hlua_log(lua_State *L)
8388{
8389 int level;
8390 const char *msg;
8391
8392 MAY_LJMP(check_args(L, 2, "log"));
8393 level = MAY_LJMP(luaL_checkinteger(L, 1));
8394 msg = MAY_LJMP(luaL_checkstring(L, 2));
8395
8396 if (level < 0 || level >= NB_LOG_LEVELS)
8397 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8398
8399 hlua_sendlog(NULL, level, msg);
8400 return 0;
8401}
8402
8403__LJMP static int hlua_log_debug(lua_State *L)
8404{
8405 const char *msg;
8406
8407 MAY_LJMP(check_args(L, 1, "debug"));
8408 msg = MAY_LJMP(luaL_checkstring(L, 1));
8409 hlua_sendlog(NULL, LOG_DEBUG, msg);
8410 return 0;
8411}
8412
8413__LJMP static int hlua_log_info(lua_State *L)
8414{
8415 const char *msg;
8416
8417 MAY_LJMP(check_args(L, 1, "info"));
8418 msg = MAY_LJMP(luaL_checkstring(L, 1));
8419 hlua_sendlog(NULL, LOG_INFO, msg);
8420 return 0;
8421}
8422
8423__LJMP static int hlua_log_warning(lua_State *L)
8424{
8425 const char *msg;
8426
8427 MAY_LJMP(check_args(L, 1, "warning"));
8428 msg = MAY_LJMP(luaL_checkstring(L, 1));
8429 hlua_sendlog(NULL, LOG_WARNING, msg);
8430 return 0;
8431}
8432
8433__LJMP static int hlua_log_alert(lua_State *L)
8434{
8435 const char *msg;
8436
8437 MAY_LJMP(check_args(L, 1, "alert"));
8438 msg = MAY_LJMP(luaL_checkstring(L, 1));
8439 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008440 return 0;
8441}
8442
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008443__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008444{
8445 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008446 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008447 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008448 return 0;
8449}
8450
8451__LJMP static int hlua_sleep(lua_State *L)
8452{
8453 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008454 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008455
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008456 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008457
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008458 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008459 wakeup_ms = tick_add(now_ms, delay);
8460 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008461
Willy Tarreau9635e032018-10-16 17:52:55 +02008462 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008463 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008464}
8465
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008466__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008467{
8468 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008469 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008470
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008471 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008472
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008473 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008474 wakeup_ms = tick_add(now_ms, delay);
8475 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008476
Willy Tarreau9635e032018-10-16 17:52:55 +02008477 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008478 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008479}
8480
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008481/* This functionis an LUA binding. it permits to give back
8482 * the hand at the HAProxy scheduler. It is used when the
8483 * LUA processing consumes a lot of time.
8484 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008485__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008486{
8487 return 0;
8488}
8489
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008490__LJMP static int hlua_yield(lua_State *L)
8491{
Willy Tarreau9635e032018-10-16 17:52:55 +02008492 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008493 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008494}
8495
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008496/* This function change the nice of the currently executed
8497 * task. It is used set low or high priority at the current
8498 * task.
8499 */
Willy Tarreau59551662015-03-10 14:23:13 +01008500__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008501{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008502 struct hlua *hlua;
8503 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008504
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008505 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008506 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008507
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008508 /* Get hlua struct, or NULL if we execute from main lua state */
8509 hlua = hlua_gethlua(L);
8510
8511 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008512 if (!hlua || !hlua->task)
8513 return 0;
8514
8515 if (nice < -1024)
8516 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008517 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008518 nice = 1024;
8519
8520 hlua->task->nice = nice;
8521 return 0;
8522}
8523
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008524/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008525 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8526 * return an E_AGAIN signal, the emmiter of this signal must set a
8527 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008528 *
8529 * Task wrapper are longjmp safe because the only one Lua code
8530 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008531 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008532struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008533{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008534 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008535 enum hlua_exec status;
8536
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008537 if (task->tid < 0)
8538 task->tid = tid;
8539
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008540 /* If it is the first call to the task, we must initialize the
8541 * execution timeouts.
8542 */
8543 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008544 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008545
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008546 /* Execute the Lua code. */
8547 status = hlua_ctx_resume(hlua, 1);
8548
8549 switch (status) {
8550 /* finished or yield */
8551 case HLUA_E_OK:
8552 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008553 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008554 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008555 break;
8556
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008557 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008558 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008559 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008560 break;
8561
8562 /* finished with error. */
8563 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008564 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008565 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008566 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008567 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008568 break;
8569
8570 case HLUA_E_ERR:
8571 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008572 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008573 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008574 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008575 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008576 break;
8577 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008578 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008579}
8580
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008581/* This function is an LUA binding that register LUA function to be
8582 * executed after the HAProxy configuration parsing and before the
8583 * HAProxy scheduler starts. This function expect only one LUA
8584 * argument that is a function. This function returns nothing, but
8585 * throws if an error is encountered.
8586 */
8587__LJMP static int hlua_register_init(lua_State *L)
8588{
8589 struct hlua_init_function *init;
8590 int ref;
8591
8592 MAY_LJMP(check_args(L, 1, "register_init"));
8593
8594 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8595
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008596 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008597 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008598 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008599
8600 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008601 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008602 return 0;
8603}
8604
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008605/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008606 * executed in parallel of the main HAroxy activity. The task is
8607 * created and it is set in the HAProxy scheduler. It can be called
8608 * from the "init" section, "post init" or during the runtime.
8609 *
8610 * Lua prototype:
8611 *
8612 * <none> core.register_task(<function>)
8613 */
8614static int hlua_register_task(lua_State *L)
8615{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008616 struct hlua *hlua = NULL;
8617 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008618 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008619 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008620
8621 MAY_LJMP(check_args(L, 1, "register_task"));
8622
8623 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8624
Thierry Fournier75fc0292020-11-28 13:18:56 +01008625 /* Get the reference state. If the reference is NULL, L is the master
8626 * state, otherwise hlua->T is.
8627 */
8628 hlua = hlua_gethlua(L);
8629 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008630 /* we are in runtime processing */
8631 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008632 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008633 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008634 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008635
Willy Tarreaubafbe012017-11-24 17:34:44 +01008636 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008637 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008638 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008639 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008640
Thierry Fournier59f11be2020-11-29 00:37:41 +01008641 /* We are in the common lua state, execute the task anywhere,
8642 * otherwise, inherit the current thread identifier
8643 */
8644 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008645 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008646 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008647 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008648 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008649 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008650
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008651 task->context = hlua;
8652 task->process = hlua_process_task;
8653
Thierry Fournier021d9862020-11-28 23:42:03 +01008654 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008655 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008656
8657 /* Restore the function in the stack. */
8658 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8659 hlua->nargs = 0;
8660
8661 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008662 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008663
8664 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008665
8666 alloc_error:
8667 task_destroy(task);
8668 hlua_ctx_destroy(hlua);
8669 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8670 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008671}
8672
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008673/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8674 * doesn't allow "yield" functions because the HAProxy engine cannot
8675 * resume converters.
8676 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008677static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008678{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008679 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008680 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008681 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008682
Willy Tarreaube508f12016-03-10 11:47:01 +01008683 if (!stream)
8684 return 0;
8685
Willy Tarreau87b09662015-04-03 00:22:06 +02008686 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008687 * Lua context can be not initialized. This behavior
8688 * permits to save performances because a systematic
8689 * Lua initialization cause 5% performances loss.
8690 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008691 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008692 struct hlua *hlua;
8693
8694 hlua = pool_alloc(pool_head_hlua);
8695 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008696 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8697 return 0;
8698 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008699 HLUA_INIT(hlua);
8700 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008701 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008702 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8703 return 0;
8704 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008705 }
8706
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008707 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008708 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008709
8710 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008711 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008712 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8713 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008714 else
8715 error = "critical error";
8716 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008717 return 0;
8718 }
8719
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008720 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008721 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008722 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008723 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008724 return 0;
8725 }
8726
8727 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008728 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008729
8730 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008731 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008732 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008733 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008734 return 0;
8735 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008736 hlua_smp2lua(stream->hlua->T, smp);
8737 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008738
8739 /* push keywords in the stack. */
8740 if (arg_p) {
8741 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008742 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008743 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008744 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008745 return 0;
8746 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008747 hlua_arg2lua(stream->hlua->T, arg_p);
8748 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008749 }
8750 }
8751
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008752 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008753 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008754
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008755 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008756 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008757 }
8758
8759 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008760 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008761 /* finished. */
8762 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008763 /* If the stack is empty, the function fails. */
8764 if (lua_gettop(stream->hlua->T) <= 0)
8765 return 0;
8766
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008767 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008768 hlua_lua2smp(stream->hlua->T, -1, smp);
8769 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008770 return 1;
8771
8772 /* yield. */
8773 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008774 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008775 return 0;
8776
8777 /* finished with error. */
8778 case HLUA_E_ERRMSG:
8779 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008780 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008781 fcn->name, lua_tostring(stream->hlua->T, -1));
8782 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008783 return 0;
8784
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008785 case HLUA_E_ETMOUT:
8786 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8787 return 0;
8788
8789 case HLUA_E_NOMEM:
8790 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8791 return 0;
8792
8793 case HLUA_E_YIELD:
8794 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8795 return 0;
8796
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008797 case HLUA_E_ERR:
8798 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008799 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008800 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008801
8802 default:
8803 return 0;
8804 }
8805}
8806
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008807/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8808 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008809 * resume sample-fetches. This function will be called by the sample
8810 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008811 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008812static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8813 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008814{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008815 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008816 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008817 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008818 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008819
Willy Tarreaube508f12016-03-10 11:47:01 +01008820 if (!stream)
8821 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008822
Willy Tarreau87b09662015-04-03 00:22:06 +02008823 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008824 * Lua context can be not initialized. This behavior
8825 * permits to save performances because a systematic
8826 * Lua initialization cause 5% performances loss.
8827 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008828 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008829 struct hlua *hlua;
8830
8831 hlua = pool_alloc(pool_head_hlua);
8832 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008833 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8834 return 0;
8835 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008836 hlua->T = NULL;
8837 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008838 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008839 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8840 return 0;
8841 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008842 }
8843
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008844 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008845 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008846
8847 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008848 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008849 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8850 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008851 else
8852 error = "critical error";
8853 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008854 return 0;
8855 }
8856
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008857 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008858 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008859 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008860 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008861 return 0;
8862 }
8863
8864 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008865 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008866
8867 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008868 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008869 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008870 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008871 return 0;
8872 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008873 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008874
8875 /* push keywords in the stack. */
8876 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8877 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008878 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008879 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008880 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008881 return 0;
8882 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008883 hlua_arg2lua(stream->hlua->T, arg_p);
8884 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008885 }
8886
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008887 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008888 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008889
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008890 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008891 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008892 }
8893
8894 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008895 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008896 /* finished. */
8897 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008898 /* If the stack is empty, the function fails. */
8899 if (lua_gettop(stream->hlua->T) <= 0)
8900 return 0;
8901
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008902 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008903 hlua_lua2smp(stream->hlua->T, -1, smp);
8904 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008905
8906 /* Set the end of execution flag. */
8907 smp->flags &= ~SMP_F_MAY_CHANGE;
8908 return 1;
8909
8910 /* yield. */
8911 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008912 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008913 return 0;
8914
8915 /* finished with error. */
8916 case HLUA_E_ERRMSG:
8917 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008918 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008919 fcn->name, lua_tostring(stream->hlua->T, -1));
8920 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008921 return 0;
8922
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008923 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008924 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8925 return 0;
8926
8927 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008928 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8929 return 0;
8930
8931 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008932 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8933 return 0;
8934
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008935 case HLUA_E_ERR:
8936 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008937 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008938 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008939
8940 default:
8941 return 0;
8942 }
8943}
8944
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008945/* This function is an LUA binding used for registering
8946 * "sample-conv" functions. It expects a converter name used
8947 * in the haproxy configuration file, and an LUA function.
8948 */
8949__LJMP static int hlua_register_converters(lua_State *L)
8950{
8951 struct sample_conv_kw_list *sck;
8952 const char *name;
8953 int ref;
8954 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008955 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008956 struct sample_conv *sc;
8957 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008958
8959 MAY_LJMP(check_args(L, 2, "register_converters"));
8960
8961 /* First argument : converter name. */
8962 name = MAY_LJMP(luaL_checkstring(L, 1));
8963
8964 /* Second argument : lua function. */
8965 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8966
Thierry Fournierf67442e2020-11-28 20:41:07 +01008967 /* Check if the converter is already registered */
8968 trash = get_trash_chunk();
8969 chunk_printf(trash, "lua.%s", name);
8970 sc = find_sample_conv(trash->area, trash->data);
8971 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008972 fcn = sc->private;
8973 if (fcn->function_ref[hlua_state_id] != -1) {
8974 ha_warning("Trying to register converter 'lua.%s' more than once. "
8975 "This will become a hard error in version 2.5.\n", name);
8976 }
8977 fcn->function_ref[hlua_state_id] = ref;
8978 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008979 }
8980
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008981 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008982 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008983 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008984 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008985 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008986 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008987 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008988
8989 /* Fill fcn. */
8990 fcn->name = strdup(name);
8991 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008992 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008993 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008994
8995 /* List head */
8996 sck->list.n = sck->list.p = NULL;
8997
8998 /* converter keyword. */
8999 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009000 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009001 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009002 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009003
9004 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9005 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009006 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 +01009007 sck->kw[0].val_args = NULL;
9008 sck->kw[0].in_type = SMP_T_STR;
9009 sck->kw[0].out_type = SMP_T_STR;
9010 sck->kw[0].private = fcn;
9011
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009012 /* Register this new converter */
9013 sample_register_convs(sck);
9014
9015 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009016
9017 alloc_error:
9018 release_hlua_function(fcn);
9019 ha_free(&sck);
9020 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9021 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009022}
9023
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009024/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009025 * "sample-fetch" functions. It expects a converter name used
9026 * in the haproxy configuration file, and an LUA function.
9027 */
9028__LJMP static int hlua_register_fetches(lua_State *L)
9029{
9030 const char *name;
9031 int ref;
9032 int len;
9033 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009034 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009035 struct sample_fetch *sf;
9036 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009037
9038 MAY_LJMP(check_args(L, 2, "register_fetches"));
9039
9040 /* First argument : sample-fetch name. */
9041 name = MAY_LJMP(luaL_checkstring(L, 1));
9042
9043 /* Second argument : lua function. */
9044 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9045
Thierry Fournierf67442e2020-11-28 20:41:07 +01009046 /* Check if the sample-fetch is already registered */
9047 trash = get_trash_chunk();
9048 chunk_printf(trash, "lua.%s", name);
9049 sf = find_sample_fetch(trash->area, trash->data);
9050 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009051 fcn = sf->private;
9052 if (fcn->function_ref[hlua_state_id] != -1) {
9053 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9054 "This will become a hard error in version 2.5.\n", name);
9055 }
9056 fcn->function_ref[hlua_state_id] = ref;
9057 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009058 }
9059
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009060 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009061 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009062 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009063 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009064 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009065 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009066 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009067
9068 /* Fill fcn. */
9069 fcn->name = strdup(name);
9070 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009071 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009072 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009073
9074 /* List head */
9075 sfk->list.n = sfk->list.p = NULL;
9076
9077 /* sample-fetch keyword. */
9078 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009079 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009080 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009081 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009082
9083 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9084 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009085 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 +01009086 sfk->kw[0].val_args = NULL;
9087 sfk->kw[0].out_type = SMP_T_STR;
9088 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9089 sfk->kw[0].val = 0;
9090 sfk->kw[0].private = fcn;
9091
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009092 /* Register this new fetch. */
9093 sample_register_fetches(sfk);
9094
9095 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009096
9097 alloc_error:
9098 release_hlua_function(fcn);
9099 ha_free(&sfk);
9100 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9101 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009102}
9103
Christopher Faulet501465d2020-02-26 14:54:16 +01009104/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009105 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009106__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009107{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009108 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009109 unsigned int delay;
9110 unsigned int wakeup_ms;
9111
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009112 /* Get hlua struct, or NULL if we execute from main lua state */
9113 hlua = hlua_gethlua(L);
9114 if (!hlua) {
9115 return 0;
9116 }
9117
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009118 MAY_LJMP(check_args(L, 1, "wake_time"));
9119
9120 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9121 wakeup_ms = tick_add(now_ms, delay);
9122 hlua->wake_time = wakeup_ms;
9123 return 0;
9124}
9125
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009126/* This function is a wrapper to execute each LUA function declared as an action
9127 * wrapper during the initialisation period. This function may return any
9128 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9129 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9130 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009131 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009132static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009133 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009134{
9135 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009136 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009137 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009138 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009139
9140 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009141 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9142 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9143 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9144 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009145 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009146 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009147 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009148 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009149
Willy Tarreau87b09662015-04-03 00:22:06 +02009150 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009151 * Lua context can be not initialized. This behavior
9152 * permits to save performances because a systematic
9153 * Lua initialization cause 5% performances loss.
9154 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009155 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009156 struct hlua *hlua;
9157
9158 hlua = pool_alloc(pool_head_hlua);
9159 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009160 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009161 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009162 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009163 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009164 HLUA_INIT(hlua);
9165 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009166 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 +01009167 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009168 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009169 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009170 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009171 }
9172
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009173 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009174 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009175
9176 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009177 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009178 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9179 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009180 else
9181 error = "critical error";
9182 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009183 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009184 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009185 }
9186
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009187 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009188 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009189 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009190 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009191 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009192 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009193 }
9194
9195 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009196 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 +01009197
Willy Tarreau87b09662015-04-03 00:22:06 +02009198 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009199 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009200 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009201 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009202 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009203 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009204 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009205 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009206
9207 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009208 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009209 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009210 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009211 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009212 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009213 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009214 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009215 lua_pushstring(s->hlua->T, *arg);
9216 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009217 }
9218
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009219 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009220 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009221
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009222 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009223 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009224 }
9225
9226 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009227 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009228 /* finished. */
9229 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009230 /* Catch the return value */
9231 if (lua_gettop(s->hlua->T) > 0)
9232 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009233
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009234 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009235 if (act_ret == ACT_RET_YIELD) {
9236 if (flags & ACT_OPT_FINAL)
9237 goto err_yield;
9238
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009239 if (dir == SMP_OPT_DIR_REQ)
9240 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9241 s->hlua->wake_time);
9242 else
9243 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9244 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009245 }
9246 goto end;
9247
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009248 /* yield. */
9249 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009250 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009251 if (dir == SMP_OPT_DIR_REQ)
9252 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9253 s->hlua->wake_time);
9254 else
9255 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9256 s->hlua->wake_time);
9257
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009258 /* Some actions can be wake up when a "write" event
9259 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009260 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009261 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009262 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009263 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009264 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009265 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009266 act_ret = ACT_RET_YIELD;
9267 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009268
9269 /* finished with error. */
9270 case HLUA_E_ERRMSG:
9271 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009272 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009273 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009274 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009275 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009276
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009277 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009278 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009279 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009280
9281 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009282 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009283 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009284
9285 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009286 err_yield:
9287 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009288 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009289 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009290 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009291
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009292 case HLUA_E_ERR:
9293 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009294 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009295 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009296
9297 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009298 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009299 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009300
9301 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009302 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009303 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009304 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009305}
9306
Willy Tarreau144f84a2021-03-02 16:09:26 +01009307struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009308{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009309 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009310
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009311 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009312 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009313 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009314}
9315
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009316static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009317{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009318 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009319 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009320 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009321 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009322 struct task *task;
9323 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009324 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009325
Willy Tarreaubafbe012017-11-24 17:34:44 +01009326 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009327 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009328 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009329 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009330 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009331 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009332 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009333 tcp_ctx->hlua = hlua;
9334 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009335
9336 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009337 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009338 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009339 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009340 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009341 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009342 }
9343 task->nice = 0;
9344 task->context = ctx;
9345 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009346 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009347
9348 /* In the execution wrappers linked with a stream, the
9349 * Lua context can be not initialized. This behavior
9350 * permits to save performances because a systematic
9351 * Lua initialization cause 5% performances loss.
9352 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009353 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 +01009354 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009355 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009356 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009357 }
9358
9359 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009360 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009361
9362 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009363 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009364 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9365 error = lua_tostring(hlua->T, -1);
9366 else
9367 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009368 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009369 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009370 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009371 }
9372
9373 /* Check stack available size. */
9374 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009375 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009376 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009377 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009378 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009379 }
9380
9381 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009382 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009383
9384 /* Create and and push object stream in the stack. */
9385 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009386 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009387 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009388 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009389 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009390 }
9391 hlua->nargs = 1;
9392
9393 /* push keywords in the stack. */
9394 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9395 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009396 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009397 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009398 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009399 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009400 }
9401 lua_pushstring(hlua->T, *arg);
9402 hlua->nargs++;
9403 }
9404
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009405 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009406
9407 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009408 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009409 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009410
Christopher Fauletc9929382022-05-12 11:52:27 +02009411 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009412}
9413
Willy Tarreau60409db2019-08-21 14:14:50 +02009414void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009415{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009416 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009417 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009418 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009419 struct act_rule *rule = ctx->rule;
9420 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009421 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009422
Christopher Faulet31572222023-03-31 11:13:48 +02009423 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9424 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009425
Christopher Faulet31572222023-03-31 11:13:48 +02009426 /* The applet execution is already done. */
9427 if (tcp_ctx->flags & APPLET_DONE)
9428 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009429
9430 /* Execute the function. */
9431 switch (hlua_ctx_resume(hlua, 1)) {
9432 /* finished. */
9433 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009434 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009435 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
9436 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009437
9438 /* yield. */
9439 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009440 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009441 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +02009442 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009443
9444 /* finished with error. */
9445 case HLUA_E_ERRMSG:
9446 /* Display log. */
9447 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009448 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009449 lua_pop(hlua->T, 1);
9450 goto error;
9451
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009452 case HLUA_E_ETMOUT:
9453 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009454 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009455 goto error;
9456
9457 case HLUA_E_NOMEM:
9458 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009459 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009460 goto error;
9461
9462 case HLUA_E_YIELD: /* unexpected */
9463 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009464 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009465 goto error;
9466
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009467 case HLUA_E_ERR:
9468 /* Display log. */
9469 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009470 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009471 goto error;
9472
9473 default:
9474 goto error;
9475 }
9476
Christopher Faulet31572222023-03-31 11:13:48 +02009477out:
9478 /* eat the whole request */
9479 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
9480 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009481
Christopher Faulet31572222023-03-31 11:13:48 +02009482error:
9483 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009484 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009485 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009486}
9487
9488static void hlua_applet_tcp_release(struct appctx *ctx)
9489{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009490 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9491
9492 task_destroy(tcp_ctx->task);
9493 tcp_ctx->task = NULL;
9494 hlua_ctx_destroy(tcp_ctx->hlua);
9495 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009496}
9497
Christopher Fauletc9929382022-05-12 11:52:27 +02009498/* The function returns 0 if the initialisation is complete or -1 if
9499 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009500 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009501static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009502{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009503 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009504 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009505 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009506 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009507 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009508 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009509 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009510 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009511
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009512 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009513 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009514 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009515 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009516 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009517 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009518 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009519 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009520 http_ctx->hlua = hlua;
9521 http_ctx->left_bytes = -1;
9522 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009523
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009524 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009525 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009526
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009527 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009528 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009529 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009530 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009531 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009532 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009533 }
9534 task->nice = 0;
9535 task->context = ctx;
9536 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009537 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009538
9539 /* In the execution wrappers linked with a stream, the
9540 * Lua context can be not initialized. This behavior
9541 * permits to save performances because a systematic
9542 * Lua initialization cause 5% performances loss.
9543 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009544 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 +01009545 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009546 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009547 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009548 }
9549
9550 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009551 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009552
9553 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009554 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009555 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9556 error = lua_tostring(hlua->T, -1);
9557 else
9558 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009559 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009560 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009561 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009562 }
9563
9564 /* Check stack available size. */
9565 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009566 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009567 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009568 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009569 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009570 }
9571
9572 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009573 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009574
9575 /* Create and and push object stream in the stack. */
9576 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009577 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009578 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009579 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009580 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009581 }
9582 hlua->nargs = 1;
9583
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009584 /* push keywords in the stack. */
9585 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9586 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009587 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009588 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009589 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009590 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009591 }
9592 lua_pushstring(hlua->T, *arg);
9593 hlua->nargs++;
9594 }
9595
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009596 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009597
9598 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009599 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009600
Christopher Fauletc9929382022-05-12 11:52:27 +02009601 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009602}
9603
Willy Tarreau60409db2019-08-21 14:14:50 +02009604void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009605{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009606 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009607 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009608 struct stream *strm = __sc_strm(sc);
9609 struct channel *req = sc_oc(sc);
9610 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009611 struct act_rule *rule = ctx->rule;
9612 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009613 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009614 struct htx *req_htx, *res_htx;
9615
9616 res_htx = htx_from_buf(&res->buf);
9617
Christopher Faulet31572222023-03-31 11:13:48 +02009618 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9619 goto out;
9620
9621 /* The applet execution is already done. */
9622 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009623 goto out;
9624
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009625 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009626 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009627 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009628 goto out;
9629 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009630
9631 /* Set the currently running flag. */
9632 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009633 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009634 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009635 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009636 goto out;
9637 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009638 }
9639
Christopher Faulet31572222023-03-31 11:13:48 +02009640 /* Execute the function. */
9641 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009642 /* finished. */
9643 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009644 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009645 break;
9646
9647 /* yield. */
9648 case HLUA_E_AGAIN:
9649 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009650 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009651 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009652
9653 /* finished with error. */
9654 case HLUA_E_ERRMSG:
9655 /* Display log. */
9656 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009657 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009658 lua_pop(hlua->T, 1);
9659 goto error;
9660
9661 case HLUA_E_ETMOUT:
9662 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009663 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009664 goto error;
9665
9666 case HLUA_E_NOMEM:
9667 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009668 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009669 goto error;
9670
9671 case HLUA_E_YIELD: /* unexpected */
9672 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009673 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009674 goto error;
9675
9676 case HLUA_E_ERR:
9677 /* Display log. */
9678 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009679 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009680 goto error;
9681
9682 default:
9683 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009684 }
9685
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009686 if (http_ctx->flags & APPLET_DONE) {
9687 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +02009688 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009689
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009690 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009691 goto error;
9692
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009693 /* no more data are expected. If the response buffer is empty
9694 * for a chunked message, be sure to add something (EOT block in
9695 * this case) to have something to send. It is important to be
9696 * sure the EOM flags will be handled by the endpoint.
9697 */
9698 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9699 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009700 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009701 goto out;
9702 }
9703 channel_add_input(res, 1);
9704 }
9705
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009706 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +02009707 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009708 strm->txn->status = http_ctx->status;
9709 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009710 }
9711
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009712 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009713 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +02009714 /* eat the whole request */
9715 if (co_data(req)) {
9716 req_htx = htx_from_buf(&req->buf);
9717 co_htx_skip(req, req_htx, co_data(req));
9718 htx_to_buf(req_htx, &req->buf);
9719 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009720 return;
9721
9722 error:
9723
9724 /* If we are in HTTP mode, and we are not send any
9725 * data, return a 500 server error in best effort:
9726 * if there is no room available in the buffer,
9727 * just close the connection.
9728 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009729 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009730 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009731
9732 channel_erase(res);
9733 res->buf.data = b_data(err);
9734 memcpy(res->buf.area, b_head(err), b_data(err));
9735 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009736 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +02009737 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009738 }
Christopher Faulet31572222023-03-31 11:13:48 +02009739 else
9740 se_fl_set(ctx->sedesc, SE_FL_ERROR);
9741
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009742 if (!(strm->flags & SF_ERR_MASK))
9743 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009744 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009745 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009746}
9747
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009748static void hlua_applet_http_release(struct appctx *ctx)
9749{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009750 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9751
9752 task_destroy(http_ctx->task);
9753 http_ctx->task = NULL;
9754 hlua_ctx_destroy(http_ctx->hlua);
9755 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009756}
9757
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009758/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009759 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009760 *
9761 * This function can fail with an abort() due to an Lua critical error.
9762 * We are in the configuration parsing process of HAProxy, this abort() is
9763 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009764 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009765static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9766 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009767{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009768 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009769 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009770
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009771 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009772 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009773 if (!rule->arg.hlua_rule) {
9774 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009775 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009776 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009777
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009778 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009779 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9780 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009781 if (!rule->arg.hlua_rule->args) {
9782 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009783 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009784 }
9785
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009786 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009787 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009788
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009789 /* Expect some arguments */
9790 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009791 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009792 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009793 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009794 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009795 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009796 if (!rule->arg.hlua_rule->args[i]) {
9797 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009798 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009799 }
9800 (*cur_arg)++;
9801 }
9802 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009803
Thierry FOURNIER42148732015-09-02 17:17:33 +02009804 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009805 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009806 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009807
9808 error:
9809 if (rule->arg.hlua_rule) {
9810 if (rule->arg.hlua_rule->args) {
9811 for (i = 0; i < fcn->nargs; i++)
9812 ha_free(&rule->arg.hlua_rule->args[i]);
9813 ha_free(&rule->arg.hlua_rule->args);
9814 }
9815 ha_free(&rule->arg.hlua_rule);
9816 }
9817 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009818}
9819
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009820static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9821 struct act_rule *rule, char **err)
9822{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009823 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009824
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009825 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009826 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009827 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009828 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009829 * the call of this analyzer.
9830 */
9831 if (rule->from != ACT_F_HTTP_REQ) {
9832 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9833 return ACT_RET_PRS_ERR;
9834 }
9835
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009836 /* Memory for the rule. */
9837 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9838 if (!rule->arg.hlua_rule) {
9839 memprintf(err, "out of memory error");
9840 return ACT_RET_PRS_ERR;
9841 }
9842
9843 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009844 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009845
9846 /* TODO: later accept arguments. */
9847 rule->arg.hlua_rule->args = NULL;
9848
9849 /* Add applet pointer in the rule. */
9850 rule->applet.obj_type = OBJ_TYPE_APPLET;
9851 rule->applet.name = fcn->name;
9852 rule->applet.init = hlua_applet_http_init;
9853 rule->applet.fct = hlua_applet_http_fct;
9854 rule->applet.release = hlua_applet_http_release;
9855 rule->applet.timeout = hlua_timeout_applet;
9856
9857 return ACT_RET_PRS_OK;
9858}
9859
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009860/* This function is an LUA binding used for registering
9861 * "sample-conv" functions. It expects a converter name used
9862 * in the haproxy configuration file, and an LUA function.
9863 */
9864__LJMP static int hlua_register_action(lua_State *L)
9865{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009866 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009867 const char *name;
9868 int ref;
9869 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009870 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009871 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009872 struct buffer *trash;
9873 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009874
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009875 /* Initialise the number of expected arguments at 0. */
9876 nargs = 0;
9877
9878 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9879 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009880
9881 /* First argument : converter name. */
9882 name = MAY_LJMP(luaL_checkstring(L, 1));
9883
9884 /* Second argument : environment. */
9885 if (lua_type(L, 2) != LUA_TTABLE)
9886 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9887
9888 /* Third argument : lua function. */
9889 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9890
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009891 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009892 if (lua_gettop(L) >= 4)
9893 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9894
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009895 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009896 lua_pushnil(L);
9897 while (lua_next(L, 2) != 0) {
9898 if (lua_type(L, -1) != LUA_TSTRING)
9899 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9900
Thierry Fournierf67442e2020-11-28 20:41:07 +01009901 /* Check if action exists */
9902 trash = get_trash_chunk();
9903 chunk_printf(trash, "lua.%s", name);
9904 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9905 akw = tcp_req_cont_action(trash->area);
9906 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9907 akw = tcp_res_cont_action(trash->area);
9908 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9909 akw = action_http_req_custom(trash->area);
9910 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9911 akw = action_http_res_custom(trash->area);
9912 } else {
9913 akw = NULL;
9914 }
9915 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009916 fcn = akw->private;
9917 if (fcn->function_ref[hlua_state_id] != -1) {
9918 ha_warning("Trying to register action 'lua.%s' more than once. "
9919 "This will become a hard error in version 2.5.\n", name);
9920 }
9921 fcn->function_ref[hlua_state_id] = ref;
9922
9923 /* pop the environment string. */
9924 lua_pop(L, 1);
9925 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009926 }
9927
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009928 /* Check required environment. Only accepted "http" or "tcp". */
9929 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009930 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009931 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009932 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009933 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009934 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009935 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009936
9937 /* Fill fcn. */
9938 fcn->name = strdup(name);
9939 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009940 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009941 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009942
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009943 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009944 fcn->nargs = nargs;
9945
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009946 /* List head */
9947 akl->list.n = akl->list.p = NULL;
9948
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009949 /* action keyword. */
9950 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009951 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009952 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009953 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009954
9955 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9956
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009957 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009958 akl->kw[0].private = fcn;
9959 akl->kw[0].parse = action_register_lua;
9960
9961 /* select the action registering point. */
9962 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9963 tcp_req_cont_keywords_register(akl);
9964 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9965 tcp_res_cont_keywords_register(akl);
9966 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9967 http_req_keywords_register(akl);
9968 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9969 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009970 else {
9971 release_hlua_function(fcn);
9972 if (akl)
9973 ha_free((char **)&(akl->kw[0].kw));
9974 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009975 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009976 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9977 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009978 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009979
9980 /* pop the environment string. */
9981 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009982
9983 /* reset for next loop */
9984 akl = NULL;
9985 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009986 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009987 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009988
9989 alloc_error:
9990 release_hlua_function(fcn);
9991 ha_free(&akl);
9992 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9993 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009994}
9995
9996static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9997 struct act_rule *rule, char **err)
9998{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009999 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010000
Christopher Faulet280f85b2019-07-15 15:02:04 +020010001 if (px->mode == PR_MODE_HTTP) {
10002 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010003 return ACT_RET_PRS_ERR;
10004 }
10005
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010006 /* Memory for the rule. */
10007 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10008 if (!rule->arg.hlua_rule) {
10009 memprintf(err, "out of memory error");
10010 return ACT_RET_PRS_ERR;
10011 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010012
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010013 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010014 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010015
10016 /* TODO: later accept arguments. */
10017 rule->arg.hlua_rule->args = NULL;
10018
10019 /* Add applet pointer in the rule. */
10020 rule->applet.obj_type = OBJ_TYPE_APPLET;
10021 rule->applet.name = fcn->name;
10022 rule->applet.init = hlua_applet_tcp_init;
10023 rule->applet.fct = hlua_applet_tcp_fct;
10024 rule->applet.release = hlua_applet_tcp_release;
10025 rule->applet.timeout = hlua_timeout_applet;
10026
10027 return 0;
10028}
10029
10030/* This function is an LUA binding used for registering
10031 * "sample-conv" functions. It expects a converter name used
10032 * in the haproxy configuration file, and an LUA function.
10033 */
10034__LJMP static int hlua_register_service(lua_State *L)
10035{
10036 struct action_kw_list *akl;
10037 const char *name;
10038 const char *env;
10039 int ref;
10040 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010041 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010042 struct buffer *trash;
10043 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010044
10045 MAY_LJMP(check_args(L, 3, "register_service"));
10046
10047 /* First argument : converter name. */
10048 name = MAY_LJMP(luaL_checkstring(L, 1));
10049
10050 /* Second argument : environment. */
10051 env = MAY_LJMP(luaL_checkstring(L, 2));
10052
10053 /* Third argument : lua function. */
10054 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10055
Thierry Fournierf67442e2020-11-28 20:41:07 +010010056 /* Check for service already registered */
10057 trash = get_trash_chunk();
10058 chunk_printf(trash, "lua.%s", name);
10059 akw = service_find(trash->area);
10060 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010061 fcn = akw->private;
10062 if (fcn->function_ref[hlua_state_id] != -1) {
10063 ha_warning("Trying to register service 'lua.%s' more than once. "
10064 "This will become a hard error in version 2.5.\n", name);
10065 }
10066 fcn->function_ref[hlua_state_id] = ref;
10067 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010068 }
10069
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010070 /* Allocate and fill the sample fetch keyword struct. */
10071 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10072 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010073 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010074 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010075 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010076 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010077
10078 /* Fill fcn. */
10079 len = strlen("<lua.>") + strlen(name) + 1;
10080 fcn->name = calloc(1, len);
10081 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010082 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010083 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010084 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010085
10086 /* List head */
10087 akl->list.n = akl->list.p = NULL;
10088
10089 /* converter keyword. */
10090 len = strlen("lua.") + strlen(name) + 1;
10091 akl->kw[0].kw = calloc(1, len);
10092 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010093 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010094
10095 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10096
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010097 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010098 if (strcmp(env, "tcp") == 0)
10099 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010100 else if (strcmp(env, "http") == 0)
10101 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010102 else {
10103 release_hlua_function(fcn);
10104 if (akl)
10105 ha_free((char **)&(akl->kw[0].kw));
10106 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010107 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010108 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010109 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010110
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010111 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010112 akl->kw[0].private = fcn;
10113
10114 /* End of array. */
10115 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10116
10117 /* Register this new converter */
10118 service_keywords_register(akl);
10119
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010120 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010121
10122 alloc_error:
10123 release_hlua_function(fcn);
10124 ha_free(&akl);
10125 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10126 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010127}
10128
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010129/* This function initialises Lua cli handler. It copies the
10130 * arguments in the Lua stack and create channel IO objects.
10131 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010132static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010133{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010134 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010135 struct hlua *hlua;
10136 struct hlua_function *fcn;
10137 int i;
10138 const char *error;
10139
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010140 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010141 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010142
Willy Tarreaubafbe012017-11-24 17:34:44 +010010143 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010144 if (!hlua) {
10145 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010146 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010147 }
10148 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010149 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010150
10151 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010152 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010153 * applet_http. It is absolutely compatible.
10154 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010155 ctx->task = task_new_here();
10156 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010157 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010158 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010159 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010160 ctx->task->nice = 0;
10161 ctx->task->context = appctx;
10162 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010163
10164 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010165 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010166 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010167 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010168 }
10169
10170 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010171 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010172 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10173 error = lua_tostring(hlua->T, -1);
10174 else
10175 error = "critical error";
10176 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10177 goto error;
10178 }
10179
10180 /* Check stack available size. */
10181 if (!lua_checkstack(hlua->T, 2)) {
10182 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10183 goto error;
10184 }
10185
10186 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010187 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010188
10189 /* Once the arguments parsed, the CLI is like an AppletTCP,
10190 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010191 */
10192 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10193 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10194 goto error;
10195 }
10196 hlua->nargs = 1;
10197
10198 /* push keywords in the stack. */
10199 for (i = 0; *args[i]; i++) {
10200 /* Check stack available size. */
10201 if (!lua_checkstack(hlua->T, 1)) {
10202 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10203 goto error;
10204 }
10205 lua_pushstring(hlua->T, args[i]);
10206 hlua->nargs++;
10207 }
10208
10209 /* We must initialize the execution timeouts. */
10210 hlua->max_time = hlua_timeout_session;
10211
10212 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010213 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010214
10215 /* It's ok */
10216 return 0;
10217
10218 /* It's not ok. */
10219error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010220 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010221 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010222 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010223 return 1;
10224}
10225
10226static int hlua_cli_io_handler_fct(struct appctx *appctx)
10227{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010228 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010229 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010230 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010231 struct hlua_function *fcn;
10232
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010233 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010234 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010235 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010236
10237 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010238 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010239 return 1;
10240
10241 /* Execute the function. */
10242 switch (hlua_ctx_resume(hlua, 1)) {
10243
10244 /* finished. */
10245 case HLUA_E_OK:
10246 return 1;
10247
10248 /* yield. */
10249 case HLUA_E_AGAIN:
10250 /* We want write. */
10251 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010252 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010253 /* Set the timeout. */
10254 if (hlua->wake_time != TICK_ETERNITY)
10255 task_schedule(hlua->task, hlua->wake_time);
10256 return 0;
10257
10258 /* finished with error. */
10259 case HLUA_E_ERRMSG:
10260 /* Display log. */
10261 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10262 fcn->name, lua_tostring(hlua->T, -1));
10263 lua_pop(hlua->T, 1);
10264 return 1;
10265
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010266 case HLUA_E_ETMOUT:
10267 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10268 fcn->name);
10269 return 1;
10270
10271 case HLUA_E_NOMEM:
10272 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10273 fcn->name);
10274 return 1;
10275
10276 case HLUA_E_YIELD: /* unexpected */
10277 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10278 fcn->name);
10279 return 1;
10280
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010281 case HLUA_E_ERR:
10282 /* Display log. */
10283 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10284 fcn->name);
10285 return 1;
10286
10287 default:
10288 return 1;
10289 }
10290
10291 return 1;
10292}
10293
10294static void hlua_cli_io_release_fct(struct appctx *appctx)
10295{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010296 struct hlua_cli_ctx *ctx = appctx->svcctx;
10297
10298 hlua_ctx_destroy(ctx->hlua);
10299 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010300}
10301
10302/* This function is an LUA binding used for registering
10303 * new keywords in the cli. It expects a list of keywords
10304 * which are the "path". It is limited to 5 keywords. A
10305 * description of the command, a function to be executed
10306 * for the parsing and a function for io handlers.
10307 */
10308__LJMP static int hlua_register_cli(lua_State *L)
10309{
10310 struct cli_kw_list *cli_kws;
10311 const char *message;
10312 int ref_io;
10313 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010314 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010315 int index;
10316 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010317 struct buffer *trash;
10318 const char *kw[5];
10319 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010320 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010321
10322 MAY_LJMP(check_args(L, 3, "register_cli"));
10323
10324 /* First argument : an array of maximum 5 keywords. */
10325 if (!lua_istable(L, 1))
10326 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10327
10328 /* Second argument : string with contextual message. */
10329 message = MAY_LJMP(luaL_checkstring(L, 2));
10330
10331 /* Third and fourth argument : lua function. */
10332 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10333
Thierry Fournierf67442e2020-11-28 20:41:07 +010010334 /* Check for CLI service already registered */
10335 trash = get_trash_chunk();
10336 index = 0;
10337 lua_pushnil(L);
10338 memset(kw, 0, sizeof(kw));
10339 while (lua_next(L, 1) != 0) {
10340 if (index >= CLI_PREFIX_KW_NB)
10341 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10342 if (lua_type(L, -1) != LUA_TSTRING)
10343 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10344 kw[index] = lua_tostring(L, -1);
10345 if (index == 0)
10346 chunk_printf(trash, "%s", kw[index]);
10347 else
10348 chunk_appendf(trash, " %s", kw[index]);
10349 index++;
10350 lua_pop(L, 1);
10351 }
10352 cli_kw = cli_find_kw_exact((char **)kw);
10353 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010354 fcn = cli_kw->private;
10355 if (fcn->function_ref[hlua_state_id] != -1) {
10356 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10357 "This will become a hard error in version 2.5.\n", trash->area);
10358 }
10359 fcn->function_ref[hlua_state_id] = ref_io;
10360 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010361 }
10362
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010363 /* Allocate and fill the sample fetch keyword struct. */
10364 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010365 if (!cli_kws) {
10366 errmsg = "Lua out of memory error.";
10367 goto error;
10368 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010369 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010370 if (!fcn) {
10371 errmsg = "Lua out of memory error.";
10372 goto error;
10373 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010374
10375 /* Fill path. */
10376 index = 0;
10377 lua_pushnil(L);
10378 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010379 if (index >= 5) {
10380 errmsg = "1st argument must be a table with a maximum of 5 entries";
10381 goto error;
10382 }
10383 if (lua_type(L, -1) != LUA_TSTRING) {
10384 errmsg = "1st argument must be a table filled with strings";
10385 goto error;
10386 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010387 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010388 if (!cli_kws->kw[0].str_kw[index]) {
10389 errmsg = "Lua out of memory error.";
10390 goto error;
10391 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010392 index++;
10393 lua_pop(L, 1);
10394 }
10395
10396 /* Copy help message. */
10397 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010398 if (!cli_kws->kw[0].usage) {
10399 errmsg = "Lua out of memory error.";
10400 goto error;
10401 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010402
10403 /* Fill fcn io handler. */
10404 len = strlen("<lua.cli>") + 1;
10405 for (i = 0; i < index; i++)
10406 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10407 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010408 if (!fcn->name) {
10409 errmsg = "Lua out of memory error.";
10410 goto error;
10411 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010412 strncat((char *)fcn->name, "<lua.cli", len);
10413 for (i = 0; i < index; i++) {
10414 strncat((char *)fcn->name, ".", len);
10415 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10416 }
10417 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010418 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010419
10420 /* Fill last entries. */
10421 cli_kws->kw[0].private = fcn;
10422 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10423 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10424 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10425
10426 /* Register this new converter */
10427 cli_register_kw(cli_kws);
10428
10429 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010430
10431 error:
10432 release_hlua_function(fcn);
10433 if (cli_kws) {
10434 for (i = 0; i < index; i++)
10435 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10436 ha_free((char **)&(cli_kws->kw[0].usage));
10437 }
10438 ha_free(&cli_kws);
10439 WILL_LJMP(luaL_error(L, errmsg));
10440 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010441}
10442
Christopher Faulet69c581a2021-05-31 08:54:04 +020010443static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10444{
10445 struct hlua_flt_config *conf = fconf->conf;
10446 lua_State *L;
10447 int error, pos, state_id, flt_ref;
10448
10449 state_id = reg_flt_to_stack_id(conf->reg);
10450 L = hlua_states[state_id];
10451 pos = lua_gettop(L);
10452
10453 /* The filter parsing function */
10454 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10455
10456 /* Push the filter class on the stack and resolve all callbacks */
10457 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10458
10459 /* Duplicate the filter class so each filter will have its own copy */
10460 lua_newtable(L);
10461 lua_pushnil(L);
10462
10463 while (lua_next(L, pos+2)) {
10464 lua_pushvalue(L, -2);
10465 lua_insert(L, -2);
10466 lua_settable(L, -4);
10467 }
10468 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10469
10470 /* Remove the original lua filter class from the stack */
10471 lua_pop(L, 1);
10472
10473 /* Push the copy on the stack */
10474 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10475
10476 /* extra args are pushed in a table */
10477 lua_newtable(L);
10478 for (pos = 0; conf->args[pos]; pos++) {
10479 /* Check stack available size. */
10480 if (!lua_checkstack(L, 1)) {
10481 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10482 goto error;
10483 }
10484 lua_pushstring(L, conf->args[pos]);
10485 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10486 }
10487
10488 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10489 switch (error) {
10490 case LUA_OK:
10491 /* replace the filter ref */
10492 conf->ref[state_id] = flt_ref;
10493 break;
10494 case LUA_ERRRUN:
10495 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10496 goto error;
10497 case LUA_ERRMEM:
10498 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10499 goto error;
10500 case LUA_ERRERR:
10501 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10502 goto error;
10503#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10504 case LUA_ERRGCMM:
10505 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10506 goto error;
10507#endif
10508 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010509 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010510 goto error;
10511 }
10512
10513 lua_settop(L, 0);
10514 return 0;
10515
10516 error:
10517 lua_settop(L, 0);
10518 return -1;
10519}
10520
10521static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10522{
10523 struct hlua_flt_config *conf = fconf->conf;
10524 lua_State *L;
10525 int state_id;
10526
10527 if (!conf)
10528 return;
10529
10530 state_id = reg_flt_to_stack_id(conf->reg);
10531 L = hlua_states[state_id];
10532 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10533}
10534
10535static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10536{
10537 struct hlua_flt_config *conf = fconf->conf;
10538 int state_id = reg_flt_to_stack_id(conf->reg);
10539
10540 /* Rely on per-thread init for global scripts */
10541 if (!state_id)
10542 return hlua_filter_init_per_thread(px, fconf);
10543 return 0;
10544}
10545
10546static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10547{
10548
10549 if (fconf->conf) {
10550 struct hlua_flt_config *conf = fconf->conf;
10551 int state_id = reg_flt_to_stack_id(conf->reg);
10552 int pos;
10553
10554 /* Rely on per-thread deinit for global scripts */
10555 if (!state_id)
10556 hlua_filter_deinit_per_thread(px, fconf);
10557
10558 for (pos = 0; conf->args[pos]; pos++)
10559 free(conf->args[pos]);
10560 free(conf->args);
10561 }
10562 ha_free(&fconf->conf);
10563 ha_free((char **)&fconf->id);
10564 ha_free(&fconf->ops);
10565}
10566
10567static int hlua_filter_new(struct stream *s, struct filter *filter)
10568{
10569 struct hlua_flt_config *conf = FLT_CONF(filter);
10570 struct hlua_flt_ctx *flt_ctx = NULL;
10571 int ret = 1;
10572
10573 /* In the execution wrappers linked with a stream, the
10574 * Lua context can be not initialized. This behavior
10575 * permits to save performances because a systematic
10576 * Lua initialization cause 5% performances loss.
10577 */
10578 if (!s->hlua) {
10579 struct hlua *hlua;
10580
10581 hlua = pool_alloc(pool_head_hlua);
10582 if (!hlua) {
10583 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10584 conf->reg->name);
10585 ret = 0;
10586 goto end;
10587 }
10588 HLUA_INIT(hlua);
10589 s->hlua = hlua;
10590 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10591 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10592 conf->reg->name);
10593 ret = 0;
10594 goto end;
10595 }
10596 }
10597
10598 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10599 if (!flt_ctx) {
10600 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10601 conf->reg->name);
10602 ret = 0;
10603 goto end;
10604 }
10605 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10606 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10607 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10608 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10609 conf->reg->name);
10610 ret = 0;
10611 goto end;
10612 }
10613 HLUA_INIT(flt_ctx->hlua[0]);
10614 HLUA_INIT(flt_ctx->hlua[1]);
10615 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10616 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10617 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10618 conf->reg->name);
10619 ret = 0;
10620 goto end;
10621 }
10622
10623 if (!HLUA_IS_RUNNING(s->hlua)) {
10624 /* The following Lua calls can fail. */
10625 if (!SET_SAFE_LJMP(s->hlua)) {
10626 const char *error;
10627
10628 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10629 error = lua_tostring(s->hlua->T, -1);
10630 else
10631 error = "critical error";
10632 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10633 ret = 0;
10634 goto end;
10635 }
10636
10637 /* Check stack size. */
10638 if (!lua_checkstack(s->hlua->T, 1)) {
10639 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010640 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010641 ret = 0;
10642 goto end;
10643 }
10644
10645 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10646 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10647 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10648 conf->reg->name);
10649 RESET_SAFE_LJMP(s->hlua);
10650 ret = 0;
10651 goto end;
10652 }
10653 lua_insert(s->hlua->T, -2);
10654
10655 /* Push the copy on the stack */
10656 s->hlua->nargs = 1;
10657
10658 /* We must initialize the execution timeouts. */
10659 s->hlua->max_time = hlua_timeout_session;
10660
10661 /* At this point the execution is safe. */
10662 RESET_SAFE_LJMP(s->hlua);
10663 }
10664
10665 switch (hlua_ctx_resume(s->hlua, 0)) {
10666 case HLUA_E_OK:
10667 /* Nothing returned or not a table, ignore the filter for current stream */
10668 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10669 ret = 0;
10670 goto end;
10671 }
10672
10673 /* Attached the filter pointer to the ctx */
10674 lua_pushstring(s->hlua->T, "__filter");
10675 lua_pushlightuserdata(s->hlua->T, filter);
10676 lua_settable(s->hlua->T, -3);
10677
10678 /* Save a ref on the filter ctx */
10679 lua_pushvalue(s->hlua->T, 1);
10680 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10681 filter->ctx = flt_ctx;
10682 break;
10683 case HLUA_E_ERRMSG:
10684 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10685 ret = -1;
10686 goto end;
10687 case HLUA_E_ETMOUT:
10688 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10689 ret = 0;
10690 goto end;
10691 case HLUA_E_NOMEM:
10692 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10693 ret = 0;
10694 goto end;
10695 case HLUA_E_AGAIN:
10696 case HLUA_E_YIELD:
10697 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10698 " are not allowed from 'new' function.\n", conf->reg->name);
10699 ret = 0;
10700 goto end;
10701 case HLUA_E_ERR:
10702 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10703 ret = 0;
10704 goto end;
10705 default:
10706 ret = 0;
10707 goto end;
10708 }
10709
10710 end:
10711 if (s->hlua)
10712 lua_settop(s->hlua->T, 0);
10713 if (ret <= 0) {
10714 if (flt_ctx) {
10715 hlua_ctx_destroy(flt_ctx->hlua[0]);
10716 hlua_ctx_destroy(flt_ctx->hlua[1]);
10717 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10718 }
10719 }
10720 return ret;
10721}
10722
10723static void hlua_filter_delete(struct stream *s, struct filter *filter)
10724{
10725 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10726
10727 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10728 hlua_ctx_destroy(flt_ctx->hlua[0]);
10729 hlua_ctx_destroy(flt_ctx->hlua[1]);
10730 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10731 filter->ctx = NULL;
10732}
10733
Christopher Faulet9f55a502020-02-25 15:21:02 +010010734static int hlua_filter_from_payload(struct filter *filter)
10735{
10736 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10737
10738 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10739}
10740
Christopher Fauletc404f112020-02-26 15:03:09 +010010741static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10742 int dir, unsigned int flags)
10743{
10744 struct hlua *flt_hlua;
10745 struct hlua_flt_config *conf = FLT_CONF(filter);
10746 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10747 unsigned int hflags = HLUA_TXN_FLT_CTX;
10748 int ret = 1;
10749
10750 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10751 if (!flt_hlua)
10752 goto end;
10753
10754 if (!HLUA_IS_RUNNING(flt_hlua)) {
10755 int extra_idx = lua_gettop(flt_hlua->T);
10756
10757 /* The following Lua calls can fail. */
10758 if (!SET_SAFE_LJMP(flt_hlua)) {
10759 const char *error;
10760
10761 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10762 error = lua_tostring(flt_hlua->T, -1);
10763 else
10764 error = "critical error";
10765 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10766 goto end;
10767 }
10768
10769 /* Check stack size. */
10770 if (!lua_checkstack(flt_hlua->T, 3)) {
10771 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10772 RESET_SAFE_LJMP(flt_hlua);
10773 goto end;
10774 }
10775
10776 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10777 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10778 RESET_SAFE_LJMP(flt_hlua);
10779 goto end;
10780 }
10781 lua_insert(flt_hlua->T, -2);
10782
10783 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10784 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10785 RESET_SAFE_LJMP(flt_hlua);
10786 goto end;
10787 }
10788 flt_hlua->nargs = 2;
10789
10790 if (flags & HLUA_FLT_CB_ARG_CHN) {
10791 if (dir == SMP_OPT_DIR_REQ)
10792 lua_getfield(flt_hlua->T, -1, "req");
10793 else
10794 lua_getfield(flt_hlua->T, -1, "res");
10795 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10796 lua_pushstring(flt_hlua->T, "__filter");
10797 lua_pushlightuserdata(flt_hlua->T, filter);
10798 lua_settable(flt_hlua->T, -3);
10799 }
10800 flt_hlua->nargs++;
10801 }
10802 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010803 if (dir == SMP_OPT_DIR_REQ)
10804 lua_getfield(flt_hlua->T, -1, "http_req");
10805 else
10806 lua_getfield(flt_hlua->T, -1, "http_res");
10807 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10808 lua_pushstring(flt_hlua->T, "__filter");
10809 lua_pushlightuserdata(flt_hlua->T, filter);
10810 lua_settable(flt_hlua->T, -3);
10811 }
10812 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010813 }
10814
10815 /* Check stack size. */
10816 if (!lua_checkstack(flt_hlua->T, 1)) {
10817 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10818 RESET_SAFE_LJMP(flt_hlua);
10819 goto end;
10820 }
10821
10822 while (extra_idx--) {
10823 lua_pushvalue(flt_hlua->T, 1);
10824 lua_remove(flt_hlua->T, 1);
10825 flt_hlua->nargs++;
10826 }
10827
10828 /* We must initialize the execution timeouts. */
10829 flt_hlua->max_time = hlua_timeout_session;
10830
10831 /* At this point the execution is safe. */
10832 RESET_SAFE_LJMP(flt_hlua);
10833 }
10834
10835 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10836 case HLUA_E_OK:
10837 /* Catch the return value if it required */
10838 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10839 ret = lua_tointeger(flt_hlua->T, -1);
10840 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10841 }
10842
10843 /* Set timeout in the required channel. */
10844 if (flt_hlua->wake_time != TICK_ETERNITY) {
10845 if (dir == SMP_OPT_DIR_REQ)
10846 s->req.analyse_exp = flt_hlua->wake_time;
10847 else
10848 s->res.analyse_exp = flt_hlua->wake_time;
10849 }
10850 break;
10851 case HLUA_E_AGAIN:
10852 /* Set timeout in the required channel. */
10853 if (flt_hlua->wake_time != TICK_ETERNITY) {
10854 if (dir == SMP_OPT_DIR_REQ)
10855 s->req.analyse_exp = flt_hlua->wake_time;
10856 else
10857 s->res.analyse_exp = flt_hlua->wake_time;
10858 }
10859 /* Some actions can be wake up when a "write" event
10860 * is detected on a response channel. This is useful
10861 * only for actions targeted on the requests.
10862 */
10863 if (HLUA_IS_WAKERESWR(flt_hlua))
10864 s->res.flags |= CF_WAKE_WRITE;
10865 if (HLUA_IS_WAKEREQWR(flt_hlua))
10866 s->req.flags |= CF_WAKE_WRITE;
10867 ret = 0;
10868 goto end;
10869 case HLUA_E_ERRMSG:
10870 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10871 ret = -1;
10872 goto end;
10873 case HLUA_E_ETMOUT:
10874 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10875 goto end;
10876 case HLUA_E_NOMEM:
10877 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10878 goto end;
10879 case HLUA_E_YIELD:
10880 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10881 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10882 goto end;
10883 case HLUA_E_ERR:
10884 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10885 goto end;
10886 default:
10887 goto end;
10888 }
10889
10890
10891 end:
10892 return ret;
10893}
10894
10895static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10896{
10897 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10898
10899 flt_ctx->flags = 0;
10900 return hlua_filter_callback(s, filter, "start_analyze",
10901 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10902 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10903}
10904
10905static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10906{
10907 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10908
10909 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10910 return hlua_filter_callback(s, filter, "end_analyze",
10911 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10912 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10913}
10914
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010915static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10916{
10917 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10918
10919 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10920 return hlua_filter_callback(s, filter, "http_headers",
10921 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10922 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10923}
10924
10925static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10926 unsigned int offset, unsigned int len)
10927{
10928 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10929 struct hlua *flt_hlua;
10930 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10931 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10932 int ret;
10933
10934 flt_hlua = flt_ctx->hlua[idx];
10935 flt_ctx->cur_off[idx] = offset;
10936 flt_ctx->cur_len[idx] = len;
10937 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10938 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10939 if (ret != -1) {
10940 ret = flt_ctx->cur_len[idx];
10941 if (lua_gettop(flt_hlua->T) > 0) {
10942 ret = lua_tointeger(flt_hlua->T, -1);
10943 if (ret > flt_ctx->cur_len[idx])
10944 ret = flt_ctx->cur_len[idx];
10945 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10946 }
10947 }
10948 return ret;
10949}
10950
10951static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10952{
10953 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10954
10955 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10956 return hlua_filter_callback(s, filter, "http_end",
10957 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10958 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10959}
10960
Christopher Fauletc404f112020-02-26 15:03:09 +010010961static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10962 unsigned int offset, unsigned int len)
10963{
10964 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10965 struct hlua *flt_hlua;
10966 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10967 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10968 int ret;
10969
10970 flt_hlua = flt_ctx->hlua[idx];
10971 flt_ctx->cur_off[idx] = offset;
10972 flt_ctx->cur_len[idx] = len;
10973 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10974 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10975 if (ret != -1) {
10976 ret = flt_ctx->cur_len[idx];
10977 if (lua_gettop(flt_hlua->T) > 0) {
10978 ret = lua_tointeger(flt_hlua->T, -1);
10979 if (ret > flt_ctx->cur_len[idx])
10980 ret = flt_ctx->cur_len[idx];
10981 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10982 }
10983 }
10984 return ret;
10985}
10986
Christopher Faulet69c581a2021-05-31 08:54:04 +020010987static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10988 struct flt_conf *fconf, char **err, void *private)
10989{
10990 struct hlua_reg_filter *reg_flt = private;
10991 lua_State *L;
10992 struct hlua_flt_config *conf = NULL;
10993 const char *flt_id = NULL;
10994 int state_id, pos, flt_flags = 0;
10995 struct flt_ops *hlua_flt_ops = NULL;
10996
10997 state_id = reg_flt_to_stack_id(reg_flt);
10998 L = hlua_states[state_id];
10999
11000 /* Initialize the filter ops with default callbacks */
11001 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011002 if (!hlua_flt_ops)
11003 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011004 hlua_flt_ops->init = hlua_filter_init;
11005 hlua_flt_ops->deinit = hlua_filter_deinit;
11006 if (state_id) {
11007 /* Set per-thread callback if script is loaded per-thread */
11008 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11009 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11010 }
11011 hlua_flt_ops->attach = hlua_filter_new;
11012 hlua_flt_ops->detach = hlua_filter_delete;
11013
11014 /* Push the filter class on the stack and resolve all callbacks */
11015 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11016
Christopher Fauletc404f112020-02-26 15:03:09 +010011017 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11018 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11019 lua_pop(L, 1);
11020 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11021 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11022 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011023 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11024 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11025 lua_pop(L, 1);
11026 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11027 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11028 lua_pop(L, 1);
11029 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11030 hlua_flt_ops->http_end = hlua_filter_http_end;
11031 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011032 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11033 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11034 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011035
11036 /* Get id and flags of the filter class */
11037 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11038 flt_id = lua_tostring(L, -1);
11039 lua_pop(L, 1);
11040 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11041 flt_flags = lua_tointeger(L, -1);
11042 lua_pop(L, 1);
11043
11044 /* Create the filter config */
11045 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011046 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011047 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011048 conf->reg = reg_flt;
11049
11050 /* duplicate args */
11051 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11052 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011053 if (!conf->args)
11054 goto error;
11055 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011056 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011057 if (!conf->args[pos])
11058 goto error;
11059 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011060 conf->args[pos] = NULL;
11061 *cur_arg += pos + 1;
11062
Christopher Fauletc86bb872021-08-13 08:33:57 +020011063 if (flt_id) {
11064 fconf->id = strdup(flt_id);
11065 if (!fconf->id)
11066 goto error;
11067 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011068 fconf->flags = flt_flags;
11069 fconf->conf = conf;
11070 fconf->ops = hlua_flt_ops;
11071
11072 lua_settop(L, 0);
11073 return 0;
11074
11075 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011076 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011077 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011078 if (conf && conf->args) {
11079 for (pos = 0; conf->args[pos]; pos++)
11080 free(conf->args[pos]);
11081 free(conf->args);
11082 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011083 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011084 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011085 lua_settop(L, 0);
11086 return -1;
11087}
11088
Christopher Fauletc404f112020-02-26 15:03:09 +010011089__LJMP static int hlua_register_data_filter(lua_State *L)
11090{
11091 struct filter *filter;
11092 struct channel *chn;
11093
11094 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11095 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11096 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11097
11098 lua_getfield(L, 1, "__filter");
11099 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11100 filter = lua_touserdata (L, -1);
11101 lua_pop(L, 1);
11102
11103 register_data_filter(chn_strm(chn), chn, filter);
11104 return 1;
11105}
11106
11107__LJMP static int hlua_unregister_data_filter(lua_State *L)
11108{
11109 struct filter *filter;
11110 struct channel *chn;
11111
11112 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11113 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11114 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11115
11116 lua_getfield(L, 1, "__filter");
11117 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11118 filter = lua_touserdata (L, -1);
11119 lua_pop(L, 1);
11120
11121 unregister_data_filter(chn_strm(chn), chn, filter);
11122 return 1;
11123}
11124
Christopher Faulet69c581a2021-05-31 08:54:04 +020011125/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011126 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011127 * parse configuration arguments.
11128 */
11129__LJMP static int hlua_register_filter(lua_State *L)
11130{
11131 struct buffer *trash;
11132 struct flt_kw_list *fkl;
11133 struct flt_kw *fkw;
11134 const char *name;
11135 struct hlua_reg_filter *reg_flt= NULL;
11136 int flt_ref, fun_ref;
11137 int len;
11138
11139 MAY_LJMP(check_args(L, 3, "register_filter"));
11140
11141 /* First argument : filter name. */
11142 name = MAY_LJMP(luaL_checkstring(L, 1));
11143
11144 /* Second argument : The filter class */
11145 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11146
11147 /* Third argument : lua function. */
11148 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11149
11150 trash = get_trash_chunk();
11151 chunk_printf(trash, "lua.%s", name);
11152 fkw = flt_find_kw(trash->area);
11153 if (fkw != NULL) {
11154 reg_flt = fkw->private;
11155 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11156 ha_warning("Trying to register filter 'lua.%s' more than once. "
11157 "This will become a hard error in version 2.5.\n", name);
11158 }
11159 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11160 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11161 return 0;
11162 }
11163
11164 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11165 if (!fkl)
11166 goto alloc_error;
11167 fkl->scope = "HLUA";
11168
11169 reg_flt = new_hlua_reg_filter(name);
11170 if (!reg_flt)
11171 goto alloc_error;
11172
11173 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11174 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11175
11176 /* The filter keyword */
11177 len = strlen("lua.") + strlen(name) + 1;
11178 fkl->kw[0].kw = calloc(1, len);
11179 if (!fkl->kw[0].kw)
11180 goto alloc_error;
11181
11182 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11183
11184 fkl->kw[0].parse = hlua_filter_parse_fct;
11185 fkl->kw[0].private = reg_flt;
11186 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11187
11188 /* Register this new filter */
11189 flt_register_keywords(fkl);
11190
11191 return 0;
11192
11193 alloc_error:
11194 release_hlua_reg_filter(reg_flt);
11195 ha_free(&fkl);
11196 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11197 return 0; /* Never reached */
11198}
11199
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011200static int hlua_read_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, unsigned int *timeout)
11203{
11204 const char *error;
11205
11206 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011207 if (error == PARSE_TIME_OVER) {
11208 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11209 args[1], args[0]);
11210 return -1;
11211 }
11212 else if (error == PARSE_TIME_UNDER) {
11213 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11214 args[1], args[0]);
11215 return -1;
11216 }
11217 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011218 memprintf(err, "%s: invalid timeout", args[0]);
11219 return -1;
11220 }
11221 return 0;
11222}
11223
11224static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011225 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011226 char **err)
11227{
11228 return hlua_read_timeout(args, section_type, curpx, defpx,
11229 file, line, err, &hlua_timeout_session);
11230}
11231
11232static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011233 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011234 char **err)
11235{
11236 return hlua_read_timeout(args, section_type, curpx, defpx,
11237 file, line, err, &hlua_timeout_task);
11238}
11239
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011240static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011241 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011242 char **err)
11243{
11244 return hlua_read_timeout(args, section_type, curpx, defpx,
11245 file, line, err, &hlua_timeout_applet);
11246}
11247
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011248static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011249 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011250 char **err)
11251{
11252 char *error;
11253
11254 hlua_nb_instruction = strtoll(args[1], &error, 10);
11255 if (*error != '\0') {
11256 memprintf(err, "%s: invalid number", args[0]);
11257 return -1;
11258 }
11259 return 0;
11260}
11261
Willy Tarreau32f61e22015-03-18 17:54:59 +010011262static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011263 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011264 char **err)
11265{
11266 char *error;
11267
11268 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011269 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011270 return -1;
11271 }
11272 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11273 if (*error != '\0') {
11274 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11275 return -1;
11276 }
11277 return 0;
11278}
11279
11280
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011281/* This function is called by the main configuration key "lua-load". It loads and
11282 * execute an lua file during the parsing of the HAProxy configuration file. It is
11283 * the main lua entry point.
11284 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011285 * This function runs with the HAProxy keywords API. It returns -1 if an error
11286 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011287 *
11288 * In some error case, LUA set an error message in top of the stack. This function
11289 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011290 *
11291 * This function can fail with an abort() due to an Lua critical error.
11292 * We are in the configuration parsing process of HAProxy, this abort() is
11293 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011294 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011295static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011296{
11297 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011298 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011299
11300 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011301 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011302 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011303 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011304 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011305 return -1;
11306 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011307
11308 /* Push args in the Lua stack, except the first one which is the filename */
11309 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011310 /* Check stack size. */
11311 if (!lua_checkstack(L, 1)) {
11312 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11313 return -1;
11314 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011315 lua_pushstring(L, args[nargs]);
11316 }
11317 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011318
11319 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011320 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011321 switch (error) {
11322 case LUA_OK:
11323 break;
11324 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011325 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011326 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011327 return -1;
11328 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011329 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011330 return -1;
11331 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011332 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011333 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011334 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011335#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011336 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011337 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011338 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011339 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011340#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011341 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011342 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011343 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011344 return -1;
11345 }
11346
11347 return 0;
11348}
11349
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011350static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011351 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011352 char **err)
11353{
11354 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011355 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011356 return -1;
11357 }
11358
Thierry Fournier59f11be2020-11-29 00:37:41 +010011359 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011360 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011361 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011362 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011363}
11364
Thierry Fournier59f11be2020-11-29 00:37:41 +010011365static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011366 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011367 char **err)
11368{
11369 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011370 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011371
11372 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011373 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011374 return -1;
11375 }
11376
11377 if (per_thread_load == NULL) {
11378 /* allocate the first entry large enough to store the final NULL */
11379 per_thread_load = calloc(1, sizeof(*per_thread_load));
11380 if (per_thread_load == NULL) {
11381 memprintf(err, "out of memory error");
11382 return -1;
11383 }
11384 }
11385
11386 /* count used entries */
11387 for (len = 0; per_thread_load[len] != NULL; len++)
11388 ;
11389
11390 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11391 if (per_thread_load == NULL) {
11392 memprintf(err, "out of memory error");
11393 return -1;
11394 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011395 per_thread_load[len + 1] = NULL;
11396
Thierry Fournierae6b5682022-09-19 09:04:16 +020011397 /* count args excepting the first, allocate array and copy args */
11398 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011399 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011400 if (per_thread_load[len] == NULL) {
11401 memprintf(err, "out of memory error");
11402 return -1;
11403 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011404 for (i = 1; *(args[i]) != 0; i++) {
11405 per_thread_load[len][i - 1] = strdup(args[i]);
11406 if (per_thread_load[len][i - 1] == NULL) {
11407 memprintf(err, "out of memory error");
11408 return -1;
11409 }
11410 }
11411 per_thread_load[len][i - 1] = strdup("");
11412 if (per_thread_load[len][i - 1] == NULL) {
11413 memprintf(err, "out of memory error");
11414 return -1;
11415 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011416
11417 /* loading for thread 1 only */
11418 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011419 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011420 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011421}
11422
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011423/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11424 * in the given <ctx>.
11425 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011426static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011427{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011428 lua_getglobal(L, "package"); /* push package variable */
11429 lua_pushstring(L, path); /* push given path */
11430 lua_pushstring(L, ";"); /* push semicolon */
11431 lua_getfield(L, -3, type); /* push old path */
11432 lua_concat(L, 3); /* concatenate to new path */
11433 lua_setfield(L, -2, type); /* store new path */
11434 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011435
11436 return 0;
11437}
11438
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011439static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011440 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011441 char **err)
11442{
11443 char *path;
11444 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011445 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011446 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011447
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011448 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011449 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011450 }
11451
11452 if (!(*args[1])) {
11453 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011454 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011455 }
11456 path = args[1];
11457
11458 if (*args[2]) {
11459 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11460 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011461 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011462 }
11463 type = args[2];
11464 }
11465
Thierry Fournier59f11be2020-11-29 00:37:41 +010011466 p = calloc(1, sizeof(*p));
11467 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011468 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011469 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011470 }
11471 p->path = strdup(path);
11472 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011473 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011474 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011475 }
11476 p->type = strdup(type);
11477 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011478 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011479 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011480 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011481 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011482
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011483 /* Handle the global state and the per-thread state for the first
11484 * thread. The remaining threads will be initialized based on
11485 * prepend_path_list.
11486 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011487 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011488 lua_State *L = hlua_states[i];
11489 const char *error;
11490
11491 if (setjmp(safe_ljmp_env) != 0) {
11492 lua_atpanic(L, hlua_panic_safe);
11493 if (lua_type(L, -1) == LUA_TSTRING)
11494 error = lua_tostring(L, -1);
11495 else
11496 error = "critical error";
11497 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11498 exit(1);
11499 } else {
11500 lua_atpanic(L, hlua_panic_ljmp);
11501 }
11502
11503 hlua_prepend_path(L, type, path);
11504
11505 lua_atpanic(L, hlua_panic_safe);
11506 }
11507
Thierry Fournier59f11be2020-11-29 00:37:41 +010011508 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011509
11510err2:
11511 free(p->type);
11512 free(p->path);
11513err:
11514 free(p);
11515 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011516}
11517
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011518/* configuration keywords declaration */
11519static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011520 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011521 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011522 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011523 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11524 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011525 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011526 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011527 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011528 { 0, NULL, NULL },
11529}};
11530
Willy Tarreau0108d902018-11-25 19:14:37 +010011531INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11532
William Lallemand52139182022-03-30 15:05:42 +020011533#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011534
William Lallemand30fcca12022-03-30 12:03:12 +020011535/*
11536 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11537 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11538 * difference is that the yield in lua and for the CLI is not handled the same
11539 * way.
11540 */
11541__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11542{
11543 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11544 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11545 struct ckch_inst *ckchi = *lua_ckchi;
11546 struct ckch_store *old_ckchs = lua_ckchs[0];
11547 struct ckch_store *new_ckchs = lua_ckchs[1];
11548 struct hlua *hlua;
11549 char *err = NULL;
11550 int y = 1;
11551
11552 hlua = hlua_gethlua(L);
11553
11554 /* get the first ckchi to copy */
11555 if (ckchi == NULL)
11556 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11557
11558 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11559 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11560 struct ckch_inst *new_inst;
11561
11562 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11563 if (y % 10 == 0) {
11564
11565 *lua_ckchi = ckchi;
11566
11567 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11568 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11569 }
11570
11571 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11572 goto error;
11573
11574 /* link the new ckch_inst to the duplicate */
11575 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11576 y++;
11577 }
11578
11579 /* The generation is finished, we can insert everything */
11580 ckch_store_replace(old_ckchs, new_ckchs);
11581
11582 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11583
11584 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11585
11586 return 0;
11587
11588error:
11589 ckch_store_free(new_ckchs);
11590 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11591 WILL_LJMP(luaL_error(L, "%s", err));
11592 free(err);
11593
11594 return 0;
11595}
11596
11597/*
11598 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11599 * from the table in parameter.
11600 *
11601 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11602 * means it does not need to have a transaction since everything is done in the
11603 * same function.
11604 *
11605 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11606 *
11607 */
11608__LJMP static int hlua_ckch_set(lua_State *L)
11609{
11610 struct hlua *hlua;
11611 struct ckch_inst **lua_ckchi;
11612 struct ckch_store **lua_ckchs;
11613 struct ckch_store *old_ckchs = NULL;
11614 struct ckch_store *new_ckchs = NULL;
11615 int errcode = 0;
11616 char *err = NULL;
11617 struct cert_exts *cert_ext = NULL;
11618 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010011619 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020011620 int ret;
11621
11622 if (lua_type(L, -1) != LUA_TTABLE)
11623 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11624
11625 hlua = hlua_gethlua(L);
11626
11627 /* FIXME: this should not return an error but should come back later */
11628 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11629 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11630
11631 ret = lua_getfield(L, -1, "filename");
11632 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011633 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011634 errcode |= ERR_ALERT | ERR_FATAL;
11635 goto end;
11636 }
11637 filename = (char *)lua_tostring(L, -1);
11638
11639
11640 /* look for the filename in the tree */
11641 old_ckchs = ckchs_lookup(filename);
11642 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011643 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011644 errcode |= ERR_ALERT | ERR_FATAL;
11645 goto end;
11646 }
11647 /* TODO: handle extra_files_noext */
11648
11649 new_ckchs = ckchs_dup(old_ckchs);
11650 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011651 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011652 errcode |= ERR_ALERT | ERR_FATAL;
11653 goto end;
11654 }
11655
William Lallemand52ddd992022-11-22 11:51:53 +010011656 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020011657
11658 /* loop on the field in the table, which have the same name as the
11659 * possible extensions of files */
11660 lua_pushnil(L);
11661 while (lua_next(L, 1)) {
11662 int i;
11663 const char *field = lua_tostring(L, -2);
11664 char *payload = (char *)lua_tostring(L, -1);
11665
11666 if (!field || strcmp(field, "filename") == 0) {
11667 lua_pop(L, 1);
11668 continue;
11669 }
11670
11671 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11672 if (strcmp(field, cert_exts[i].ext) == 0) {
11673 cert_ext = &cert_exts[i];
11674 break;
11675 }
11676 }
11677
11678 /* this is the default type, the field is not supported */
11679 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011680 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011681 errcode |= ERR_ALERT | ERR_FATAL;
11682 goto end;
11683 }
11684
11685 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010011686 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011687 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011688 errcode |= ERR_ALERT | ERR_FATAL;
11689 goto end;
11690 }
11691 lua_pop(L, 1);
11692 }
11693
11694 /* store the pointers on the lua stack */
11695 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11696 lua_ckchs[0] = old_ckchs;
11697 lua_ckchs[1] = new_ckchs;
11698 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11699 *lua_ckchi = NULL;
11700
11701 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11702 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11703
11704end:
11705 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11706
11707 if (errcode & ERR_CODE) {
11708 ckch_store_free(new_ckchs);
11709 WILL_LJMP(luaL_error(L, "%s", err));
11710 }
11711 free(err);
11712
11713 return 0;
11714}
11715
William Lallemand52139182022-03-30 15:05:42 +020011716#else
11717
11718__LJMP static int hlua_ckch_set(lua_State *L)
11719{
11720 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11721
11722 return 0;
11723}
11724#endif /* ! USE_OPENSSL */
11725
11726
11727
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011728/* This function can fail with an abort() due to an Lua critical error.
11729 * We are in the initialisation process of HAProxy, this abort() is
11730 * tolerated.
11731 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011732int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011733{
11734 struct hlua_init_function *init;
11735 const char *msg;
11736 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011737 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011738 const char *kind;
11739 const char *trace;
11740 int return_status = 1;
11741#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11742 int nres;
11743#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011744
Willy Tarreaucdb53462020-12-02 12:12:00 +010011745 /* disable memory limit checks if limit is not set */
11746 if (!hlua_global_allocator.limit)
11747 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11748
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011749 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011750 if (setjmp(safe_ljmp_env) != 0) {
11751 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011752 if (lua_type(L, -1) == LUA_TSTRING)
11753 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011754 else
11755 error = "critical error";
11756 fprintf(stderr, "Lua post-init: %s.\n", error);
11757 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011758 } else {
11759 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011760 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011761
Thierry Fournierb8cef172020-11-28 15:37:17 +010011762 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011763
Thierry Fournierc7492592020-11-28 23:57:24 +010011764 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011765 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011766
11767#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011768 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011769#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011770 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011771#endif
11772 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011773 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011774
11775 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011776 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011777 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011778
11779 case LUA_ERRERR:
11780 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011781 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011782 case LUA_ERRRUN:
11783 if (!kind)
11784 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011785 msg = lua_tostring(L, -1);
11786 lua_settop(L, 0); /* Empty the stack. */
11787 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011788 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011789 if (msg)
11790 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11791 else
11792 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11793 return_status = 0;
11794 break;
11795
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011796 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011797 /* Unknown error */
11798 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011799 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011800 case LUA_YIELD:
11801 /* yield is not configured at this step, this state doesn't happen */
11802 if (!kind)
11803 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010011804 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011805 case LUA_ERRMEM:
11806 if (!kind)
11807 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011808 lua_settop(L, 0);
11809 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011810 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011811 ha_alert("Lua init: %s: %s\n", kind, trace);
11812 return_status = 0;
11813 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011814 }
Thierry Fournier670db242020-11-28 10:49:59 +010011815 if (!return_status)
11816 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011817 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011818
11819 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011820 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011821}
11822
Thierry Fournierb8cef172020-11-28 15:37:17 +010011823int hlua_post_init()
11824{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011825 int ret;
11826 int i;
11827 int errors;
11828 char *err = NULL;
11829 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011830 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011831
Willy Tarreaub1310492021-08-30 09:35:18 +020011832#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011833 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011834 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011835 int saved_used_backed = global.ssl_used_backend;
11836 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011837 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011838 global.ssl_used_backend = saved_used_backed;
11839 }
11840#endif
11841
Thierry Fournierc7492592020-11-28 23:57:24 +010011842 /* Perform post init of common thread */
11843 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011844 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011845 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11846 if (ret == 0)
11847 return 0;
11848
11849 /* init remaining lua states and load files */
11850 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11851
11852 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011853 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011854
11855 /* Init lua state */
11856 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11857
11858 /* Load lua files */
11859 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11860 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11861 if (ret != 0) {
11862 ha_alert("Lua init: %s\n", err);
11863 return 0;
11864 }
11865 }
11866 }
11867
11868 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011869 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011870
11871 /* Execute post init for all states */
11872 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11873
11874 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011875 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011876
11877 /* run post init */
11878 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11879 if (ret == 0)
11880 return 0;
11881 }
11882
11883 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011884 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011885
11886 /* control functions registering. Each function must have:
11887 * - only the function_ref[0] set positive and all other to -1
11888 * - only the function_ref[0] set to -1 and all other positive
11889 * This ensure a same reference is not used both in shared
11890 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011891 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011892 * complicated to found for the end user.
11893 */
11894 errors = 0;
11895 list_for_each_entry(fcn, &referenced_functions, l) {
11896 ret = 0;
11897 for (i = 1; i < global.nbthread + 1; i++) {
11898 if (fcn->function_ref[i] == -1)
11899 ret--;
11900 else
11901 ret++;
11902 }
11903 if (abs(ret) != global.nbthread) {
11904 ha_alert("Lua function '%s' is not referenced in all thread. "
11905 "Expect function in all thread or in none thread.\n", fcn->name);
11906 errors++;
11907 continue;
11908 }
11909
11910 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011911 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11912 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011913 "exclusive.\n", fcn->name);
11914 errors++;
11915 }
11916 }
11917
Christopher Faulet69c581a2021-05-31 08:54:04 +020011918 /* Do the same with registered filters */
11919 list_for_each_entry(reg_flt, &referenced_filters, l) {
11920 ret = 0;
11921 for (i = 1; i < global.nbthread + 1; i++) {
11922 if (reg_flt->flt_ref[i] == -1)
11923 ret--;
11924 else
11925 ret++;
11926 }
11927 if (abs(ret) != global.nbthread) {
11928 ha_alert("Lua filter '%s' is not referenced in all thread. "
11929 "Expect function in all thread or in none thread.\n", reg_flt->name);
11930 errors++;
11931 continue;
11932 }
11933
11934 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11935 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11936 "and per-thread Lua context (through lua-load-per-thread). these two context "
11937 "exclusive.\n", fcn->name);
11938 errors++;
11939 }
11940 }
11941
11942
Thierry Fournier59f11be2020-11-29 00:37:41 +010011943 if (errors > 0)
11944 return 0;
11945
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011946 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011947 * -1 in order to have probably a segfault if someone use it
11948 */
11949 hlua_state_id = -1;
11950
11951 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011952}
11953
Willy Tarreau32f61e22015-03-18 17:54:59 +010011954/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11955 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11956 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011957 * allocation. <nsize> is the requested new size. A new allocation is
11958 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011959 * zero. This one verifies that the limits are respected but is optimized
11960 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011961 *
11962 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11963 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11964 * that and will simply allocate zero as if it were the result of malloc(0),
11965 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11966 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011967 */
11968static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11969{
11970 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011971 size_t limit, old, new;
11972
11973 /* a limit of ~0 means unlimited and boot complete, so there's no need
11974 * for accounting anymore.
11975 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011976 if (likely(~zone->limit == 0)) {
11977 if (!nsize)
11978 ha_free(&ptr);
11979 else
11980 ptr = realloc(ptr, nsize);
11981 return ptr;
11982 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011983
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011984 if (!ptr)
11985 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011986
Willy Tarreaucdb53462020-12-02 12:12:00 +010011987 /* enforce strict limits across all threads */
11988 limit = zone->limit;
11989 old = _HA_ATOMIC_LOAD(&zone->allocated);
11990 do {
11991 new = old + nsize - osize;
11992 if (unlikely(nsize && limit && new > limit))
11993 return NULL;
11994 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011995
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011996 if (!nsize)
11997 ha_free(&ptr);
11998 else
11999 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012000
12001 if (unlikely(!ptr && nsize)) // failed
12002 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12003
12004 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012005 return ptr;
12006}
12007
Thierry Fournierecb83c22020-11-28 15:49:44 +010012008/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012009 * We are in the initialisation process of HAProxy, this abort() is
12010 * tolerated.
12011 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012012lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012013{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012014 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012015 int idx;
12016 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012017 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012018 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012019 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012020 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012021 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012022 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012023
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012024 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012025 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012026
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012027 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012028 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012029 *context = NULL;
12030
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012031 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012032 * the Lua function can fail with an abort. We are in the initialisation
12033 * process of HAProxy, this abort() is tolerated.
12034 */
12035
Thierry Fournier3c539322020-11-28 16:05:05 +010012036 /* Call post initialisation function in safe environment. */
12037 if (setjmp(safe_ljmp_env) != 0) {
12038 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012039 if (lua_type(L, -1) == LUA_TSTRING)
12040 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012041 else
12042 error_msg = "critical error";
12043 fprintf(stderr, "Lua init: %s.\n", error_msg);
12044 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012045 } else {
12046 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012047 }
12048
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012049 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012050 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012051#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12052#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12053#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012054 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012055#endif
12056#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012057 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012058#endif
12059#undef HLUA_PREPEND_PATH_TOSTRING
12060#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012061
Thierry Fournier59f11be2020-11-29 00:37:41 +010012062 /* Apply configured prepend path */
12063 list_for_each_entry(pp, &prepend_path_list, l)
12064 hlua_prepend_path(L, pp->type, pp->path);
12065
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012066 /*
12067 *
12068 * Create "core" object.
12069 *
12070 */
12071
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012072 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012073 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012074
Thierry Fournierecb83c22020-11-28 15:49:44 +010012075 /* set the thread id */
12076 hlua_class_const_int(L, "thread", thread_num);
12077
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012078 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012079 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012080 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012081
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012082 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012083 hlua_class_function(L, "register_init", hlua_register_init);
12084 hlua_class_function(L, "register_task", hlua_register_task);
12085 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12086 hlua_class_function(L, "register_converters", hlua_register_converters);
12087 hlua_class_function(L, "register_action", hlua_register_action);
12088 hlua_class_function(L, "register_service", hlua_register_service);
12089 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012090 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012091 hlua_class_function(L, "yield", hlua_yield);
12092 hlua_class_function(L, "set_nice", hlua_set_nice);
12093 hlua_class_function(L, "sleep", hlua_sleep);
12094 hlua_class_function(L, "msleep", hlua_msleep);
12095 hlua_class_function(L, "add_acl", hlua_add_acl);
12096 hlua_class_function(L, "del_acl", hlua_del_acl);
12097 hlua_class_function(L, "set_map", hlua_set_map);
12098 hlua_class_function(L, "del_map", hlua_del_map);
12099 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012100 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012101 hlua_class_function(L, "log", hlua_log);
12102 hlua_class_function(L, "Debug", hlua_log_debug);
12103 hlua_class_function(L, "Info", hlua_log_info);
12104 hlua_class_function(L, "Warning", hlua_log_warning);
12105 hlua_class_function(L, "Alert", hlua_log_alert);
12106 hlua_class_function(L, "done", hlua_done);
12107 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012108
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012109 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012110
12111 /*
12112 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012113 * Create "act" object.
12114 *
12115 */
12116
12117 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012118 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012119
12120 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012121 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12122 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12123 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12124 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12125 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12126 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12127 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12128 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012129
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012130 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012131
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012132 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012133
12134 /*
12135 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012136 * Create "Filter" object.
12137 *
12138 */
12139
12140 /* This table entry is the object "filter" base. */
12141 lua_newtable(L);
12142
12143 /* push flags and constants */
12144 hlua_class_const_int(L, "CONTINUE", 1);
12145 hlua_class_const_int(L, "WAIT", 0);
12146 hlua_class_const_int(L, "ERROR", -1);
12147
12148 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12149
Christopher Fauletc404f112020-02-26 15:03:09 +010012150 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12151 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12152 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12153
Christopher Faulet69c581a2021-05-31 08:54:04 +020012154 lua_setglobal(L, "filter");
12155
12156 /*
12157 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012158 * Register class Map
12159 *
12160 */
12161
12162 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012163 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012164
12165 /* register pattern types. */
12166 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012167 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012168 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012169 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012170 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012171 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012172
12173 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012174 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012175
12176 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012177 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012178
Ilya Shipitsind4259502020-04-08 01:07:56 +050012179 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 lua_pushstring(L, "__index");
12181 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012182
12183 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012184 hlua_class_function(L, "lookup", hlua_map_lookup);
12185 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012186
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012187 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012188
Thierry Fournier45e78d72016-02-19 18:34:46 +010012189 /* Register previous table in the registry with reference and named entry.
12190 * The function hlua_register_metatable() pops the stack, so we
12191 * previously create a copy of the table.
12192 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012193 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12194 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012195
12196 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012197 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012198
12199 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012201
12202 /*
12203 *
William Lallemand30fcca12022-03-30 12:03:12 +020012204 * Register "CertCache" class
12205 *
12206 */
12207
12208 /* Create and fill the metatable. */
12209 lua_newtable(L);
12210 /* Register */
12211 hlua_class_function(L, "set", hlua_ckch_set);
12212 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12213
12214 /*
12215 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012216 * Register class Channel
12217 *
12218 */
12219
12220 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012221 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012222
Ilya Shipitsind4259502020-04-08 01:07:56 +050012223 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012224 lua_pushstring(L, "__index");
12225 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012226
12227 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012228 hlua_class_function(L, "data", hlua_channel_get_data);
12229 hlua_class_function(L, "line", hlua_channel_get_line);
12230 hlua_class_function(L, "set", hlua_channel_set_data);
12231 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012232 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012233 hlua_class_function(L, "prepend", hlua_channel_prepend);
12234 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012235 hlua_class_function(L, "send", hlua_channel_send);
12236 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012237 hlua_class_function(L, "input", hlua_channel_get_in_len);
12238 hlua_class_function(L, "output", hlua_channel_get_out_len);
12239 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012240 hlua_class_function(L, "is_full", hlua_channel_is_full);
12241 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012242
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012243 /* Deprecated API */
12244 hlua_class_function(L, "get", hlua_channel_get);
12245 hlua_class_function(L, "dup", hlua_channel_dup);
12246 hlua_class_function(L, "getline", hlua_channel_getline);
12247 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12248 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12249
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012250 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012251
12252 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012253 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012254
12255 /*
12256 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012257 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012258 *
12259 */
12260
12261 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012262 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012263
Ilya Shipitsind4259502020-04-08 01:07:56 +050012264 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012265 lua_pushstring(L, "__index");
12266 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012267
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012268 /* Browse existing fetches and create the associated
12269 * object method.
12270 */
12271 sf = NULL;
12272 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012273 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12274 * by an underscore.
12275 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012276 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012277 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012278 if (*p == '.' || *p == '-' || *p == '+')
12279 *p = '_';
12280
12281 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012282 lua_pushstring(L, trash.area);
12283 lua_pushlightuserdata(L, sf);
12284 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12285 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012286 }
12287
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012288 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012289
12290 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012291 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012292
12293 /*
12294 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012295 * Register class Converters
12296 *
12297 */
12298
12299 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012300 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012301
12302 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012303 lua_pushstring(L, "__index");
12304 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012305
12306 /* Browse existing converters and create the associated
12307 * object method.
12308 */
12309 sc = NULL;
12310 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012311 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12312 * by an underscore.
12313 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012314 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012315 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012316 if (*p == '.' || *p == '-' || *p == '+')
12317 *p = '_';
12318
12319 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012320 lua_pushstring(L, trash.area);
12321 lua_pushlightuserdata(L, sc);
12322 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12323 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012324 }
12325
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012326 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012327
12328 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012329 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012330
12331 /*
12332 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012333 * Register class HTTP
12334 *
12335 */
12336
12337 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012338 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012339
Ilya Shipitsind4259502020-04-08 01:07:56 +050012340 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012341 lua_pushstring(L, "__index");
12342 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012343
12344 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012345 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12346 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12347 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12348 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12349 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12350 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12351 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12352 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12353 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12354 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012355
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012356 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12357 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12358 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12359 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12360 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12361 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12362 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012363
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012364 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012365
12366 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012367 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012368
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012369 /*
12370 *
12371 * Register class HTTPMessage
12372 *
12373 */
12374
12375 /* Create and fill the metatable. */
12376 lua_newtable(L);
12377
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012378 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012379 lua_pushstring(L, "__index");
12380 lua_newtable(L);
12381
12382 /* Register Lua functions. */
12383 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12384 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12385 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12386 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12387 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12388 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12389 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12390 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12391 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12392 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12393 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12394 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12395 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12396 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12397 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12398 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12399 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12400 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12401
12402 hlua_class_function(L, "body", hlua_http_msg_get_body);
12403 hlua_class_function(L, "set", hlua_http_msg_set_data);
12404 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12405 hlua_class_function(L, "append", hlua_http_msg_append);
12406 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12407 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12408 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12409 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12410
12411 hlua_class_function(L, "send", hlua_http_msg_send);
12412 hlua_class_function(L, "forward", hlua_http_msg_forward);
12413
12414 lua_rawset(L, -3);
12415
12416 /* Register previous table in the registry with reference and named entry. */
12417 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012418
12419 /*
12420 *
12421 * Register class HTTPClient
12422 *
12423 */
12424
12425 /* Create and fill the metatable. */
12426 lua_newtable(L);
12427 lua_pushstring(L, "__index");
12428 lua_newtable(L);
12429 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012430 hlua_class_function(L, "head", hlua_httpclient_head);
12431 hlua_class_function(L, "put", hlua_httpclient_put);
12432 hlua_class_function(L, "post", hlua_httpclient_post);
12433 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012434 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012435 /* Register the garbage collector entry. */
12436 lua_pushstring(L, "__gc");
12437 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12438 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12439
William Lallemand3956c4e2021-09-21 16:25:15 +020012440
12441
12442 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012443 /*
12444 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012445 * Register class AppletTCP
12446 *
12447 */
12448
12449 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012450 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012451
Ilya Shipitsind4259502020-04-08 01:07:56 +050012452 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012453 lua_pushstring(L, "__index");
12454 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012455
12456 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012457 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12458 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12459 hlua_class_function(L, "send", hlua_applet_tcp_send);
12460 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12461 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12462 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12463 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12464 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012465
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012466 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012467
12468 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012469 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012470
12471 /*
12472 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012473 * Register class AppletHTTP
12474 *
12475 */
12476
12477 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012478 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012479
Ilya Shipitsind4259502020-04-08 01:07:56 +050012480 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012481 lua_pushstring(L, "__index");
12482 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012483
12484 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012485 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12486 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12487 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12488 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12489 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12490 hlua_class_function(L, "getline", hlua_applet_http_getline);
12491 hlua_class_function(L, "receive", hlua_applet_http_recv);
12492 hlua_class_function(L, "send", hlua_applet_http_send);
12493 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12494 hlua_class_function(L, "set_status", hlua_applet_http_status);
12495 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012496
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012497 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012498
12499 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012500 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012501
12502 /*
12503 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012504 * Register class TXN
12505 *
12506 */
12507
12508 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012509 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012510
Ilya Shipitsind4259502020-04-08 01:07:56 +050012511 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012512 lua_pushstring(L, "__index");
12513 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012514
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012515 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012516 hlua_class_function(L, "set_priv", hlua_set_priv);
12517 hlua_class_function(L, "get_priv", hlua_get_priv);
12518 hlua_class_function(L, "set_var", hlua_set_var);
12519 hlua_class_function(L, "unset_var", hlua_unset_var);
12520 hlua_class_function(L, "get_var", hlua_get_var);
12521 hlua_class_function(L, "done", hlua_txn_done);
12522 hlua_class_function(L, "reply", hlua_txn_reply_new);
12523 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12524 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12525 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12526 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12527 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12528 hlua_class_function(L, "deflog", hlua_txn_deflog);
12529 hlua_class_function(L, "log", hlua_txn_log);
12530 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12531 hlua_class_function(L, "Info", hlua_txn_log_info);
12532 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12533 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012534
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012535 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012536
12537 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012538 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012539
12540 /*
12541 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012542 * Register class reply
12543 *
12544 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012545 lua_newtable(L);
12546 lua_pushstring(L, "__index");
12547 lua_newtable(L);
12548 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12549 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12550 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12551 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12552 lua_settable(L, -3); /* Sets the __index entry. */
12553 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012554
12555
12556 /*
12557 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012558 * Register class Socket
12559 *
12560 */
12561
12562 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012563 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012564
Ilya Shipitsind4259502020-04-08 01:07:56 +050012565 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012566 lua_pushstring(L, "__index");
12567 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012568
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012569#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012570 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012571#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012572 hlua_class_function(L, "connect", hlua_socket_connect);
12573 hlua_class_function(L, "send", hlua_socket_send);
12574 hlua_class_function(L, "receive", hlua_socket_receive);
12575 hlua_class_function(L, "close", hlua_socket_close);
12576 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12577 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12578 hlua_class_function(L, "setoption", hlua_socket_setoption);
12579 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012580
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012581 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012582
12583 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012584 lua_pushstring(L, "__gc");
12585 lua_pushcclosure(L, hlua_socket_gc, 0);
12586 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012587
12588 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012589 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012590
Thierry Fournieraafc7772020-12-04 11:47:47 +010012591 lua_atpanic(L, hlua_panic_safe);
12592
12593 return L;
12594}
12595
12596void hlua_init(void) {
12597 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012598 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012599#ifdef USE_OPENSSL
12600 struct srv_kw *kw;
12601 int tmp_error;
12602 char *error;
12603 char *args[] = { /* SSL client configuration. */
12604 "ssl",
12605 "verify",
12606 "none",
12607 NULL
12608 };
12609#endif
12610
12611 /* Init post init function list head */
12612 for (i = 0; i < MAX_THREADS + 1; i++)
12613 LIST_INIT(&hlua_init_functions[i]);
12614
12615 /* Init state for common/shared lua parts */
12616 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012617 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012618 hlua_states[0] = hlua_init_state(0);
12619
12620 /* Init state 1 for thread 0. We have at least one thread. */
12621 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012622 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012623 hlua_states[1] = hlua_init_state(1);
12624
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012625 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012626 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012627 if (!socket_proxy) {
12628 fprintf(stderr, "Lua init: %s\n", errmsg);
12629 exit(1);
12630 }
12631 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012632
12633 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012634 socket_tcp = new_server(socket_proxy);
12635 if (!socket_tcp) {
12636 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12637 exit(1);
12638 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012639
12640#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012641 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012642 socket_ssl = new_server(socket_proxy);
12643 if (!socket_ssl) {
12644 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12645 exit(1);
12646 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012647
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012648 socket_ssl->use_ssl = 1;
12649 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012650
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012651 for (i = 0; args[i] != NULL; i++) {
12652 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012653 /*
12654 *
12655 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012656 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012657 * features like client certificates and ssl_verify.
12658 *
12659 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012660 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012661 if (tmp_error != 0) {
12662 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12663 abort(); /* This must be never arrives because the command line
12664 not editable by the user. */
12665 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012666 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012667 }
12668 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012669#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012670
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012671}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012672
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012673static void hlua_deinit()
12674{
Willy Tarreau186f3762020-12-04 11:48:12 +010012675 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012676 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12677
12678 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12679 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012680
12681 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12682 if (hlua_states[thr])
12683 lua_close(hlua_states[thr]);
12684 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012685
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012686 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012687
Willy Tarreau0f143af2021-03-05 10:41:48 +010012688#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012689 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012690#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012691
12692 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012693}
12694
12695REGISTER_POST_DEINIT(hlua_deinit);
12696
Willy Tarreau80713382018-11-26 10:19:54 +010012697static void hlua_register_build_options(void)
12698{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012699 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012700
Willy Tarreaubb57d942016-12-21 19:04:56 +010012701 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12702 hap_register_build_opts(ptr, 1);
12703}
Willy Tarreau80713382018-11-26 10:19:54 +010012704
12705INITCALL0(STG_REGISTER, hlua_register_build_options);