blob: cc8624c50eee11277f0a08fcc21ca90d9c1748e6 [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
Willy Tarreau5321da92022-05-06 11:57:34 +02002003 if (ctx->die) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002004 sc_shutw(sc);
2005 sc_shutr(sc);
Willy Tarreau5321da92022-05-06 11:57:34 +02002006 notification_wake(&ctx->wake_on_read);
2007 notification_wake(&ctx->wake_on_write);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002008 stream_shutdown(__sc_strm(sc), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002009 }
2010
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002011 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002012 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002013 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002014
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002015 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002016 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002017 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002018
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002019 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002020 * to be notified whenever the connection completes.
2021 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002022 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002023 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002024 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002025 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002026 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002027 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002028
2029 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002030 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002031
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002032 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002033 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002034 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035
2036 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002037 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002038 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002039
2040 /* Some data were injected in the buffer, notify the stream
2041 * interface.
2042 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002043 if (!channel_is_empty(sc_ic(sc)))
2044 sc_update(sc);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002045
2046 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002047 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002048 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002049 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002050 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051}
2052
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002053static int hlua_socket_init(struct appctx *appctx)
2054{
2055 struct hlua_csk_ctx *ctx = appctx->svcctx;
2056 struct stream *s;
2057
2058 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2059 goto error;
2060
2061 s = appctx_strm(appctx);
2062
Willy Tarreau4596fe22022-05-17 19:07:51 +02002063 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002064 * and retrieve data from the server. The connection is initialized
2065 * with the "struct server".
2066 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002067 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002068
2069 /* Force destination server. */
2070 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2071 s->target = &socket_tcp->obj_type;
2072
2073 ctx->appctx = appctx;
2074 return 0;
2075
2076 error:
2077 return -1;
2078}
2079
Willy Tarreau87b09662015-04-03 00:22:06 +02002080/* This function is called when the "struct stream" is destroyed.
2081 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082 * Wake all the pending signals.
2083 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002084static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085{
Willy Tarreau5321da92022-05-06 11:57:34 +02002086 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002087 struct xref *peer;
2088
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002089 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002090 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002091 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002092 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002093
2094 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002095 notification_wake(&ctx->wake_on_read);
2096 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097}
2098
2099/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002100 * uses this object. If the stream does not exists, just quit.
2101 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002102 * pending signal can rest in the read and write lists. destroy
2103 * it.
2104 */
2105__LJMP static int hlua_socket_gc(lua_State *L)
2106{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002107 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002108 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002109 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002111 MAY_LJMP(check_args(L, 1, "__gc"));
2112
2113 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002114 peer = xref_get_peer_and_lock(&socket->xref);
2115 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002116 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002117
2118 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002119
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002120 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002121 ctx->die = 1;
2122 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002123
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002124 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002125 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126 return 0;
2127}
2128
2129/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002130 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131 */
sada05ed3302018-05-11 11:48:18 -07002132__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002133{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002134 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002135 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002136 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002137 struct hlua *hlua;
2138
2139 /* Get hlua struct, or NULL if we execute from main lua state */
2140 hlua = hlua_gethlua(L);
2141 if (!hlua)
2142 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002143
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002144 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002145
2146 /* Check if we run on the same thread than the xreator thread.
2147 * We cannot access to the socket if the thread is different.
2148 */
2149 if (socket->tid != tid)
2150 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2151
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002152 peer = xref_get_peer_and_lock(&socket->xref);
2153 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002154 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002155
2156 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002157 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002159 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002160 ctx->die = 1;
2161 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002163 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002164 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165 return 0;
2166}
2167
sada05ed3302018-05-11 11:48:18 -07002168/* The close function calls close_helper.
2169 */
2170__LJMP static int hlua_socket_close(lua_State *L)
2171{
2172 MAY_LJMP(check_args(L, 1, "close"));
2173 return hlua_socket_close_helper(L);
2174}
2175
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176/* This Lua function assumes that the stack contain three parameters.
2177 * 1 - USERDATA containing a struct socket
2178 * 2 - INTEGER with values of the macro defined below
2179 * If the integer is -1, we must read at most one line.
2180 * If the integer is -2, we ust read all the data until the
2181 * end of the stream.
2182 * If the integer is positive value, we must read a number of
2183 * bytes corresponding to this value.
2184 */
2185#define HLSR_READ_LINE (-1)
2186#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002187__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188{
2189 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2190 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002191 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002192 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002193 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002194 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002196 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002197 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002198 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002199 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002200 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002201 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002202 struct stream *s;
2203 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002204 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002206 /* Get hlua struct, or NULL if we execute from main lua state */
2207 hlua = hlua_gethlua(L);
2208
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209 /* Check if this lua stack is schedulable. */
2210 if (!hlua || !hlua->task)
2211 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2212 "'frontend', 'backend' or 'task'"));
2213
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002214 /* Check if we run on the same thread than the xreator thread.
2215 * We cannot access to the socket if the thread is different.
2216 */
2217 if (socket->tid != tid)
2218 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2219
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002220 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002221 peer = xref_get_peer_and_lock(&socket->xref);
2222 if (!peer)
2223 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002224
2225 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2226 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002227 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002229 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002232 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002233 if (nblk < 0) /* Connection close. */
2234 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002235 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002237
2238 /* remove final \r\n. */
2239 if (nblk == 1) {
2240 if (blk1[len1-1] == '\n') {
2241 len1--;
2242 skip_at_end++;
2243 if (blk1[len1-1] == '\r') {
2244 len1--;
2245 skip_at_end++;
2246 }
2247 }
2248 }
2249 else {
2250 if (blk2[len2-1] == '\n') {
2251 len2--;
2252 skip_at_end++;
2253 if (blk2[len2-1] == '\r') {
2254 len2--;
2255 skip_at_end++;
2256 }
2257 }
2258 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002259 }
2260
2261 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002263 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002264 if (nblk < 0) /* Connection close. */
2265 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002266 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267 goto connection_empty;
2268 }
2269
2270 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002272 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273 if (nblk < 0) /* Connection close. */
2274 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002275 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276 goto connection_empty;
2277
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002278 missing_bytes = wanted - socket->b.n;
2279 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002281 len1 = missing_bytes;
2282 } if (nblk == 2 && len1 + len2 > missing_bytes)
2283 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002284 }
2285
2286 len = len1;
2287
2288 luaL_addlstring(&socket->b, blk1, len1);
2289 if (nblk == 2) {
2290 len += len2;
2291 luaL_addlstring(&socket->b, blk2, len2);
2292 }
2293
2294 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002295 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296
2297 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002298 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299
2300 /* If the pattern reclaim to read all the data
2301 * in the connection, got out.
2302 */
2303 if (wanted == HLSR_READ_ALL)
2304 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002305 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 goto connection_empty;
2307
2308 /* Return result. */
2309 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002310 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 return 1;
2312
2313connection_closed:
2314
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002315 xref_unlock(&socket->xref, peer);
2316
2317no_peer:
2318
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 /* If the buffer containds data. */
2320 if (socket->b.n > 0) {
2321 luaL_pushresult(&socket->b);
2322 return 1;
2323 }
2324 lua_pushnil(L);
2325 lua_pushstring(L, "connection closed.");
2326 return 2;
2327
2328connection_empty:
2329
Willy Tarreau5321da92022-05-06 11:57:34 +02002330 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002331 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002333 }
2334 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002335 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336 return 0;
2337}
2338
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002339/* This Lua function gets two parameters. The first one can be string
2340 * or a number. If the string is "*l", the user requires one line. If
2341 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342 * If the value is a number, the user require a number of bytes equal
2343 * to the value. The default value is "*l" (a line).
2344 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002345 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 * integer takes this values:
2347 * -1 : read a line
2348 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002349 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002351 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 * concatenated with the read data.
2353 */
2354__LJMP static int hlua_socket_receive(struct lua_State *L)
2355{
2356 int wanted = HLSR_READ_LINE;
2357 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002358 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 char *error;
2360 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002361 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362
2363 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2364 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2365
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002366 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002367
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002368 /* Check if we run on the same thread than the xreator thread.
2369 * We cannot access to the socket if the thread is different.
2370 */
2371 if (socket->tid != tid)
2372 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2373
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 /* check for pattern. */
2375 if (lua_gettop(L) >= 2) {
2376 type = lua_type(L, 2);
2377 if (type == LUA_TSTRING) {
2378 pattern = lua_tostring(L, 2);
2379 if (strcmp(pattern, "*a") == 0)
2380 wanted = HLSR_READ_ALL;
2381 else if (strcmp(pattern, "*l") == 0)
2382 wanted = HLSR_READ_LINE;
2383 else {
2384 wanted = strtoll(pattern, &error, 10);
2385 if (*error != '\0')
2386 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2387 }
2388 }
2389 else if (type == LUA_TNUMBER) {
2390 wanted = lua_tointeger(L, 2);
2391 if (wanted < 0)
2392 WILL_LJMP(luaL_error(L, "Unsupported size."));
2393 }
2394 }
2395
2396 /* Set pattern. */
2397 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002398
2399 /* Check if we would replace the top by itself. */
2400 if (lua_gettop(L) != 2)
2401 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002402
Christopher Fauletc31b2002021-05-03 10:11:13 +02002403 /* Save index of the top of the stack because since buffers are used, it
2404 * may change
2405 */
2406 lastarg = lua_gettop(L);
2407
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002408 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 luaL_buffinit(L, &socket->b);
2410
2411 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002412 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413 if (lua_type(L, 3) != LUA_TSTRING)
2414 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2415 pattern = lua_tolstring(L, 3, &len);
2416 luaL_addlstring(&socket->b, pattern, len);
2417 }
2418
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002419 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420}
2421
2422/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002423 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002424 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002425static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002426{
2427 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002428 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002429 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002430 struct appctx *appctx;
2431 size_t buf_len;
2432 const char *buf;
2433 int len;
2434 int send_len;
2435 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002436 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002437 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002438 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002440 /* Get hlua struct, or NULL if we execute from main lua state */
2441 hlua = hlua_gethlua(L);
2442
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443 /* Check if this lua stack is schedulable. */
2444 if (!hlua || !hlua->task)
2445 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2446 "'frontend', 'backend' or 'task'"));
2447
2448 /* Get object */
2449 socket = MAY_LJMP(hlua_checksocket(L, 1));
2450 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002451 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002452
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002453 /* Check if we run on the same thread than the xreator thread.
2454 * We cannot access to the socket if the thread is different.
2455 */
2456 if (socket->tid != tid)
2457 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2458
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002459 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002460 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002461 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002462 lua_pushinteger(L, -1);
2463 return 1;
2464 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002465
2466 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2467 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002468 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002469 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002470
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002471 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002472 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002473 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474 lua_pushinteger(L, -1);
2475 return 1;
2476 }
2477
2478 /* Update the input buffer data. */
2479 buf += sent;
2480 send_len = buf_len - sent;
2481
2482 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002483 if (sent >= buf_len) {
2484 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002485 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002486 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002487
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002488 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002489 * the request buffer if its not required.
2490 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002491 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002492 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002493 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002494 }
2495
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002496 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002497 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002498 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002499 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002500 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501
2502 /* send data */
2503 if (len < send_len)
2504 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002505 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506
2507 /* "Not enough space" (-1), "Buffer too little to contain
2508 * the data" (-2) are not expected because the available length
2509 * is tested.
2510 * Other unknown error are also not expected.
2511 */
2512 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002513 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002514 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002515
sada05ed3302018-05-11 11:48:18 -07002516 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002517 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002518 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002519 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002520 return 1;
2521 }
2522
2523 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002524 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002525
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002526 /* Update length sent. */
2527 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002528 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002529
2530 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002531 if (sent + len >= buf_len) {
2532 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002533 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002534 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002535
2536hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002537 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002538 xref_unlock(&socket->xref, peer);
2539 WILL_LJMP(luaL_error(L, "out of memory"));
2540 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002541 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002542 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543 return 0;
2544}
2545
2546/* This function initiate the send of data. It just check the input
2547 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002548 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002549 * "hlua_socket_write_yield" that can yield.
2550 *
2551 * The Lua function gets between 3 and 4 parameters. The first one is
2552 * the associated object. The second is a string buffer. The third is
2553 * a facultative integer that represents where is the buffer position
2554 * of the start of the data that can send. The first byte is the
2555 * position "1". The default value is "1". The fourth argument is a
2556 * facultative integer that represents where is the buffer position
2557 * of the end of the data that can send. The default is the last byte.
2558 */
2559static int hlua_socket_send(struct lua_State *L)
2560{
2561 int i;
2562 int j;
2563 const char *buf;
2564 size_t buf_len;
2565
2566 /* Check number of arguments. */
2567 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2568 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2569
2570 /* Get the string. */
2571 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2572
2573 /* Get and check j. */
2574 if (lua_gettop(L) == 4) {
2575 j = MAY_LJMP(luaL_checkinteger(L, 4));
2576 if (j < 0)
2577 j = buf_len + j + 1;
2578 if (j > buf_len)
2579 j = buf_len + 1;
2580 lua_pop(L, 1);
2581 }
2582 else
2583 j = buf_len;
2584
2585 /* Get and check i. */
2586 if (lua_gettop(L) == 3) {
2587 i = MAY_LJMP(luaL_checkinteger(L, 3));
2588 if (i < 0)
2589 i = buf_len + i + 1;
2590 if (i > buf_len)
2591 i = buf_len + 1;
2592 lua_pop(L, 1);
2593 } else
2594 i = 1;
2595
2596 /* Check bth i and j. */
2597 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002598 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002599 return 1;
2600 }
2601 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002602 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603 return 1;
2604 }
2605 if (i == 0)
2606 i = 1;
2607 if (j == 0)
2608 j = 1;
2609
2610 /* Pop the string. */
2611 lua_pop(L, 1);
2612
2613 /* Update the buffer length. */
2614 buf += i - 1;
2615 buf_len = j - i + 1;
2616 lua_pushlstring(L, buf, buf_len);
2617
2618 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002619 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002621 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002622}
2623
Willy Tarreau22b0a682015-06-17 19:43:49 +02002624#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002625__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626{
2627 static char buffer[SOCKET_INFO_MAX_LEN];
2628 int ret;
2629 int len;
2630 char *p;
2631
2632 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2633 if (ret <= 0) {
2634 lua_pushnil(L);
2635 return 1;
2636 }
2637
2638 if (ret == AF_UNIX) {
2639 lua_pushstring(L, buffer+1);
2640 return 1;
2641 }
2642 else if (ret == AF_INET6) {
2643 buffer[0] = '[';
2644 len = strlen(buffer);
2645 buffer[len] = ']';
2646 len++;
2647 buffer[len] = ':';
2648 len++;
2649 p = buffer;
2650 }
2651 else if (ret == AF_INET) {
2652 p = buffer + 1;
2653 len = strlen(p);
2654 p[len] = ':';
2655 len++;
2656 }
2657 else {
2658 lua_pushnil(L);
2659 return 1;
2660 }
2661
2662 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2663 lua_pushnil(L);
2664 return 1;
2665 }
2666
2667 lua_pushstring(L, p);
2668 return 1;
2669}
2670
2671/* Returns information about the peer of the connection. */
2672__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2673{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002674 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002675 struct xref *peer;
2676 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002677 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002678 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002679 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002680
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002681 MAY_LJMP(check_args(L, 1, "getpeername"));
2682
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002683 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002685 /* Check if we run on the same thread than the xreator thread.
2686 * We cannot access to the socket if the thread is different.
2687 */
2688 if (socket->tid != tid)
2689 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2690
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002691 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002692 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002693 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694 lua_pushnil(L);
2695 return 1;
2696 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002697
2698 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002699 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002700 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002701 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002702 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002703 lua_pushnil(L);
2704 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002705 }
2706
Christopher Faulet16f16af2021-10-27 09:34:56 +02002707 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002708 xref_unlock(&socket->xref, peer);
2709 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002710}
2711
2712/* Returns information about my connection side. */
2713static int hlua_socket_getsockname(struct lua_State *L)
2714{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002715 struct hlua_socket *socket;
2716 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002717 struct appctx *appctx;
2718 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002719 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002720 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002721
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002722 MAY_LJMP(check_args(L, 1, "getsockname"));
2723
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002724 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002726 /* Check if we run on the same thread than the xreator thread.
2727 * We cannot access to the socket if the thread is different.
2728 */
2729 if (socket->tid != tid)
2730 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2731
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002732 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002733 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002734 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002735 lua_pushnil(L);
2736 return 1;
2737 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002738
2739 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002740 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002741
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002742 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002743 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002744 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002745 lua_pushnil(L);
2746 return 1;
2747 }
2748
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002749 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002750 xref_unlock(&socket->xref, peer);
2751 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002752}
2753
2754/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002755static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002756 .obj_type = OBJ_TYPE_APPLET,
2757 .name = "<LUA_TCP>",
2758 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002759 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002760 .release = hlua_socket_release,
2761};
2762
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002763__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002764{
2765 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002766 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002767 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002768 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002769 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002770 struct stream *s;
2771
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002772 /* Get hlua struct, or NULL if we execute from main lua state */
2773 hlua = hlua_gethlua(L);
2774 if (!hlua)
2775 return 0;
2776
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002777 /* Check if we run on the same thread than the xreator thread.
2778 * We cannot access to the socket if the thread is different.
2779 */
2780 if (socket->tid != tid)
2781 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2782
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002783 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002784 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002785 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002786 lua_pushnil(L);
2787 lua_pushstring(L, "Can't connect");
2788 return 2;
2789 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002790
2791 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2792 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002793 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002794
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002795 /* Check if we run on the same thread than the xreator thread.
2796 * We cannot access to the socket if the thread is different.
2797 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002798 if (socket->tid != tid) {
2799 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002800 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002801 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002802
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002803 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002804 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002805 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002806 lua_pushnil(L);
2807 lua_pushstring(L, "Can't connect");
2808 return 2;
2809 }
2810
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002811 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002812
2813 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002814 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002815 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002816 lua_pushinteger(L, 1);
2817 return 1;
2818 }
2819
Willy Tarreau5321da92022-05-06 11:57:34 +02002820 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002821 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002822 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002823 }
2824 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002825 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002826 return 0;
2827}
2828
2829/* This function fail or initite the connection. */
2830__LJMP static int hlua_socket_connect(struct lua_State *L)
2831{
2832 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002833 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002834 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002835 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002836 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002837 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002838 int low, high;
2839 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002840 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002841 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002842 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002843
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002844 if (lua_gettop(L) < 2)
2845 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002846
2847 /* Get args. */
2848 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002849
2850 /* Check if we run on the same thread than the xreator thread.
2851 * We cannot access to the socket if the thread is different.
2852 */
2853 if (socket->tid != tid)
2854 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2855
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002856 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002857 if (lua_gettop(L) >= 3) {
2858 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002859 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002860
Tim Duesterhus6edab862018-01-06 19:04:45 +01002861 /* Force the ip to end with a colon, to support IPv6 addresses
2862 * that are not enclosed within square brackets.
2863 */
2864 if (port > 0) {
2865 luaL_buffinit(L, &b);
2866 luaL_addstring(&b, ip);
2867 luaL_addchar(&b, ':');
2868 luaL_pushresult(&b);
2869 ip = lua_tolstring(L, lua_gettop(L), NULL);
2870 }
2871 }
2872
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002873 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002874 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002875 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002876 lua_pushnil(L);
2877 return 1;
2878 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002879
2880 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002881 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 +02002882 if (!addr) {
2883 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002884 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002885 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002886
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002887 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002888 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002889 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002890 if (port == -1) {
2891 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002892 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002893 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002894 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2895 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002896 if (port == -1) {
2897 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002898 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002899 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002900 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002901 }
2902 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002903
Willy Tarreau5321da92022-05-06 11:57:34 +02002904 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2905 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002906 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002907 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002908
Willy Tarreau3e7be362022-05-27 10:35:27 +02002909 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002910 xref_unlock(&socket->xref, peer);
2911 WILL_LJMP(luaL_error(L, "connect: internal error"));
2912 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002913
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002914 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002915 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002916 if (!hlua)
2917 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002918
2919 /* inform the stream that we want to be notified whenever the
2920 * connection completes.
2921 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002922 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002923 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002924 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002925
Willy Tarreauf31af932020-01-14 09:59:38 +01002926 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002927
Willy Tarreau5321da92022-05-06 11:57:34 +02002928 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002929 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002930 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002931 }
2932 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002933
2934 task_wakeup(s->task, TASK_WOKEN_INIT);
2935 /* Return yield waiting for connection. */
2936
Willy Tarreau9635e032018-10-16 17:52:55 +02002937 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002938
2939 return 0;
2940}
2941
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002942#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002943__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2944{
2945 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002946 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002947 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002948
2949 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2950 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002951
2952 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002953 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002954 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002955 lua_pushnil(L);
2956 return 1;
2957 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002958
Willy Tarreau0698c802022-05-11 14:09:57 +02002959 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002960
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002961 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002962 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002963 return MAY_LJMP(hlua_socket_connect(L));
2964}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002965#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002966
2967__LJMP static int hlua_socket_setoption(struct lua_State *L)
2968{
2969 return 0;
2970}
2971
2972__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2973{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002974 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002975 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002976 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002977 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002978 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002979
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002980 MAY_LJMP(check_args(L, 2, "settimeout"));
2981
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002982 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002983
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002984 /* convert the timeout to millis */
2985 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002986
Thierry Fournier17a921b2018-03-08 09:59:02 +01002987 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002988 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002989 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2990
Mark Lakes56cc1252018-03-27 09:48:06 +02002991 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002992 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002993
2994 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002995 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002996 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002997
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002998 /* Check if we run on the same thread than the xreator thread.
2999 * We cannot access to the socket if the thread is different.
3000 */
3001 if (socket->tid != tid)
3002 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3003
Mark Lakes56cc1252018-03-27 09:48:06 +02003004 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003005 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003006 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003007 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3008 WILL_LJMP(lua_error(L));
3009 return 0;
3010 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003011
Willy Tarreau0698c802022-05-11 14:09:57 +02003012 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003013
Cyril Bonté7bb63452018-08-17 23:51:02 +02003014 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003015 s->scf->ioto = tmout;
3016 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003017
3018 s->task->expire = tick_add_ifset(now_ms, tmout);
3019 task_queue(s->task);
3020
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003021 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003022
Thierry Fourniere9636f12018-03-08 09:54:32 +01003023 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003024 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003025}
3026
3027__LJMP static int hlua_socket_new(lua_State *L)
3028{
3029 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003030 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003031 struct appctx *appctx;
3032
3033 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003034 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003035 hlua_pusherror(L, "socket: full stack");
3036 goto out_fail_conf;
3037 }
3038
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003039 /* Create the object: obj[0] = userdata. */
3040 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003041 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003042 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003043 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003044 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003045
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003046 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003047 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003048 hlua_pusherror(L, "socket: uninitialized pools.");
3049 goto out_fail_conf;
3050 }
3051
Willy Tarreau87b09662015-04-03 00:22:06 +02003052 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003053 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3054 lua_setmetatable(L, -2);
3055
Willy Tarreaud420a972015-04-06 00:39:18 +02003056 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003057 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003058 if (!appctx) {
3059 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003060 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003061 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003062 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3063 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003064 ctx->die = 0;
3065 LIST_INIT(&ctx->wake_on_write);
3066 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003067
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003068 if (appctx_init(appctx) == -1) {
3069 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003070 goto out_fail_appctx;
3071 }
3072
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003073 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003074 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003075 return 1;
3076
Christopher Faulet13a35e52021-12-20 15:34:16 +01003077 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003078 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003079 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003080 WILL_LJMP(lua_error(L));
3081 return 0;
3082}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003083
3084/*
3085 *
3086 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003087 * Class Channel
3088 *
3089 *
3090 */
3091
3092/* Returns the struct hlua_channel join to the class channel in the
3093 * stack entry "ud" or throws an argument error.
3094 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003095__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003096{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003097 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003098}
3099
Willy Tarreau47860ed2015-03-10 14:07:50 +01003100/* Pushes the channel onto the top of the stack. If the stask does not have a
3101 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003102 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003103static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003104{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003105 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003106 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003107 return 0;
3108
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003109 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003110 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003111 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003112
3113 /* Pop a class sesison metatable and affect it to the userdata. */
3114 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3115 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003116 return 1;
3117}
3118
Christopher Faulet9f55a502020-02-25 15:21:02 +01003119/* Helper function returning a filter attached to a channel at the position <ud>
3120 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003121 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003122 * initialized.
3123 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003124static 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 +01003125{
3126 struct filter *filter = NULL;
3127
3128 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3129 struct hlua_flt_ctx *flt_ctx;
3130
3131 filter = lua_touserdata (L, -1);
3132 flt_ctx = filter->ctx;
3133 if (hlua_filter_from_payload(filter)) {
3134 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3135 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3136 }
3137 }
3138
3139 lua_pop(L, 1);
3140 return filter;
3141}
3142
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003143/* Copies <len> bytes of data present in the channel's buffer, starting at the
3144* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003145* responsibility to ensure <len> and <offset> are valid. It always return the
3146* length of the built string. <len> may be 0, in this case, an empty string is
3147* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003148*/
3149static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003150{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003151 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003152 luaL_Buffer b;
3153
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003154 block1 = len;
3155 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3156 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3157 block2 = len - block1;
3158
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003159 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003160 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3161 if (block2)
3162 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003163 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003164 return len;
3165}
3166
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003167/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3168 * function returns -1 if data cannot be copied. Otherwise, it returns the
3169 * number of bytes copied.
3170 */
3171static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3172{
3173 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003174
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003175 /* Nothing to do, just return */
3176 if (unlikely(istlen(str) == 0))
3177 goto end;
3178
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003179 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003180 ret = -1;
3181 goto end;
3182 }
3183 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3184
3185 end:
3186 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003187}
3188
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003189/* Removes <len> bytes of data at the absolute position <offset>.
3190 */
3191static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3192{
3193 size_t end = offset + len;
3194
3195 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3196 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3197 b_data(&chn->buf) - end, -len);
3198 b_sub(&chn->buf, len);
3199}
3200
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003201/* Copies input data in the channel's buffer. It is possible to set a specific
3202 * offset (0 by default) and a length (all remaining input data starting for the
3203 * offset by default). If there is not enough input data and more data can be
3204 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003205 *
3206 * From an action, All input data are considered. For a filter, the offset and
3207 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003208 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003209__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003210{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003211 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003212 struct filter *filter;
3213 size_t input, output;
3214 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003215
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003216 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003217
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003218 output = co_data(chn);
3219 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003220
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003221 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3222 if (filter && !hlua_filter_from_payload(filter))
3223 WILL_LJMP(lua_error(L));
3224
3225 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003226 if (lua_gettop(L) > 1) {
3227 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3228 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003229 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003230 offset += output;
3231 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003232 lua_pushfstring(L, "offset out of range.");
3233 WILL_LJMP(lua_error(L));
3234 }
3235 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003237 if (lua_gettop(L) == 3) {
3238 len = MAY_LJMP(luaL_checkinteger(L, 3));
3239 if (!len)
3240 goto dup;
3241 if (len == -1)
3242 len = global.tune.bufsize;
3243 if (len < 0) {
3244 lua_pushfstring(L, "length out of range.");
3245 WILL_LJMP(lua_error(L));
3246 }
3247 }
3248
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003249 /* Wait for more data if possible if no length was specified and there
3250 * is no data or not enough data was received.
3251 */
3252 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003253 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3254 /* Yield waiting for more data, as requested */
3255 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3256 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003257
3258 /* Return 'nil' if there is no data and the channel can't receive more data */
3259 if (!len) {
3260 lua_pushnil(L);
3261 return -1;
3262 }
3263
3264 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003265 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003266 }
3267
3268 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003269 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003270 return 1;
3271}
3272
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003273/* Copies the first line (including the trailing LF) of input data in the
3274 * channel's buffer. It is possible to set a specific offset (0 by default) and
3275 * a length (all remaining input data starting for the offset by default). If
3276 * there is not enough input data and more data can be received, the function
3277 * yields. If a length is explicitly specified, no more data are
3278 * copied. Otherwise, if no LF is found and more data can be received, this
3279 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003280 *
3281 * From an action, All input data are considered. For a filter, the offset and
3282 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003283 */
3284__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003285{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003286 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003287 struct filter *filter;
3288 size_t l, input, output;
3289 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003290
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003291 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003292 output = co_data(chn);
3293 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003294
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3296 if (filter && !hlua_filter_from_payload(filter))
3297 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003298
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003299 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003300 if (lua_gettop(L) > 1) {
3301 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3302 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003303 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003304 offset += output;
3305 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003306 lua_pushfstring(L, "offset out of range.");
3307 WILL_LJMP(lua_error(L));
3308 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003309 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003310
3311 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003312 if (lua_gettop(L) == 3) {
3313 len = MAY_LJMP(luaL_checkinteger(L, 3));
3314 if (!len)
3315 goto dup;
3316 if (len == -1)
3317 len = global.tune.bufsize;
3318 if (len < 0) {
3319 lua_pushfstring(L, "length out of range.");
3320 WILL_LJMP(lua_error(L));
3321 }
3322 }
3323
3324 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003325 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003326 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003327 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003328 len = l+1;
3329 goto dup;
3330 }
3331 }
3332
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003333 /* Wait for more data if possible if no line is found and no length was
3334 * specified or not enough data was received.
3335 */
3336 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003337 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3338 /* Yield waiting for more data */
3339 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3340 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003341
3342 /* Return 'nil' if there is no data and the channel can't receive more data */
3343 if (!len) {
3344 lua_pushnil(L);
3345 return -1;
3346 }
3347
3348 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003349 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003350 }
3351
3352 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003353 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003354 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003355}
3356
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003357/* [ DEPRECATED ]
3358 *
3359 * Duplicate all input data foud in the channel's buffer. The data are not
3360 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003361 *
3362 * From an action, All input data are considered. For a filter, the offset and
3363 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003364 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003365__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003366{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003367 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003368 struct filter *filter;
3369 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003370
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003371 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003372 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003373 if (IS_HTX_STRM(chn_strm(chn))) {
3374 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3375 WILL_LJMP(lua_error(L));
3376 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003377
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003378 offset = co_data(chn);
3379 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003380
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003381 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3382 if (filter && !hlua_filter_from_payload(filter))
3383 WILL_LJMP(lua_error(L));
3384
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003385 if (!ci_data(chn) && channel_input_closed(chn)) {
3386 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003387 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003388 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003389
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003390 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003391 return 1;
3392}
3393
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003394/* [ DEPRECATED ]
3395 *
3396 * Get all input data foud in the channel's buffer. The data are removed from
3397 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3398 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003399 *
3400 * From an action, All input data are considered. For a filter, the offset and
3401 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003402 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003403__LJMP static int hlua_channel_get(lua_State *L)
3404{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003405 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003406 struct filter *filter;
3407 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003408 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003409
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003410 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003411 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3412 if (IS_HTX_STRM(chn_strm(chn))) {
3413 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3414 WILL_LJMP(lua_error(L));
3415 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003416
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003417 offset = co_data(chn);
3418 len = ci_data(chn);
3419
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003420 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3421 if (filter && !hlua_filter_from_payload(filter))
3422 WILL_LJMP(lua_error(L));
3423
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003424 if (!ci_data(chn) && channel_input_closed(chn)) {
3425 lua_pushnil(L);
3426 return 1;
3427 }
3428
3429 ret = _hlua_channel_dup(chn, L, offset, len);
3430 _hlua_channel_delete(chn, offset, ret);
3431 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003432}
3433
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003434/* This functions consumes and returns one line. If the channel is closed,
3435 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003436 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003437 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003438 *
3439 * From an action, All input data are considered. For a filter, the offset and
3440 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003441 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003442__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003443{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003444 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003445 struct filter *filter;
3446 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003447 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003448
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003449 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003450
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003451 offset = co_data(chn);
3452 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003453
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003454 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3455 if (filter && !hlua_filter_from_payload(filter))
3456 WILL_LJMP(lua_error(L));
3457
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003458 if (!ci_data(chn) && channel_input_closed(chn)) {
3459 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003460 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003461 }
3462
3463 for (l = 0; l < len; l++) {
3464 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3465 len = l+1;
3466 goto dup;
3467 }
3468 }
3469
3470 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3471 /* Yield waiting for more data */
3472 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3473 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003474
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003475 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003476 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003477 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003478 return 1;
3479}
3480
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003481/* [ DEPRECATED ]
3482 *
3483 * Check arguments for the function "hlua_channel_getline_yield".
3484 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003485__LJMP static int hlua_channel_getline(lua_State *L)
3486{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003487 struct channel *chn;
3488
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003489 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003490 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3491 if (IS_HTX_STRM(chn_strm(chn))) {
3492 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3493 WILL_LJMP(lua_error(L));
3494 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003495 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3496}
3497
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003498/* Retrieves a given amount of input data at the given offset. By default all
3499 * available input data are returned. The offset may be negactive to start from
3500 * the end of input data. The length may be -1 to set it to the maximum buffer
3501 * size.
3502 */
3503__LJMP static int hlua_channel_get_data(lua_State *L)
3504{
3505 struct channel *chn;
3506
3507 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3508 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3509 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3510 if (IS_HTX_STRM(chn_strm(chn))) {
3511 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3512 WILL_LJMP(lua_error(L));
3513 }
3514 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3515}
3516
3517/* Retrieves a given amount of input data at the given offset. By default all
3518 * available input data are returned. The offset may be negactive to start from
3519 * the end of input data. The length may be -1 to set it to the maximum buffer
3520 * size.
3521 */
3522__LJMP static int hlua_channel_get_line(lua_State *L)
3523{
3524 struct channel *chn;
3525
3526 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3527 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3528 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3529 if (IS_HTX_STRM(chn_strm(chn))) {
3530 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3531 WILL_LJMP(lua_error(L));
3532 }
3533 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3534}
3535
3536/* Appends a string into the input side of channel. It returns the length of the
3537 * written string, or -1 if the channel is closed or if the buffer size is too
3538 * little for the data. 0 may be returned if nothing is copied. This function
3539 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003540 *
3541 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003542 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003543__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003544{
Christopher Faulet23976d92021-08-06 09:59:49 +02003545 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003546 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003547 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003548 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003549 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003550
3551 MAY_LJMP(check_args(L, 2, "append"));
3552 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003553 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003554 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003555 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003556 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003557 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003558
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003559 offset = co_data(chn);
3560 len = ci_data(chn);
3561
3562 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3563 if (filter && !hlua_filter_from_payload(filter))
3564 WILL_LJMP(lua_error(L));
3565
3566 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3567 if (ret > 0 && filter) {
3568 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3569
3570 flt_update_offsets(filter, chn, ret);
3571 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3572 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003573 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003574 return 1;
3575}
3576
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003577/* Prepends a string into the input side of channel. It returns the length of the
3578 * written string, or -1 if the channel is closed or if the buffer size is too
3579 * little for the data. 0 may be returned if nothing is copied. This function
3580 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003581 *
3582 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003583 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003584__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003585{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003586 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003587 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003588 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003590 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003591
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003593 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003594 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3595 if (IS_HTX_STRM(chn_strm(chn))) {
3596 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3597 WILL_LJMP(lua_error(L));
3598 }
3599
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003600 offset = co_data(chn);
3601 len = ci_data(chn);
3602
3603 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3604 if (filter && !hlua_filter_from_payload(filter))
3605 WILL_LJMP(lua_error(L));
3606
3607 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3608 if (ret > 0 && filter) {
3609 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3610
3611 flt_update_offsets(filter, chn, ret);
3612 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3613 }
3614
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003615 lua_pushinteger(L, ret);
3616 return 1;
3617}
3618
3619/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003620 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621 * returns the length of the written string, or -1 if the channel is closed or
3622 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 *
3624 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003625 */
3626__LJMP static int hlua_channel_insert_data(lua_State *L)
3627{
3628 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003629 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003631 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003632 int ret, offset;
3633
3634 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3635 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3636 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3637 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638
3639 output = co_data(chn);
3640 input = ci_data(chn);
3641
3642 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3643 if (filter && !hlua_filter_from_payload(filter))
3644 WILL_LJMP(lua_error(L));
3645
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003646 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003647 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003648 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003649 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003650 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003651 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003652 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003653 lua_pushfstring(L, "offset out of range.");
3654 WILL_LJMP(lua_error(L));
3655 }
3656 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003657 if (IS_HTX_STRM(chn_strm(chn))) {
3658 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3659 WILL_LJMP(lua_error(L));
3660 }
3661
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3663 if (ret > 0 && filter) {
3664 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003665
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666 flt_update_offsets(filter, chn, ret);
3667 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003668 }
3669
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003670 lua_pushinteger(L, ret);
3671 return 1;
3672}
3673/* Replaces a given amount of input data at the given offset by a string
3674 * content. By default all remaining data are removed (offset = 0 and len =
3675 * -1). It returns the length of the written string, or -1 if the channel is
3676 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003677 *
3678 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003679 */
3680__LJMP static int hlua_channel_set_data(lua_State *L)
3681{
3682 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003683 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003684 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003685 size_t sz, input, output;
3686 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003687
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3689 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3690 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3691 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003692
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003693 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003694 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003695 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003696 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003697
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003698 output = co_data(chn);
3699 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003701 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3702 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704
3705 offset = output;
3706 if (lua_gettop(L) > 2) {
3707 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3708 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003709 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003710 offset += output;
3711 if (offset < output || offset > input + output) {
3712 lua_pushfstring(L, "offset out of range.");
3713 WILL_LJMP(lua_error(L));
3714 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003715 }
3716
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717 len = output + input - offset;
3718 if (lua_gettop(L) == 4) {
3719 len = MAY_LJMP(luaL_checkinteger(L, 4));
3720 if (!len)
3721 goto set;
3722 if (len == -1)
3723 len = output + input - offset;
3724 if (len < 0 || offset + len > output + input) {
3725 lua_pushfstring(L, "length out of range.");
3726 WILL_LJMP(lua_error(L));
3727 }
3728 }
3729
3730 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003731 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003732 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003733 lua_pushinteger(L, -1);
3734 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003735 _hlua_channel_delete(chn, offset, len);
3736 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3737 if (filter) {
3738 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3739
3740 len -= (ret > 0 ? ret : 0);
3741 flt_update_offsets(filter, chn, -len);
3742 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3743 }
3744
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003745 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003746 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003747 return 1;
3748}
3749
3750/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003751 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003752 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003753 *
3754 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003755 */
3756__LJMP static int hlua_channel_del_data(lua_State *L)
3757{
3758 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003759 struct filter *filter;
3760 size_t input, output;
3761 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003762
3763 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3764 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3765 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003766
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003767 if (IS_HTX_STRM(chn_strm(chn))) {
3768 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3769 WILL_LJMP(lua_error(L));
3770 }
3771
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003772 output = co_data(chn);
3773 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003774
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003775 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3776 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003777 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003778
3779 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003780 if (lua_gettop(L) > 1) {
3781 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003782 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003783 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003784 offset += output;
3785 if (offset < output || offset > input + output) {
3786 lua_pushfstring(L, "offset out of range.");
3787 WILL_LJMP(lua_error(L));
3788 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003789 }
3790
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003791 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003792 if (lua_gettop(L) == 3) {
3793 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003794 if (!len)
3795 goto end;
3796 if (len == -1)
3797 len = output + input - offset;
3798 if (len < 0 || offset + len > output + input) {
3799 lua_pushfstring(L, "length out of range.");
3800 WILL_LJMP(lua_error(L));
3801 }
3802 }
3803
3804 _hlua_channel_delete(chn, offset, len);
3805 if (filter) {
3806 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3807
3808 flt_update_offsets(filter, chn, -len);
3809 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3810 }
3811
3812 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003813 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003814 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003815}
3816
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003817/* Append data in the output side of the buffer. This data is immediately
3818 * sent. The function returns the amount of data written. If the buffer
3819 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003820 * if the channel is closed.
3821 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003822__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003823{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003824 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003825 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003826 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003827 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003828 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003829 struct hlua *hlua;
3830
3831 /* Get hlua struct, or NULL if we execute from main lua state */
3832 hlua = hlua_gethlua(L);
3833 if (!hlua) {
3834 lua_pushnil(L);
3835 return 1;
3836 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003837
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3839 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3840 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003841
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842 offset = co_data(chn);
3843 len = ci_data(chn);
3844
3845 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3846 if (filter && !hlua_filter_from_payload(filter))
3847 WILL_LJMP(lua_error(L));
3848
3849
Willy Tarreau47860ed2015-03-10 14:07:50 +01003850 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003851 lua_pushinteger(L, -1);
3852 return 1;
3853 }
3854
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003855 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003856 if (len > sz -l) {
3857 if (filter) {
3858 lua_pushinteger(L, -1);
3859 return 1;
3860 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003862 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003863
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003864 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003865 if (ret == -1) {
3866 lua_pop(L, 1);
3867 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003868 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003869 }
3870 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003871 if (filter) {
3872 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3873
3874
3875 flt_update_offsets(filter, chn, ret);
3876 FLT_OFF(filter, chn) += ret;
3877 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3878 }
3879 else
3880 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003881
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003882 l += ret;
3883 lua_pop(L, 1);
3884 lua_pushinteger(L, l);
3885 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003886
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003887 if (l < sz) {
3888 /* Yield only if the channel's output is not empty.
3889 * Otherwise it means we cannot add more data. */
3890 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003891 return 1;
3892
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003893 /* If we are waiting for space in the response buffer, we
3894 * must set the flag WAKERESWR. This flag required the task
3895 * wake up if any activity is detected on the response buffer.
3896 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003897 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003898 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003899 else
3900 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003901 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003902 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003903
3904 return 1;
3905}
3906
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003907/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003908 * yield the LUA process, and resume it without checking the
3909 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003910 *
3911 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003912 */
3913__LJMP static int hlua_channel_send(lua_State *L)
3914{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003915 struct channel *chn;
3916
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003917 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003918 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3919 if (IS_HTX_STRM(chn_strm(chn))) {
3920 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3921 WILL_LJMP(lua_error(L));
3922 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003923 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003924 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003925}
3926
3927/* This function forward and amount of butes. The data pass from
3928 * the input side of the buffer to the output side, and can be
3929 * forwarded. This function never fails.
3930 *
3931 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003932 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003933 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003934__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003935{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003936 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003937 struct filter *filter;
3938 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003939 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003940 struct hlua *hlua;
3941
3942 /* Get hlua struct, or NULL if we execute from main lua state */
3943 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003944 if (!hlua) {
3945 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003946 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003947 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003948
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003949 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003950 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003951 l = MAY_LJMP(luaL_checkinteger(L, -1));
3952
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003953 offset = co_data(chn);
3954 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003955
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003956 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3957 if (filter && !hlua_filter_from_payload(filter))
3958 WILL_LJMP(lua_error(L));
3959
3960 max = fwd - l;
3961 if (max > len)
3962 max = len;
3963
3964 if (filter) {
3965 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3966
3967 FLT_OFF(filter, chn) += max;
3968 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3969 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3970 }
3971 else
3972 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003973
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003974 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003975 lua_pop(L, 1);
3976 lua_pushinteger(L, l);
3977
3978 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003979 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003980 /* The the input channel or the output channel are closed, we
3981 * must return the amount of data forwarded.
3982 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003983 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003984 return 1;
3985
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003986 /* If we are waiting for space data in the response buffer, we
3987 * must set the flag WAKERESWR. This flag required the task
3988 * wake up if any activity is detected on the response buffer.
3989 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003990 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003991 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003992 else
3993 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003994
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003995 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003996 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003997 }
3998
3999 return 1;
4000}
4001
4002/* Just check the input and prepare the stack for the previous
4003 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004004 *
4005 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004006 */
4007__LJMP static int hlua_channel_forward(lua_State *L)
4008{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004009 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004010
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004011 MAY_LJMP(check_args(L, 2, "forward"));
4012 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4013 if (IS_HTX_STRM(chn_strm(chn))) {
4014 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4015 WILL_LJMP(lua_error(L));
4016 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004017 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004018 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004019}
4020
4021/* Just returns the number of bytes available in the input
4022 * side of the buffer. This function never fails.
4023 */
4024__LJMP static int hlua_channel_get_in_len(lua_State *L)
4025{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004026 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004027 struct filter *filter;
4028 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004029
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004030 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004031 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004032
4033 output = co_data(chn);
4034 input = ci_data(chn);
4035 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4036 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4037 lua_pushinteger(L, input);
4038 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004039 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004040
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004041 lua_pushinteger(L, htx->data - co_data(chn));
4042 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004043 return 1;
4044}
4045
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004046/* Returns true if the channel is full. */
4047__LJMP static int hlua_channel_is_full(lua_State *L)
4048{
4049 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004050
4051 MAY_LJMP(check_args(L, 1, "is_full"));
4052 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004053 /* ignore the reserve, we are not on a producer side (ie in an
4054 * applet).
4055 */
4056 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004057 return 1;
4058}
4059
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004060/* Returns true if the channel may still receive data. */
4061__LJMP static int hlua_channel_may_recv(lua_State *L)
4062{
4063 struct channel *chn;
4064
4065 MAY_LJMP(check_args(L, 1, "may_recv"));
4066 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4067 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4068 return 1;
4069}
4070
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004071/* Returns true if the channel is the response channel. */
4072__LJMP static int hlua_channel_is_resp(lua_State *L)
4073{
4074 struct channel *chn;
4075
4076 MAY_LJMP(check_args(L, 1, "is_resp"));
4077 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4078
4079 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4080 return 1;
4081}
4082
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004083/* Just returns the number of bytes available in the output
4084 * side of the buffer. This function never fails.
4085 */
4086__LJMP static int hlua_channel_get_out_len(lua_State *L)
4087{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004088 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004089 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004090
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004091 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004092 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004093
4094 output = co_data(chn);
4095 input = ci_data(chn);
4096 hlua_channel_filter(L, 1, chn, &output, &input);
4097
4098 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004099 return 1;
4100}
4101
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004102/*
4103 *
4104 *
4105 * Class Fetches
4106 *
4107 *
4108 */
4109
4110/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004111 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004112 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004113__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004114{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004115 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004116}
4117
4118/* This function creates and push in the stack a fetch object according
4119 * with a current TXN.
4120 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004121static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004122{
Willy Tarreau7073c472015-04-06 11:15:40 +02004123 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004124
4125 /* Check stack size. */
4126 if (!lua_checkstack(L, 3))
4127 return 0;
4128
4129 /* Create the object: obj[0] = userdata.
4130 * Note that the base of the Fetches object is the
4131 * transaction object.
4132 */
4133 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004134 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004135 lua_rawseti(L, -2, 0);
4136
Willy Tarreau7073c472015-04-06 11:15:40 +02004137 hsmp->s = txn->s;
4138 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004139 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004140 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004141
4142 /* Pop a class sesison metatable and affect it to the userdata. */
4143 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4144 lua_setmetatable(L, -2);
4145
4146 return 1;
4147}
4148
4149/* This function is an LUA binding. It is called with each sample-fetch.
4150 * It uses closure argument to store the associated sample-fetch. It
4151 * returns only one argument or throws an error. An error is thrown
4152 * only if an error is encountered during the argument parsing. If
4153 * the "sample-fetch" function fails, nil is returned.
4154 */
4155__LJMP static int hlua_run_sample_fetch(lua_State *L)
4156{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004157 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004158 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004159 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004160 int i;
4161 struct sample smp;
4162
4163 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004164 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004165
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004166 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004167 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004168
Thierry FOURNIERca988662015-12-20 18:43:03 +01004169 /* Check execution authorization. */
4170 if (f->use & SMP_USE_HTTP_ANY &&
4171 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4172 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4173 "is not available in Lua services", f->kw);
4174 WILL_LJMP(lua_error(L));
4175 }
4176
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004177 /* Get extra arguments. */
4178 for (i = 0; i < lua_gettop(L) - 1; i++) {
4179 if (i >= ARGM_NBARGS)
4180 break;
4181 hlua_lua2arg(L, i + 2, &args[i]);
4182 }
4183 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004184 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004185
4186 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004187 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004188
4189 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004190 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004191 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004192 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004193 }
4194
4195 /* Initialise the sample. */
4196 memset(&smp, 0, sizeof(smp));
4197
4198 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004199 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004200 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004201 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004202 lua_pushstring(L, "");
4203 else
4204 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004205 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004206 }
4207
4208 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004209 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004210 hlua_smp2lua_str(L, &smp);
4211 else
4212 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004213
4214 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004215 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004216 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004217
4218 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004219 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004220 WILL_LJMP(lua_error(L));
4221 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004222}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004223
4224/*
4225 *
4226 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004227 * Class Converters
4228 *
4229 *
4230 */
4231
4232/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004233 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004234 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004235__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004236{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004237 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238}
4239
4240/* This function creates and push in the stack a Converters object
4241 * according with a current TXN.
4242 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004243static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004244{
Willy Tarreau7073c472015-04-06 11:15:40 +02004245 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004246
4247 /* Check stack size. */
4248 if (!lua_checkstack(L, 3))
4249 return 0;
4250
4251 /* Create the object: obj[0] = userdata.
4252 * Note that the base of the Converters object is the
4253 * same than the TXN object.
4254 */
4255 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004256 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004257 lua_rawseti(L, -2, 0);
4258
Willy Tarreau7073c472015-04-06 11:15:40 +02004259 hsmp->s = txn->s;
4260 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004261 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004262 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004263
Willy Tarreau87b09662015-04-03 00:22:06 +02004264 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004265 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4266 lua_setmetatable(L, -2);
4267
4268 return 1;
4269}
4270
4271/* This function is an LUA binding. It is called with each converter.
4272 * It uses closure argument to store the associated converter. It
4273 * returns only one argument or throws an error. An error is thrown
4274 * only if an error is encountered during the argument parsing. If
4275 * the converter function function fails, nil is returned.
4276 */
4277__LJMP static int hlua_run_sample_conv(lua_State *L)
4278{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004279 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004280 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004281 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004282 int i;
4283 struct sample smp;
4284
4285 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004286 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004287
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004288 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004289 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004290
4291 /* Get extra arguments. */
4292 for (i = 0; i < lua_gettop(L) - 2; i++) {
4293 if (i >= ARGM_NBARGS)
4294 break;
4295 hlua_lua2arg(L, i + 3, &args[i]);
4296 }
4297 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004298 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004299
4300 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004301 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004302
4303 /* Run the special args checker. */
4304 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4305 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004306 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004307 }
4308
4309 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004310 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004311 if (!hlua_lua2smp(L, 2, &smp)) {
4312 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004313 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004314 }
4315
Willy Tarreau1777ea62016-03-10 16:15:46 +01004316 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4317
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004318 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004319 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004320 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004321 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004322 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004323 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004324 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4325 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004326 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004327 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004328 }
4329
4330 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004331 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004332 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004333 lua_pushstring(L, "");
4334 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004335 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004336 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004337 }
4338
4339 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004340 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004341 hlua_smp2lua_str(L, &smp);
4342 else
4343 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004344 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004345 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004346 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004347
4348 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004349 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004350 WILL_LJMP(lua_error(L));
4351 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004352}
4353
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004354/*
4355 *
4356 *
4357 * Class AppletTCP
4358 *
4359 *
4360 */
4361
4362/* Returns a struct hlua_txn if the stack entry "ud" is
4363 * a class stream, otherwise it throws an error.
4364 */
4365__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4366{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004367 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004368}
4369
4370/* This function creates and push in the stack an Applet object
4371 * according with a current TXN.
4372 */
4373static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4374{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004375 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004376 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004377 struct proxy *p;
4378
4379 ALREADY_CHECKED(s);
4380 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004381
4382 /* Check stack size. */
4383 if (!lua_checkstack(L, 3))
4384 return 0;
4385
4386 /* Create the object: obj[0] = userdata.
4387 * Note that the base of the Converters object is the
4388 * same than the TXN object.
4389 */
4390 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004391 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004392 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004393 luactx->appctx = ctx;
4394 luactx->htxn.s = s;
4395 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004396
4397 /* Create the "f" field that contains a list of fetches. */
4398 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004399 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004400 return 0;
4401 lua_settable(L, -3);
4402
4403 /* Create the "sf" field that contains a list of stringsafe fetches. */
4404 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004405 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004406 return 0;
4407 lua_settable(L, -3);
4408
4409 /* Create the "c" field that contains a list of converters. */
4410 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004411 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004412 return 0;
4413 lua_settable(L, -3);
4414
4415 /* Create the "sc" field that contains a list of stringsafe converters. */
4416 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004417 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004418 return 0;
4419 lua_settable(L, -3);
4420
4421 /* Pop a class stream metatable and affect it to the table. */
4422 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4423 lua_setmetatable(L, -2);
4424
4425 return 1;
4426}
4427
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004428__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4429{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004430 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004431 struct stream *s;
4432 const char *name;
4433 size_t len;
4434 struct sample smp;
4435
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004436 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4437 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004438
4439 /* It is useles to retrieve the stream, but this function
4440 * runs only in a stream context.
4441 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004442 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004443 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004444 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004445
4446 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004447 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004448 hlua_lua2smp(L, 3, &smp);
4449
4450 /* Store the sample in a variable. */
4451 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004452
4453 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4454 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4455 else
4456 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4457
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004458 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004459}
4460
4461__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4462{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004463 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004464 struct stream *s;
4465 const char *name;
4466 size_t len;
4467 struct sample smp;
4468
4469 MAY_LJMP(check_args(L, 2, "unset_var"));
4470
4471 /* It is useles to retrieve the stream, but this function
4472 * runs only in a stream context.
4473 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004474 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004475 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004476 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004477
4478 /* Unset the variable. */
4479 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004480 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4481 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004482}
4483
4484__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4485{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004487 struct stream *s;
4488 const char *name;
4489 size_t len;
4490 struct sample smp;
4491
4492 MAY_LJMP(check_args(L, 2, "get_var"));
4493
4494 /* It is useles to retrieve the stream, but this function
4495 * runs only in a stream context.
4496 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004497 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004498 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004499 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004500
4501 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004502 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004503 lua_pushnil(L);
4504 return 1;
4505 }
4506
4507 return hlua_smp2lua(L, &smp);
4508}
4509
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004510__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4511{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004512 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4513 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004514 struct hlua *hlua;
4515
4516 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004517 if (!s->hlua)
4518 return 0;
4519 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004520
4521 MAY_LJMP(check_args(L, 2, "set_priv"));
4522
4523 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004524 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004525
4526 /* Get and store new value. */
4527 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4528 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4529
4530 return 0;
4531}
4532
4533__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4534{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004535 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4536 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004537 struct hlua *hlua;
4538
4539 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004540 if (!s->hlua) {
4541 lua_pushnil(L);
4542 return 1;
4543 }
4544 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004545
4546 /* Push configuration index in the stack. */
4547 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4548
4549 return 1;
4550}
4551
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004552/* If expected data not yet available, it returns a yield. This function
4553 * consumes the data in the buffer. It returns a string containing the
4554 * data. This string can be empty.
4555 */
4556__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4557{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004558 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004559 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004560 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004561 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004562 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004563 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004564 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004565
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004566 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004567 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004568
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004569 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004570 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004571 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004572 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004573 }
4574
4575 /* End of data: commit the total strings and return. */
4576 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004577 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004578 return 1;
4579 }
4580
4581 /* Ensure that the block 2 length is usable. */
4582 if (ret == 1)
4583 len2 = 0;
4584
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004585 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004586 luaL_addlstring(&luactx->b, blk1, len1);
4587 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588
4589 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004590 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004591 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004592 return 1;
4593}
4594
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004595/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004596__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4597{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004598 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004599
4600 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004601 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602
4603 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4604}
4605
4606/* If expected data not yet available, it returns a yield. This function
4607 * consumes the data in the buffer. It returns a string containing the
4608 * data. This string can be empty.
4609 */
4610__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4611{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004612 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004613 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004614 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004616 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004617 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004618 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004619 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004620
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004621 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004622 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004623
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004624 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004625 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004626 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004627 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004628 }
4629
4630 /* End of data: commit the total strings and return. */
4631 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004632 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004633 return 1;
4634 }
4635
4636 /* Ensure that the block 2 length is usable. */
4637 if (ret == 1)
4638 len2 = 0;
4639
4640 if (len == -1) {
4641
4642 /* If len == -1, catenate all the data avalaile and
4643 * yield because we want to get all the data until
4644 * the end of data stream.
4645 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004646 luaL_addlstring(&luactx->b, blk1, len1);
4647 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004648 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004649 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004650 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004651
4652 } else {
4653
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004654 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004655 if (len1 > len)
4656 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004657 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004658 len -= len1;
4659
4660 /* Copy the second block. */
4661 if (len2 > len)
4662 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004663 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004664 len -= len2;
4665
4666 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004667 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004668
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004669 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004670 if (len > 0) {
4671 lua_pushinteger(L, len);
4672 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004673 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004674 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004675 }
4676
4677 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004678 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004679 return 1;
4680 }
4681
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004682 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004683 hlua_pusherror(L, "Lua: internal error");
4684 WILL_LJMP(lua_error(L));
4685 return 0;
4686}
4687
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004688/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004689__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4690{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004691 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004692 int len = -1;
4693
4694 if (lua_gettop(L) > 2)
4695 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4696 if (lua_gettop(L) >= 2) {
4697 len = MAY_LJMP(luaL_checkinteger(L, 2));
4698 lua_pop(L, 1);
4699 }
4700
4701 /* Confirm or set the required length */
4702 lua_pushinteger(L, len);
4703
4704 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004705 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004706
4707 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4708}
4709
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004710/* Append data in the output side of the buffer. This data is immediately
4711 * sent. The function returns the amount of data written. If the buffer
4712 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004713 * if the channel is closed.
4714 */
4715__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4716{
4717 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004718 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004719 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4720 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004721 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004722 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004723 int max;
4724
4725 /* Get the max amount of data which can write as input in the channel. */
4726 max = channel_recv_max(chn);
4727 if (max > (len - l))
4728 max = len - l;
4729
4730 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004731 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004732
4733 /* update counters. */
4734 l += max;
4735 lua_pop(L, 1);
4736 lua_pushinteger(L, l);
4737
4738 /* If some data is not send, declares the situation to the
4739 * applet, and returns a yield.
4740 */
4741 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004742 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004743 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004744 }
4745
4746 return 1;
4747}
4748
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004749/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004750 * yield the LUA process, and resume it without checking the
4751 * input arguments.
4752 */
4753__LJMP static int hlua_applet_tcp_send(lua_State *L)
4754{
4755 MAY_LJMP(check_args(L, 2, "send"));
4756 lua_pushinteger(L, 0);
4757
4758 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4759}
4760
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004761/*
4762 *
4763 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004764 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004765 *
4766 *
4767 */
4768
4769/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004770 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004771 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004772__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004773{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004774 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004775}
4776
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004777/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004778 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004779 * It relies on the caller to have already reserved the room in ctx->svcctx
4780 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004781 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004782static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004783{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004784 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004785 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004786 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004787 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004788 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004789 struct htx *htx;
4790 struct htx_blk *blk;
4791 struct htx_sl *sl;
4792 struct ist path;
4793 unsigned long long len = 0;
4794 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004795 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004796
4797 /* Check stack size. */
4798 if (!lua_checkstack(L, 3))
4799 return 0;
4800
4801 /* Create the object: obj[0] = userdata.
4802 * Note that the base of the Converters object is the
4803 * same than the TXN object.
4804 */
4805 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004806 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004807 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004808 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004809 http_ctx->status = 200; /* Default status code returned. */
4810 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004811 luactx->htxn.s = s;
4812 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004813
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004814 /* Create the "f" field that contains a list of fetches. */
4815 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004816 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004817 return 0;
4818 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004819
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004820 /* Create the "sf" field that contains a list of stringsafe fetches. */
4821 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004822 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004823 return 0;
4824 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004826 /* Create the "c" field that contains a list of converters. */
4827 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004828 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004829 return 0;
4830 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004831
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004832 /* Create the "sc" field that contains a list of stringsafe converters. */
4833 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004834 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004835 return 0;
4836 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004837
Christopher Fauleta2097962019-07-15 16:25:33 +02004838 htx = htxbuf(&s->req.buf);
4839 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004840 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004841 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004842
Christopher Fauleta2097962019-07-15 16:25:33 +02004843 /* Stores the request method. */
4844 lua_pushstring(L, "method");
4845 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4846 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004847
Christopher Fauleta2097962019-07-15 16:25:33 +02004848 /* Stores the http version. */
4849 lua_pushstring(L, "version");
4850 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4851 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004852
Christopher Fauleta2097962019-07-15 16:25:33 +02004853 /* creates an array of headers. hlua_http_get_headers() crates and push
4854 * the array on the top of the stack.
4855 */
4856 lua_pushstring(L, "headers");
4857 htxn.s = s;
4858 htxn.p = px;
4859 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004860 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004861 return 0;
4862 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004863
Amaury Denoyellec453f952021-07-06 11:40:12 +02004864 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4865 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004866 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004867 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004868
Christopher Fauleta2097962019-07-15 16:25:33 +02004869 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004870 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004871 q = p;
4872 while (q < end && *q != '?')
4873 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004874
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004875 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004876 lua_pushstring(L, "path");
4877 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004878 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004879
Christopher Fauleta2097962019-07-15 16:25:33 +02004880 /* Stores the query string. */
4881 lua_pushstring(L, "qs");
4882 if (*q == '?')
4883 q++;
4884 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004885 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004886 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004887
Christopher Fauleta2097962019-07-15 16:25:33 +02004888 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4889 struct htx_blk *blk = htx_get_blk(htx, pos);
4890 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004891
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004892 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004893 break;
4894 if (type == HTX_BLK_DATA)
4895 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004896 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01004897 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02004898 len += htx->extra;
4899
4900 /* Stores the request path. */
4901 lua_pushstring(L, "length");
4902 lua_pushinteger(L, len);
4903 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004904
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004905 /* Create an empty array of HTTP request headers. */
4906 lua_pushstring(L, "response");
4907 lua_newtable(L);
4908 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004909
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004910 /* Pop a class stream metatable and affect it to the table. */
4911 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4912 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004913
4914 return 1;
4915}
4916
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004917__LJMP static int hlua_applet_http_set_var(lua_State *L)
4918{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004919 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004920 struct stream *s;
4921 const char *name;
4922 size_t len;
4923 struct sample smp;
4924
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004925 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4926 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004927
4928 /* It is useles to retrieve the stream, but this function
4929 * runs only in a stream context.
4930 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004931 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004932 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004933 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004934
4935 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004936 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004937 hlua_lua2smp(L, 3, &smp);
4938
4939 /* Store the sample in a variable. */
4940 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004941
4942 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4943 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4944 else
4945 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4946
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004947 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004948}
4949
4950__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4951{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004952 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004953 struct stream *s;
4954 const char *name;
4955 size_t len;
4956 struct sample smp;
4957
4958 MAY_LJMP(check_args(L, 2, "unset_var"));
4959
4960 /* It is useles to retrieve the stream, but this function
4961 * runs only in a stream context.
4962 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004963 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004964 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004965 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004966
4967 /* Unset the variable. */
4968 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004969 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4970 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004971}
4972
4973__LJMP static int hlua_applet_http_get_var(lua_State *L)
4974{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004975 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004976 struct stream *s;
4977 const char *name;
4978 size_t len;
4979 struct sample smp;
4980
4981 MAY_LJMP(check_args(L, 2, "get_var"));
4982
4983 /* It is useles to retrieve the stream, but this function
4984 * runs only in a stream context.
4985 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004986 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004987 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004988 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004989
4990 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004991 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004992 lua_pushnil(L);
4993 return 1;
4994 }
4995
4996 return hlua_smp2lua(L, &smp);
4997}
4998
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004999__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5000{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005001 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5002 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005003 struct hlua *hlua;
5004
5005 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005006 if (!s->hlua)
5007 return 0;
5008 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005009
5010 MAY_LJMP(check_args(L, 2, "set_priv"));
5011
5012 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005013 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005014
5015 /* Get and store new value. */
5016 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5017 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5018
5019 return 0;
5020}
5021
5022__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5023{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005024 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5025 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005026 struct hlua *hlua;
5027
5028 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005029 if (!s->hlua) {
5030 lua_pushnil(L);
5031 return 1;
5032 }
5033 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005034
5035 /* Push configuration index in the stack. */
5036 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5037
5038 return 1;
5039}
5040
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005041/* If expected data not yet available, it returns a yield. This function
5042 * consumes the data in the buffer. It returns a string containing the
5043 * data. This string can be empty.
5044 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005045__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005046{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005047 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005048 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005049 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005050 struct htx *htx;
5051 struct htx_blk *blk;
5052 size_t count;
5053 int stop = 0;
5054
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005055 htx = htx_from_buf(&req->buf);
5056 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005057 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005058
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005059 while (count && !stop && blk) {
5060 enum htx_blk_type type = htx_get_blk_type(blk);
5061 uint32_t sz = htx_get_blksz(blk);
5062 struct ist v;
5063 uint32_t vlen;
5064 char *nl;
5065
5066 vlen = sz;
5067 if (vlen > count) {
5068 if (type != HTX_BLK_DATA)
5069 break;
5070 vlen = count;
5071 }
5072
5073 switch (type) {
5074 case HTX_BLK_UNUSED:
5075 break;
5076
5077 case HTX_BLK_DATA:
5078 v = htx_get_blk_value(htx, blk);
5079 v.len = vlen;
5080 nl = istchr(v, '\n');
5081 if (nl != NULL) {
5082 stop = 1;
5083 vlen = nl - v.ptr + 1;
5084 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005085 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005086 break;
5087
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005088 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005089 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005090 stop = 1;
5091 break;
5092
5093 default:
5094 break;
5095 }
5096
Willy Tarreau84240042022-02-28 16:51:23 +01005097 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005098 count -= vlen;
5099 if (sz == vlen)
5100 blk = htx_remove_blk(htx, blk);
5101 else {
5102 htx_cut_data_blk(htx, blk, vlen);
5103 break;
5104 }
5105 }
5106
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005107 /* The message was fully consumed and no more data are expected
5108 * (EOM flag set).
5109 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005110 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005111 stop = 1;
5112
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005113 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005114 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005115 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005116 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005117 }
5118
5119 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005120 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005121 return 1;
5122}
5123
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005124
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005125/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005126__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005127{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005128 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005129
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005130 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005131 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005132
Christopher Fauleta2097962019-07-15 16:25:33 +02005133 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005134}
5135
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005136/* If expected data not yet available, it returns a yield. This function
5137 * consumes the data in the buffer. It returns a string containing the
5138 * data. This string can be empty.
5139 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005140__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005141{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005142 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005143 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005144 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005145 struct htx *htx;
5146 struct htx_blk *blk;
5147 size_t count;
5148 int len;
5149
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005150 htx = htx_from_buf(&req->buf);
5151 len = MAY_LJMP(luaL_checkinteger(L, 2));
5152 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005153 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005154 while (count && len && blk) {
5155 enum htx_blk_type type = htx_get_blk_type(blk);
5156 uint32_t sz = htx_get_blksz(blk);
5157 struct ist v;
5158 uint32_t vlen;
5159
5160 vlen = sz;
5161 if (len > 0 && vlen > len)
5162 vlen = len;
5163 if (vlen > count) {
5164 if (type != HTX_BLK_DATA)
5165 break;
5166 vlen = count;
5167 }
5168
5169 switch (type) {
5170 case HTX_BLK_UNUSED:
5171 break;
5172
5173 case HTX_BLK_DATA:
5174 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005175 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005176 break;
5177
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005178 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005179 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005180 len = 0;
5181 break;
5182
5183 default:
5184 break;
5185 }
5186
Willy Tarreau84240042022-02-28 16:51:23 +01005187 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005188 count -= vlen;
5189 if (len > 0)
5190 len -= vlen;
5191 if (sz == vlen)
5192 blk = htx_remove_blk(htx, blk);
5193 else {
5194 htx_cut_data_blk(htx, blk, vlen);
5195 break;
5196 }
5197 }
5198
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005199 /* The message was fully consumed and no more data are expected
5200 * (EOM flag set).
5201 */
Christopher Faulet4a209722022-08-29 15:37:16 +02005202 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005203 len = 0;
5204
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005205 htx_to_buf(htx, &req->buf);
5206
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005207 /* If we are no other data available, yield waiting for new data. */
5208 if (len) {
5209 if (len > 0) {
5210 lua_pushinteger(L, len);
5211 lua_replace(L, 2);
5212 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005213 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005214 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005215 }
5216
5217 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005218 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005219 return 1;
5220}
5221
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005222/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005223__LJMP static int hlua_applet_http_recv(lua_State *L)
5224{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005225 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005226 int len = -1;
5227
5228 /* Check arguments. */
5229 if (lua_gettop(L) > 2)
5230 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5231 if (lua_gettop(L) >= 2) {
5232 len = MAY_LJMP(luaL_checkinteger(L, 2));
5233 lua_pop(L, 1);
5234 }
5235
Christopher Fauleta2097962019-07-15 16:25:33 +02005236 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005237
Christopher Fauleta2097962019-07-15 16:25:33 +02005238 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005239 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005240
Christopher Fauleta2097962019-07-15 16:25:33 +02005241 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005242}
5243
5244/* Append data in the output side of the buffer. This data is immediately
5245 * sent. The function returns the amount of data written. If the buffer
5246 * cannot contain the data, the function yields. The function returns -1
5247 * if the channel is closed.
5248 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005249__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005250{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005251 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005252 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005253 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005254 struct htx *htx = htx_from_buf(&res->buf);
5255 const char *data;
5256 size_t len;
5257 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5258 int max;
5259
Christopher Faulet9060fc02019-07-03 11:39:30 +02005260 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005261 if (!max)
5262 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005263
5264 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5265
5266 /* Get the max amount of data which can write as input in the channel. */
5267 if (max > (len - l))
5268 max = len - l;
5269
5270 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005271 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005272 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005273
5274 /* update counters. */
5275 l += max;
5276 lua_pop(L, 1);
5277 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005278
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005279 /* If some data is not send, declares the situation to the
5280 * applet, and returns a yield.
5281 */
5282 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005283 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005284 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005285 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005286 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005287 }
5288
Christopher Fauleta2097962019-07-15 16:25:33 +02005289 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005290 return 1;
5291}
5292
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005293/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005294 * yield the LUA process, and resume it without checking the
5295 * input arguments.
5296 */
5297__LJMP static int hlua_applet_http_send(lua_State *L)
5298{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005299 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005300 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005301
5302 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005303 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005304 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5305 WILL_LJMP(lua_error(L));
5306 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005307
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005308 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005309 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005310
Christopher Fauleta2097962019-07-15 16:25:33 +02005311 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005312}
5313
5314__LJMP static int hlua_applet_http_addheader(lua_State *L)
5315{
5316 const char *name;
5317 int ret;
5318
5319 MAY_LJMP(hlua_checkapplet_http(L, 1));
5320 name = MAY_LJMP(luaL_checkstring(L, 2));
5321 MAY_LJMP(luaL_checkstring(L, 3));
5322
5323 /* Push in the stack the "response" entry. */
5324 ret = lua_getfield(L, 1, "response");
5325 if (ret != LUA_TTABLE) {
5326 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5327 "is expected as an array. %s found", lua_typename(L, ret));
5328 WILL_LJMP(lua_error(L));
5329 }
5330
5331 /* check if the header is already registered if it is not
5332 * the case, register it.
5333 */
5334 ret = lua_getfield(L, -1, name);
5335 if (ret == LUA_TNIL) {
5336
5337 /* Entry not found. */
5338 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5339
5340 /* Insert the new header name in the array in the top of the stack.
5341 * It left the new array in the top of the stack.
5342 */
5343 lua_newtable(L);
5344 lua_pushvalue(L, 2);
5345 lua_pushvalue(L, -2);
5346 lua_settable(L, -4);
5347
5348 } else if (ret != LUA_TTABLE) {
5349
5350 /* corruption error. */
5351 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5352 "is expected as an array. %s found", name, lua_typename(L, ret));
5353 WILL_LJMP(lua_error(L));
5354 }
5355
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005356 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005357 * the header value as new entry.
5358 */
5359 lua_pushvalue(L, 3);
5360 ret = lua_rawlen(L, -2);
5361 lua_rawseti(L, -2, ret + 1);
5362 lua_pushboolean(L, 1);
5363 return 1;
5364}
5365
5366__LJMP static int hlua_applet_http_status(lua_State *L)
5367{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005368 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005369 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005370 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005371 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005372
5373 if (status < 100 || status > 599) {
5374 lua_pushboolean(L, 0);
5375 return 1;
5376 }
5377
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005378 http_ctx->status = status;
5379 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005380 lua_pushboolean(L, 1);
5381 return 1;
5382}
5383
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005384
Christopher Fauleta2097962019-07-15 16:25:33 +02005385__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005386{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005387 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005388 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005389 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005390 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005391 struct htx *htx;
5392 struct htx_sl *sl;
5393 struct h1m h1m;
5394 const char *status, *reason;
5395 const char *name, *value;
5396 size_t nlen, vlen;
5397 unsigned int flags;
5398
5399 /* Send the message at once. */
5400 htx = htx_from_buf(&res->buf);
5401 h1m_init_res(&h1m);
5402
5403 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005404 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5405 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005406 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005407 reason = http_get_reason(http_ctx->status);
5408 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005409 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5410 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5411 }
5412 else {
5413 flags = HTX_SL_F_IS_RESP;
5414 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5415 }
5416 if (!sl) {
5417 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005418 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005419 WILL_LJMP(lua_error(L));
5420 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005421 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005422
5423 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005424 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5425 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005426 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005427 WILL_LJMP(lua_error(L));
5428 }
5429
5430 /* Browse the list of headers. */
5431 lua_pushnil(L);
5432 while(lua_next(L, -2) != 0) {
5433 /* We expect a string as -2. */
5434 if (lua_type(L, -2) != LUA_TSTRING) {
5435 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005436 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005437 lua_typename(L, lua_type(L, -2)));
5438 WILL_LJMP(lua_error(L));
5439 }
5440 name = lua_tolstring(L, -2, &nlen);
5441
5442 /* We expect an array as -1. */
5443 if (lua_type(L, -1) != LUA_TTABLE) {
5444 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 +02005445 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005446 name,
5447 lua_typename(L, lua_type(L, -1)));
5448 WILL_LJMP(lua_error(L));
5449 }
5450
5451 /* Browse the table who is on the top of the stack. */
5452 lua_pushnil(L);
5453 while(lua_next(L, -2) != 0) {
5454 int id;
5455
5456 /* We expect a number as -2. */
5457 if (lua_type(L, -2) != LUA_TNUMBER) {
5458 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 +02005459 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005460 name,
5461 lua_typename(L, lua_type(L, -2)));
5462 WILL_LJMP(lua_error(L));
5463 }
5464 id = lua_tointeger(L, -2);
5465
5466 /* We expect a string as -2. */
5467 if (lua_type(L, -1) != LUA_TSTRING) {
5468 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 +02005469 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005470 name, id,
5471 lua_typename(L, lua_type(L, -1)));
5472 WILL_LJMP(lua_error(L));
5473 }
5474 value = lua_tolstring(L, -1, &vlen);
5475
5476 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005477 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5478 int ret;
5479
5480 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5481 if (ret < 0) {
5482 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5483 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5484 name);
5485 WILL_LJMP(lua_error(L));
5486 }
5487 else if (ret == 0)
5488 goto next; /* Skip it */
5489 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005490 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5491 struct ist v = ist2(value, vlen);
5492 int ret;
5493
5494 ret = h1_parse_cont_len_header(&h1m, &v);
5495 if (ret < 0) {
5496 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005497 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005498 name);
5499 WILL_LJMP(lua_error(L));
5500 }
5501 else if (ret == 0)
5502 goto next; /* Skip it */
5503 }
5504
5505 /* Add a new header */
5506 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5507 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005508 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005509 name);
5510 WILL_LJMP(lua_error(L));
5511 }
5512 next:
5513 /* Remove the array from the stack, and get next element with a remaining string. */
5514 lua_pop(L, 1);
5515 }
5516
5517 /* Remove the array from the stack, and get next element with a remaining string. */
5518 lua_pop(L, 1);
5519 }
5520
5521 if (h1m.flags & H1_MF_CHNK)
5522 h1m.flags &= ~H1_MF_CLEN;
5523 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5524 h1m.flags |= H1_MF_XFER_LEN;
5525
5526 /* Uset HTX start-line flags */
5527 if (h1m.flags & H1_MF_XFER_ENC)
5528 flags |= HTX_SL_F_XFER_ENC;
5529 if (h1m.flags & H1_MF_XFER_LEN) {
5530 flags |= HTX_SL_F_XFER_LEN;
5531 if (h1m.flags & H1_MF_CHNK)
5532 flags |= HTX_SL_F_CHNK;
5533 else if (h1m.flags & H1_MF_CLEN)
5534 flags |= HTX_SL_F_CLEN;
5535 if (h1m.body_len == 0)
5536 flags |= HTX_SL_F_BODYLESS;
5537 }
5538 sl->flags |= flags;
5539
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005540 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005541 * and the status code implies the presence of a message body, we must
5542 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005543 * for the keepalive compliance. If the applet announces a transfer-encoding
5544 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005545 */
5546 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005547 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005548 /* Add a new header */
5549 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5550 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5551 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005552 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005553 WILL_LJMP(lua_error(L));
5554 }
5555 }
5556
5557 /* Finalize headers. */
5558 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5559 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005560 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005561 WILL_LJMP(lua_error(L));
5562 }
5563
5564 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5565 b_reset(&res->buf);
5566 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5567 WILL_LJMP(lua_error(L));
5568 }
5569
5570 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005571 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005572
5573 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005574 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005575 return 0;
5576
5577}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005578/* We will build the status line and the headers of the HTTP response.
5579 * We will try send at once if its not possible, we give back the hand
5580 * waiting for more room.
5581 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005582__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005583{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005584 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005585 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005586 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005587
5588 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005589 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005590 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005591 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005592 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005593}
5594
5595
Christopher Fauleta2097962019-07-15 16:25:33 +02005596__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005597{
Christopher Fauleta2097962019-07-15 16:25:33 +02005598 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005599}
5600
Christopher Fauleta2097962019-07-15 16:25:33 +02005601/*
5602 *
5603 *
5604 * Class HTTP
5605 *
5606 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005607 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005608
5609/* Returns a struct hlua_txn if the stack entry "ud" is
5610 * a class stream, otherwise it throws an error.
5611 */
5612__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005613{
Christopher Fauleta2097962019-07-15 16:25:33 +02005614 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5615}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005616
Christopher Fauleta2097962019-07-15 16:25:33 +02005617/* This function creates and push in the stack a HTTP object
5618 * according with a current TXN.
5619 */
5620static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5621{
5622 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005623
Christopher Fauleta2097962019-07-15 16:25:33 +02005624 /* Check stack size. */
5625 if (!lua_checkstack(L, 3))
5626 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627
Christopher Fauleta2097962019-07-15 16:25:33 +02005628 /* Create the object: obj[0] = userdata.
5629 * Note that the base of the Converters object is the
5630 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005631 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005632 lua_newtable(L);
5633 htxn = lua_newuserdata(L, sizeof(*htxn));
5634 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005635
5636 htxn->s = txn->s;
5637 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005638 htxn->dir = txn->dir;
5639 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005640
5641 /* Pop a class stream metatable and affect it to the table. */
5642 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5643 lua_setmetatable(L, -2);
5644
5645 return 1;
5646}
5647
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005648/* This function creates and returns an array containing the status-line
5649 * elements. This function does not fails.
5650 */
5651__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5652{
5653 /* Create the table. */
5654 lua_newtable(L);
5655
5656 if (sl->flags & HTX_SL_F_IS_RESP) {
5657 lua_pushstring(L, "version");
5658 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5659 lua_settable(L, -3);
5660 lua_pushstring(L, "code");
5661 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5662 lua_settable(L, -3);
5663 lua_pushstring(L, "reason");
5664 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5665 lua_settable(L, -3);
5666 }
5667 else {
5668 lua_pushstring(L, "method");
5669 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5670 lua_settable(L, -3);
5671 lua_pushstring(L, "uri");
5672 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5673 lua_settable(L, -3);
5674 lua_pushstring(L, "version");
5675 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5676 lua_settable(L, -3);
5677 }
5678 return 1;
5679}
5680
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005681/* This function creates ans returns an array of HTTP headers.
5682 * This function does not fails. It is used as wrapper with the
5683 * 2 following functions.
5684 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005685__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005686{
Christopher Fauleta2097962019-07-15 16:25:33 +02005687 struct htx *htx;
5688 int32_t pos;
5689
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005690 /* Create the table. */
5691 lua_newtable(L);
5692
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005693
Christopher Fauleta2097962019-07-15 16:25:33 +02005694 htx = htxbuf(&msg->chn->buf);
5695 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5696 struct htx_blk *blk = htx_get_blk(htx, pos);
5697 enum htx_blk_type type = htx_get_blk_type(blk);
5698 struct ist n, v;
5699 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005700
Christopher Fauleta2097962019-07-15 16:25:33 +02005701 if (type == HTX_BLK_HDR) {
5702 n = htx_get_blk_name(htx,blk);
5703 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005704 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005705 else if (type == HTX_BLK_EOH)
5706 break;
5707 else
5708 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005709
Christopher Fauleta2097962019-07-15 16:25:33 +02005710 /* Check for existing entry:
5711 * assume that the table is on the top of the stack, and
5712 * push the key in the stack, the function lua_gettable()
5713 * perform the lookup.
5714 */
5715 lua_pushlstring(L, n.ptr, n.len);
5716 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005717
Christopher Fauleta2097962019-07-15 16:25:33 +02005718 switch (lua_type(L, -1)) {
5719 case LUA_TNIL:
5720 /* Table not found, create it. */
5721 lua_pop(L, 1); /* remove the nil value. */
5722 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5723 lua_newtable(L); /* create and push empty table. */
5724 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5725 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5726 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005727 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005728
Christopher Fauleta2097962019-07-15 16:25:33 +02005729 case LUA_TTABLE:
5730 /* Entry found: push the value in the table. */
5731 len = lua_rawlen(L, -1);
5732 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5733 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5734 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5735 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005736
Christopher Fauleta2097962019-07-15 16:25:33 +02005737 default:
5738 /* Other cases are errors. */
5739 hlua_pusherror(L, "internal error during the parsing of headers.");
5740 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005741 }
5742 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005743 return 1;
5744}
5745
5746__LJMP static int hlua_http_req_get_headers(lua_State *L)
5747{
5748 struct hlua_txn *htxn;
5749
5750 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5751 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5752
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005753 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005754 WILL_LJMP(lua_error(L));
5755
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005756 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005757}
5758
5759__LJMP static int hlua_http_res_get_headers(lua_State *L)
5760{
5761 struct hlua_txn *htxn;
5762
5763 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5764 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5765
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005766 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005767 WILL_LJMP(lua_error(L));
5768
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005769 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005770}
5771
5772/* This function replace full header, or just a value in
5773 * the request or in the response. It is a wrapper fir the
5774 * 4 following functions.
5775 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005776__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005777{
5778 size_t name_len;
5779 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5780 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5781 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005782 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005783 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005784
Dragan Dosen26743032019-04-30 15:54:36 +02005785 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005786 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5787
Christopher Fauleta2097962019-07-15 16:25:33 +02005788 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005789 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005790 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005791 return 0;
5792}
5793
5794__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5795{
5796 struct hlua_txn *htxn;
5797
5798 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5799 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5800
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005801 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005802 WILL_LJMP(lua_error(L));
5803
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005804 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005805}
5806
5807__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5808{
5809 struct hlua_txn *htxn;
5810
5811 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5812 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5813
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005814 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005815 WILL_LJMP(lua_error(L));
5816
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005817 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005818}
5819
5820__LJMP static int hlua_http_req_rep_val(lua_State *L)
5821{
5822 struct hlua_txn *htxn;
5823
5824 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5825 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5826
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005827 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005828 WILL_LJMP(lua_error(L));
5829
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005830 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005831}
5832
5833__LJMP static int hlua_http_res_rep_val(lua_State *L)
5834{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005835 struct hlua_txn *htxn;
5836
5837 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5838 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5839
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005840 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005841 WILL_LJMP(lua_error(L));
5842
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005843 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005844}
5845
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005846/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005847 * It is a wrapper for the 2 following functions.
5848 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005849__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005850{
5851 size_t len;
5852 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005853 struct htx *htx = htxbuf(&msg->chn->buf);
5854 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005855
Christopher Fauleta2097962019-07-15 16:25:33 +02005856 ctx.blk = NULL;
5857 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5858 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005859 return 0;
5860}
5861
5862__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5863{
5864 struct hlua_txn *htxn;
5865
5866 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5867 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5868
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005869 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005870 WILL_LJMP(lua_error(L));
5871
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005872 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005873}
5874
5875__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5876{
5877 struct hlua_txn *htxn;
5878
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005879 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005880 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5881
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005882 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005883 WILL_LJMP(lua_error(L));
5884
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005885 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005886}
5887
5888/* This function adds an header. It is a wrapper used by
5889 * the 2 following functions.
5890 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005891__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005892{
5893 size_t name_len;
5894 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5895 size_t value_len;
5896 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005897 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005898
Christopher Fauleta2097962019-07-15 16:25:33 +02005899 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5900 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005901 return 0;
5902}
5903
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005904__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5905{
5906 struct hlua_txn *htxn;
5907
5908 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5909 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5910
5911 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5912 WILL_LJMP(lua_error(L));
5913
5914 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5915}
5916
5917__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5918{
5919 struct hlua_txn *htxn;
5920
5921 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5922 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5923
5924 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5925 WILL_LJMP(lua_error(L));
5926
5927 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5928}
5929
5930static int hlua_http_req_set_hdr(lua_State *L)
5931{
5932 struct hlua_txn *htxn;
5933
5934 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5935 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5936
5937 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5938 WILL_LJMP(lua_error(L));
5939
5940 hlua_http_del_hdr(L, &htxn->s->txn->req);
5941 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5942}
5943
5944static int hlua_http_res_set_hdr(lua_State *L)
5945{
5946 struct hlua_txn *htxn;
5947
5948 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5949 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5950
5951 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5952 WILL_LJMP(lua_error(L));
5953
5954 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5955 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5956}
5957
5958/* This function set the method. */
5959static int hlua_http_req_set_meth(lua_State *L)
5960{
5961 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5962 size_t name_len;
5963 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5964
5965 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5966 WILL_LJMP(lua_error(L));
5967
5968 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5969 return 1;
5970}
5971
5972/* This function set the method. */
5973static int hlua_http_req_set_path(lua_State *L)
5974{
5975 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5976 size_t name_len;
5977 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5978
5979 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5980 WILL_LJMP(lua_error(L));
5981
5982 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5983 return 1;
5984}
5985
5986/* This function set the query-string. */
5987static int hlua_http_req_set_query(lua_State *L)
5988{
5989 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5990 size_t name_len;
5991 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5992
5993 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5994 WILL_LJMP(lua_error(L));
5995
5996 /* Check length. */
5997 if (name_len > trash.size - 1) {
5998 lua_pushboolean(L, 0);
5999 return 1;
6000 }
6001
6002 /* Add the mark question as prefix. */
6003 chunk_reset(&trash);
6004 trash.area[trash.data++] = '?';
6005 memcpy(trash.area + trash.data, name, name_len);
6006 trash.data += name_len;
6007
6008 lua_pushboolean(L,
6009 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6010 return 1;
6011}
6012
6013/* This function set the uri. */
6014static int hlua_http_req_set_uri(lua_State *L)
6015{
6016 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6017 size_t name_len;
6018 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6019
6020 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6021 WILL_LJMP(lua_error(L));
6022
6023 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6024 return 1;
6025}
6026
6027/* This function set the response code & optionally reason. */
6028static int hlua_http_res_set_status(lua_State *L)
6029{
6030 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6031 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6032 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6033 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6034
6035 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6036 WILL_LJMP(lua_error(L));
6037
6038 http_res_set_status(code, reason, htxn->s);
6039 return 0;
6040}
6041
6042/*
6043 *
6044 *
6045 * Class HTTPMessage
6046 *
6047 *
6048 */
6049
6050/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6051 * otherwise it throws an error.
6052 */
6053__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6054{
6055 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6056}
6057
6058/* Creates and pushes on the stack a HTTP object according with a current TXN.
6059 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006060static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006061{
6062 /* Check stack size. */
6063 if (!lua_checkstack(L, 3))
6064 return 0;
6065
6066 lua_newtable(L);
6067 lua_pushlightuserdata(L, msg);
6068 lua_rawseti(L, -2, 0);
6069
6070 /* Create the "channel" field that contains the request channel object. */
6071 lua_pushstring(L, "channel");
6072 if (!hlua_channel_new(L, msg->chn))
6073 return 0;
6074 lua_rawset(L, -3);
6075
6076 /* Pop a class stream metatable and affect it to the table. */
6077 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6078 lua_setmetatable(L, -2);
6079
6080 return 1;
6081}
6082
6083/* Helper function returning a filter attached to the HTTP message at the
6084 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006085 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006086 * filled with output and input length respectively.
6087 */
6088static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6089{
6090 struct channel *chn = msg->chn;
6091 struct htx *htx = htxbuf(&chn->buf);
6092 struct filter *filter = NULL;
6093
6094 *offset = co_data(msg->chn);
6095 *len = htx->data - co_data(msg->chn);
6096
6097 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6098 filter = lua_touserdata (L, -1);
6099 if (msg->msg_state >= HTTP_MSG_DATA) {
6100 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6101
6102 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6103 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6104 }
6105 }
6106
6107 lua_pop(L, 1);
6108 return filter;
6109}
6110
6111/* Returns true if the channel attached to the HTTP message is the response
6112 * channel.
6113 */
6114__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6115{
6116 struct http_msg *msg;
6117
6118 MAY_LJMP(check_args(L, 1, "is_resp"));
6119 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6120
6121 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6122 return 1;
6123}
6124
6125/* Returns an array containing the elements status-line of the HTTP message. It relies
6126 * on hlua_http_get_stline().
6127 */
6128__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6129{
6130 struct http_msg *msg;
6131 struct htx *htx;
6132 struct htx_sl *sl;
6133
6134 MAY_LJMP(check_args(L, 1, "get_stline"));
6135 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6136
6137 if (msg->msg_state > HTTP_MSG_BODY)
6138 WILL_LJMP(lua_error(L));
6139
6140 htx = htxbuf(&msg->chn->buf);
6141 sl = http_get_stline(htx);
6142 if (!sl)
6143 return 0;
6144 return hlua_http_get_stline(L, sl);
6145}
6146
6147/* Returns an array containing all headers of the HTTP message. it relies on
6148 * hlua_http_get_headers().
6149 */
6150__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6151{
6152 struct http_msg *msg;
6153
6154 MAY_LJMP(check_args(L, 1, "get_headers"));
6155 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6156
6157 if (msg->msg_state > HTTP_MSG_BODY)
6158 WILL_LJMP(lua_error(L));
6159
6160 return hlua_http_get_headers(L, msg);
6161}
6162
6163/* Deletes all occurrences of an header in the HTTP message matching on its
6164 * name. It relies on hlua_http_del_hdr().
6165 */
6166__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6167{
6168 struct http_msg *msg;
6169
6170 MAY_LJMP(check_args(L, 2, "del_header"));
6171 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6172
6173 if (msg->msg_state > HTTP_MSG_BODY)
6174 WILL_LJMP(lua_error(L));
6175
6176 return hlua_http_del_hdr(L, msg);
6177}
6178
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006179/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006180 * message given its name against a regex and replaces it if it matches. It
6181 * relies on hlua_http_rep_hdr().
6182 */
6183__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6184{
6185 struct http_msg *msg;
6186
6187 MAY_LJMP(check_args(L, 4, "rep_header"));
6188 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6189
6190 if (msg->msg_state > HTTP_MSG_BODY)
6191 WILL_LJMP(lua_error(L));
6192
6193 return hlua_http_rep_hdr(L, msg, 1);
6194}
6195
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006196/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006197 * message given its name against a regex and replaces it if it matches. It
6198 * relies on hlua_http_rep_hdr().
6199 */
6200__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6201{
6202 struct http_msg *msg;
6203
6204 MAY_LJMP(check_args(L, 4, "rep_value"));
6205 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6206
6207 if (msg->msg_state > HTTP_MSG_BODY)
6208 WILL_LJMP(lua_error(L));
6209
6210 return hlua_http_rep_hdr(L, msg, 0);
6211}
6212
6213/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6214__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6215{
6216 struct http_msg *msg;
6217
6218 MAY_LJMP(check_args(L, 3, "add_header"));
6219 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6220
6221 if (msg->msg_state > HTTP_MSG_BODY)
6222 WILL_LJMP(lua_error(L));
6223
6224 return hlua_http_add_hdr(L, msg);
6225}
6226
6227/* Add an header in the HTTP message removing existing headers with the same
6228 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6229 */
6230__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6231{
6232 struct http_msg *msg;
6233
6234 MAY_LJMP(check_args(L, 3, "set_header"));
6235 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6236
6237 if (msg->msg_state > HTTP_MSG_BODY)
6238 WILL_LJMP(lua_error(L));
6239
6240 hlua_http_del_hdr(L, msg);
6241 return hlua_http_add_hdr(L, msg);
6242}
6243
6244/* Rewrites the request method. It relies on http_req_replace_stline(). */
6245__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6246{
6247 struct stream *s;
6248 struct http_msg *msg;
6249 const char *name;
6250 size_t name_len;
6251
6252 MAY_LJMP(check_args(L, 2, "set_method"));
6253 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6254 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6255
6256 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6257 WILL_LJMP(lua_error(L));
6258
6259 s = chn_strm(msg->chn);
6260 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6261 return 1;
6262}
6263
6264/* Rewrites the request path. It relies on http_req_replace_stline(). */
6265__LJMP static int hlua_http_msg_set_path(lua_State *L)
6266{
6267 struct stream *s;
6268 struct http_msg *msg;
6269 const char *name;
6270 size_t name_len;
6271
6272 MAY_LJMP(check_args(L, 2, "set_path"));
6273 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6274 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6275
6276 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6277 WILL_LJMP(lua_error(L));
6278
6279 s = chn_strm(msg->chn);
6280 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6281 return 1;
6282}
6283
6284/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6285__LJMP static int hlua_http_msg_set_query(lua_State *L)
6286{
6287 struct stream *s;
6288 struct http_msg *msg;
6289 const char *name;
6290 size_t name_len;
6291
6292 MAY_LJMP(check_args(L, 2, "set_query"));
6293 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6294 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6295
6296 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6297 WILL_LJMP(lua_error(L));
6298
6299 /* Check length. */
6300 if (name_len > trash.size - 1) {
6301 lua_pushboolean(L, 0);
6302 return 1;
6303 }
6304
6305 /* Add the mark question as prefix. */
6306 chunk_reset(&trash);
6307 trash.area[trash.data++] = '?';
6308 memcpy(trash.area + trash.data, name, name_len);
6309 trash.data += name_len;
6310
6311 s = chn_strm(msg->chn);
6312 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6313 return 1;
6314}
6315
6316/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6317__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6318{
6319 struct stream *s;
6320 struct http_msg *msg;
6321 const char *name;
6322 size_t name_len;
6323
6324 MAY_LJMP(check_args(L, 2, "set_uri"));
6325 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6326 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6327
6328 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6329 WILL_LJMP(lua_error(L));
6330
6331 s = chn_strm(msg->chn);
6332 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6333 return 1;
6334}
6335
6336/* Rewrites the response status code. It relies on http_res_set_status(). */
6337__LJMP static int hlua_http_msg_set_status(lua_State *L)
6338{
6339 struct http_msg *msg;
6340 unsigned int code;
6341 const char *reason;
6342 size_t reason_len;
6343
6344 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6345 code = MAY_LJMP(luaL_checkinteger(L, 2));
6346 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6347
6348 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6349 WILL_LJMP(lua_error(L));
6350
6351 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6352 return 1;
6353}
6354
6355/* Returns true if the HTTP message is full. */
6356__LJMP static int hlua_http_msg_is_full(lua_State *L)
6357{
6358 struct http_msg *msg;
6359
6360 MAY_LJMP(check_args(L, 1, "is_full"));
6361 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6362 lua_pushboolean(L, channel_full(msg->chn, 0));
6363 return 1;
6364}
6365
6366/* Returns true if the HTTP message may still receive data. */
6367__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6368{
6369 struct http_msg *msg;
6370 struct htx *htx;
6371
6372 MAY_LJMP(check_args(L, 1, "may_recv"));
6373 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6374 htx = htxbuf(&msg->chn->buf);
6375 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6376 return 1;
6377}
6378
6379/* Returns true if the HTTP message EOM was received */
6380__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6381{
6382 struct http_msg *msg;
6383 struct htx *htx;
6384
6385 MAY_LJMP(check_args(L, 1, "may_recv"));
6386 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6387 htx = htxbuf(&msg->chn->buf);
6388 lua_pushboolean(L, !htx_expect_more(htx));
6389 return 1;
6390}
6391
6392/* Returns the number of bytes available in the input side of the HTTP
6393 * message. This function never fails.
6394 */
6395__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6396{
6397 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006398 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006399
6400 MAY_LJMP(check_args(L, 1, "input"));
6401 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006402 hlua_http_msg_filter(L, 1, msg, &output, &input);
6403 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006404 return 1;
6405}
6406
6407/* Returns the number of bytes available in the output side of the HTTP
6408 * message. This function never fails.
6409 */
6410__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6411{
6412 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006413 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006414
6415 MAY_LJMP(check_args(L, 1, "output"));
6416 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006417 hlua_http_msg_filter(L, 1, msg, &output, &input);
6418 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006419 return 1;
6420}
6421
6422/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6423 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006424 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006425 * block. This function is called during the payload filtering, so the headers
6426 * are already scheduled for output (from the filter point of view).
6427 */
6428static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6429{
6430 struct htx *htx = htxbuf(&msg->chn->buf);
6431 struct htx_blk *blk;
6432 struct htx_ret htxret;
6433 luaL_Buffer b;
6434 int ret = 0;
6435
6436 luaL_buffinit(L, &b);
6437 htxret = htx_find_offset(htx, offset);
6438 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6439 enum htx_blk_type type = htx_get_blk_type(blk);
6440 struct ist v;
6441
6442 switch (type) {
6443 case HTX_BLK_UNUSED:
6444 break;
6445
6446 case HTX_BLK_DATA:
6447 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006448 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006449 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006450
6451 luaL_addlstring(&b, v.ptr, v.len);
6452 ret += v.len;
6453 break;
6454
6455 default:
vishnu0af4bd72021-10-24 06:46:24 +05306456 if (!ret)
6457 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006458 goto end;
6459 }
6460 offset = 0;
6461 }
6462
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006463end:
vishnu0af4bd72021-10-24 06:46:24 +05306464 if (!ret && (htx->flags & HTX_FL_EOM))
6465 goto no_data;
6466 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006467 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306468
6469 no_data:
6470 /* Remove the empty string and push nil on the stack */
6471 lua_pop(L, 1);
6472 lua_pushnil(L);
6473 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006474}
6475
6476/* Copies the string <str> to the HTTP message <msg> at the offset
6477 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006478 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006479 * the filter context.
6480 */
6481static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6482{
6483 struct htx *htx = htx_from_buf(&msg->chn->buf);
6484 struct htx_ret htxret;
6485 int /*max, */ret = 0;
6486
6487 /* Nothing to do, just return */
6488 if (unlikely(istlen(str) == 0))
6489 goto end;
6490
6491 if (istlen(str) > htx_free_data_space(htx)) {
6492 ret = -1;
6493 goto end;
6494 }
6495
6496 htxret = htx_find_offset(htx, offset);
6497 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6498 if (!htx_add_last_data(htx, str))
6499 goto end;
6500 }
6501 else {
6502 struct ist v = htx_get_blk_value(htx, htxret.blk);
6503 v.ptr += htxret.ret;
6504 v.len = 0;
6505 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6506 goto end;
6507 }
6508 ret = str.len;
6509 if (ret) {
6510 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6511 flt_update_offsets(filter, msg->chn, ret);
6512 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6513 }
6514
6515 end:
6516 htx_to_buf(htx, &msg->chn->buf);
6517 return ret;
6518}
6519
6520/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6521 * position <offset>. It stops on the first non-DATA HTX block. This function is
6522 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006523 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006524 * update the filter context.
6525 */
6526static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6527{
6528 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6529 struct htx *htx = htx_from_buf(&msg->chn->buf);
6530 struct htx_blk *blk;
6531 struct htx_ret htxret;
6532 size_t ret = 0;
6533
6534 /* Be sure <len> is always the amount of DATA to remove */
6535 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006536 /* When htx tail type == HTX_BLK_DATA, no need to take care
6537 * of special blocks like HTX_BLK_EOT.
6538 * We simply truncate after offset
6539 * (truncate targeted blk and discard the following ones)
6540 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006541 htx_truncate(htx, offset);
6542 ret = len;
6543 goto end;
6544 }
6545
6546 htxret = htx_find_offset(htx, offset);
6547 blk = htxret.blk;
6548 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006549 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006550 struct ist v;
6551
6552 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6553 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006554
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006555 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006556 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006557
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006558 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006559 /* trimming data in blk: discard everything after the offset
6560 * (replace 'v' with 'IST_NULL')
6561 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006562 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006563 if (blk && v.len < len) {
6564 /* In this case, caller wants to keep removing data,
6565 * but we need to spare current blk
6566 * because it was already trimmed
6567 */
6568 blk = htx_get_next_blk(htx, blk);
6569 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006570 len -= v.len;
6571 ret += v.len;
6572 }
6573
6574
6575 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006576 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006577 enum htx_blk_type type = htx_get_blk_type(blk);
6578 uint32_t sz = htx_get_blksz(blk);
6579
6580 switch (type) {
6581 case HTX_BLK_UNUSED:
6582 break;
6583
6584 case HTX_BLK_DATA:
6585 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006586 /* don't discard whole blk, only part of it
6587 * (from the beginning)
6588 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006589 htx_cut_data_blk(htx, blk, len);
6590 ret += len;
6591 goto end;
6592 }
6593 break;
6594
6595 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006596 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006597 goto end;
6598 }
6599
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006600 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006601 len -= sz;
6602 ret += sz;
6603 blk = htx_remove_blk(htx, blk);
6604 }
6605
6606end:
6607 flt_update_offsets(filter, msg->chn, -ret);
6608 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6609 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6610 * to loose the EOM flag if the message is empty.
6611 */
6612}
6613
6614/* Copies input data found in an HTTP message. Unlike the channel function used
6615 * to duplicate raw data, this one can only be called inside a filter, from
6616 * http_payload callback. So it cannot yield. An exception is returned if it is
6617 * called from another callback. If nothing was copied, a nil value is pushed on
6618 * the stack.
6619 */
6620__LJMP static int hlua_http_msg_get_body(lua_State *L)
6621{
6622 struct http_msg *msg;
6623 struct filter *filter;
6624 size_t output, input;
6625 int offset, len;
6626
6627 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6628 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6629 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6630
6631 if (msg->msg_state < HTTP_MSG_DATA)
6632 WILL_LJMP(lua_error(L));
6633
6634 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6635 if (!filter || !hlua_filter_from_payload(filter))
6636 WILL_LJMP(lua_error(L));
6637
6638 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6639 lua_pushnil(L);
6640 return 1;
6641 }
6642
6643 offset = output;
6644 if (lua_gettop(L) > 1) {
6645 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6646 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006647 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 offset += output;
6649 if (offset < output || offset > input + output) {
6650 lua_pushfstring(L, "offset out of range.");
6651 WILL_LJMP(lua_error(L));
6652 }
6653 }
6654 len = output + input - offset;
6655 if (lua_gettop(L) == 3) {
6656 len = MAY_LJMP(luaL_checkinteger(L, 3));
6657 if (!len)
6658 goto dup;
6659 if (len == -1)
6660 len = global.tune.bufsize;
6661 if (len < 0) {
6662 lua_pushfstring(L, "length out of range.");
6663 WILL_LJMP(lua_error(L));
6664 }
6665 }
6666
6667 dup:
6668 _hlua_http_msg_dup(msg, L, offset, len);
6669 return 1;
6670}
6671
6672/* Appends a string to the HTTP message, after all existing DATA blocks but
6673 * before the trailers, if any. It returns the amount of data written or -1 if
6674 * nothing was copied. Unlike the channel function used to append data, this one
6675 * can only be called inside a filter, from http_payload callback. So it cannot
6676 * yield. An exception is returned if it is called from another callback.
6677 */
6678__LJMP static int hlua_http_msg_append(lua_State *L)
6679{
6680 struct http_msg *msg;
6681 struct filter *filter;
6682 const char *str;
6683 size_t offset, len, sz;
6684 int ret;
6685
6686 MAY_LJMP(check_args(L, 2, "append"));
6687 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6688
6689 if (msg->msg_state < HTTP_MSG_DATA)
6690 WILL_LJMP(lua_error(L));
6691
6692 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6693 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6694 if (!filter || !hlua_filter_from_payload(filter))
6695 WILL_LJMP(lua_error(L));
6696
6697 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6698 lua_pushinteger(L, ret);
6699 return 1;
6700}
6701
6702/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6703 * returns the amount of data written or -1 if nothing was copied. Unlike the
6704 * channel function used to prepend data, this one can only be called inside a
6705 * filter, from http_payload callback. So it cannot yield. An exception is
6706 * returned if it is called from another callback.
6707 */
6708__LJMP static int hlua_http_msg_prepend(lua_State *L)
6709{
6710 struct http_msg *msg;
6711 struct filter *filter;
6712 const char *str;
6713 size_t offset, len, sz;
6714 int ret;
6715
6716 MAY_LJMP(check_args(L, 2, "prepend"));
6717 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006718
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006719 if (msg->msg_state < HTTP_MSG_DATA)
6720 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006721
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006722 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6723 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6724 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006725 WILL_LJMP(lua_error(L));
6726
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006727 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6728 lua_pushinteger(L, ret);
6729 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006730}
6731
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006732/* Inserts a string to the HTTP message at a given offset. By default the string
6733 * is appended at the end of DATA blocks. It returns the amount of data written
6734 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6735 * this one can only be called inside a filter, from http_payload callback. So
6736 * it cannot yield. An exception is returned if it is called from another
6737 * callback.
6738 */
6739__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006740{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006741 struct http_msg *msg;
6742 struct filter *filter;
6743 const char *str;
6744 size_t input, output, sz;
6745 int offset;
6746 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006747
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006748 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6749 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006750 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006751
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006752 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006753 WILL_LJMP(lua_error(L));
6754
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006755 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006756 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006757 if (!filter || !hlua_filter_from_payload(filter))
6758 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006759
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006760 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006761 if (lua_gettop(L) > 2) {
6762 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6763 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006764 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006765 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006766 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006767 lua_pushfstring(L, "offset out of range.");
6768 WILL_LJMP(lua_error(L));
6769 }
6770 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006771
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006772 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6773 lua_pushinteger(L, ret);
6774 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006775}
6776
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006777/* Removes a given amount of data from the HTTP message at a given offset. By
6778 * default all DATA blocks are removed. It returns the amount of data
6779 * removed. Unlike the channel function used to remove data, this one can only
6780 * be called inside a filter, from http_payload callback. So it cannot yield. An
6781 * exception is returned if it is called from another callback.
6782 */
6783__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006784{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006785 struct http_msg *msg;
6786 struct filter *filter;
6787 size_t input, output;
6788 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006789
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006790 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006791 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006792 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006793
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006794 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006795 WILL_LJMP(lua_error(L));
6796
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006797 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006798 if (!filter || !hlua_filter_from_payload(filter))
6799 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006800
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006801 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006802 if (lua_gettop(L) > 1) {
6803 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006804 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006805 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006806 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006807 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006808 lua_pushfstring(L, "offset out of range.");
6809 WILL_LJMP(lua_error(L));
6810 }
6811 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006812
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006813 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006814 if (lua_gettop(L) == 3) {
6815 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006816 if (!len)
6817 goto end;
6818 if (len == -1)
6819 len = output + input - offset;
6820 if (len < 0 || offset + len > output + input) {
6821 lua_pushfstring(L, "length out of range.");
6822 WILL_LJMP(lua_error(L));
6823 }
6824 }
6825
6826 _hlua_http_msg_delete(msg, filter, offset, len);
6827
6828 end:
6829 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006830 return 1;
6831}
6832
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006833/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006834 * all remaining data are removed, accordingly to the filter context. It returns
6835 * the amount of data written or -1 if nothing was copied. Unlike the channel
6836 * function used to replace data, this one can only be called inside a filter,
6837 * from http_payload callback. So it cannot yield. An exception is returned if
6838 * it is called from another callback.
6839 */
6840__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006841{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006842 struct http_msg *msg;
6843 struct filter *filter;
6844 struct htx *htx;
6845 const char *str;
6846 size_t input, output, sz;
6847 int offset, len;
6848 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006849
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006850 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6851 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6852 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6853
6854 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006855 WILL_LJMP(lua_error(L));
6856
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006857 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6858 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6859 if (!filter || !hlua_filter_from_payload(filter))
6860 WILL_LJMP(lua_error(L));
6861
6862 offset = output;
6863 if (lua_gettop(L) > 2) {
6864 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6865 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006866 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006867 offset += output;
6868 if (offset < output || offset > input + output) {
6869 lua_pushfstring(L, "offset out of range.");
6870 WILL_LJMP(lua_error(L));
6871 }
6872 }
6873
6874 len = output + input - offset;
6875 if (lua_gettop(L) == 4) {
6876 len = MAY_LJMP(luaL_checkinteger(L, 4));
6877 if (!len)
6878 goto set;
6879 if (len == -1)
6880 len = output + input - offset;
6881 if (len < 0 || offset + len > output + input) {
6882 lua_pushfstring(L, "length out of range.");
6883 WILL_LJMP(lua_error(L));
6884 }
6885 }
6886
6887 set:
6888 /* Be sure we can copied the string once input data will be removed. */
6889 htx = htx_from_buf(&msg->chn->buf);
6890 if (sz > htx_free_data_space(htx) + len)
6891 lua_pushinteger(L, -1);
6892 else {
6893 _hlua_http_msg_delete(msg, filter, offset, len);
6894 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6895 lua_pushinteger(L, ret);
6896 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006897 return 1;
6898}
6899
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006900/* Prepends data into an HTTP message and forward it, from the filter point of
6901 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6902 * the channel function used to send data, this one can only be called inside a
6903 * filter, from http_payload callback. So it cannot yield. An exception is
6904 * returned if it is called from another callback.
6905 */
6906__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006907{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006908 struct http_msg *msg;
6909 struct filter *filter;
6910 struct htx *htx;
6911 const char *str;
6912 size_t offset, len, sz;
6913 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006914
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006915 MAY_LJMP(check_args(L, 2, "send"));
6916 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6917
6918 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006919 WILL_LJMP(lua_error(L));
6920
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006921 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6922 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6923 if (!filter || !hlua_filter_from_payload(filter))
6924 WILL_LJMP(lua_error(L));
6925
6926 /* Return an error if the channel's output is closed */
6927 if (unlikely(channel_output_closed(msg->chn))) {
6928 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006929 return 1;
6930 }
6931
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006932 htx = htx_from_buf(&msg->chn->buf);
6933 if (sz > htx_free_data_space(htx)) {
6934 lua_pushinteger(L, -1);
6935 return 1;
6936 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006937
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006938 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6939 if (ret > 0) {
6940 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6941
6942 FLT_OFF(filter, msg->chn) += ret;
6943 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6944 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6945 }
6946
6947 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006948 return 1;
6949}
6950
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006951/* Forwards a given amount of bytes. It return -1 if the channel's output is
6952 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6953 * channel function used to forward data, this one can only be called inside a
6954 * filter, from http_payload callback. So it cannot yield. An exception is
6955 * returned if it is called from another callback. All other functions deal with
6956 * DATA block, this one not.
6957*/
6958__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006959{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006960 struct http_msg *msg;
6961 struct filter *filter;
6962 size_t offset, len;
6963 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006964
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006965 MAY_LJMP(check_args(L, 2, "forward"));
6966 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6967
6968 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006969 WILL_LJMP(lua_error(L));
6970
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006971 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6972 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6973 if (!filter || !hlua_filter_from_payload(filter))
6974 WILL_LJMP(lua_error(L));
6975
6976 /* Nothing to do, just return */
6977 if (!fwd)
6978 goto end;
6979
6980 /* Return an error if the channel's output is closed */
6981 if (unlikely(channel_output_closed(msg->chn))) {
6982 ret = -1;
6983 goto end;
6984 }
6985
6986 ret = fwd;
6987 if (ret > len)
6988 ret = len;
6989
6990 if (ret) {
6991 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6992
6993 FLT_OFF(filter, msg->chn) += ret;
6994 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6995 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6996 }
6997
6998 end:
6999 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007000 return 1;
7001}
7002
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007003/* Set EOM flag on the HTX message.
7004 *
7005 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7006 * really know how to do without this feature.
7007 */
7008__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007009{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007010 struct http_msg *msg;
7011 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007012
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007013 MAY_LJMP(check_args(L, 1, "set_eom"));
7014 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7015 htx = htxbuf(&msg->chn->buf);
7016 htx->flags |= HTX_FL_EOM;
7017 return 0;
7018}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007019
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007020/* Unset EOM flag on the HTX message.
7021 *
7022 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7023 * really know how to do without this feature.
7024 */
7025__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7026{
7027 struct http_msg *msg;
7028 struct htx *htx;
7029
7030 MAY_LJMP(check_args(L, 1, "set_eom"));
7031 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7032 htx = htxbuf(&msg->chn->buf);
7033 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007034 return 0;
7035}
7036
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007037/*
7038 *
7039 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007040 * Class HTTPClient
7041 *
7042 *
7043 */
7044__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7045{
7046 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7047}
7048
William Lallemandf77f1de2021-09-28 19:10:38 +02007049
7050/* stops the httpclient and ask it to kill itself */
7051__LJMP static int hlua_httpclient_gc(lua_State *L)
7052{
7053 struct hlua_httpclient *hlua_hc;
7054
7055 MAY_LJMP(check_args(L, 1, "__gc"));
7056
7057 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7058
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007059 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7060 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007061 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007062 hlua_hc->hc = NULL;
7063 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007064
7065 return 0;
7066}
7067
7068
William Lallemand3956c4e2021-09-21 16:25:15 +02007069__LJMP static int hlua_httpclient_new(lua_State *L)
7070{
7071 struct hlua_httpclient *hlua_hc;
7072 struct hlua *hlua;
7073
7074 /* Get hlua struct, or NULL if we execute from main lua state */
7075 hlua = hlua_gethlua(L);
7076 if (!hlua)
7077 return 0;
7078
7079 /* Check stack size. */
7080 if (!lua_checkstack(L, 3)) {
7081 hlua_pusherror(L, "httpclient: full stack");
7082 goto err;
7083 }
7084 /* Create the object: obj[0] = userdata. */
7085 lua_newtable(L);
7086 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7087 lua_rawseti(L, -2, 0);
7088 memset(hlua_hc, 0, sizeof(*hlua_hc));
7089
7090 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7091 if (!hlua_hc->hc)
7092 goto err;
7093
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007094 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007095
William Lallemand3956c4e2021-09-21 16:25:15 +02007096 /* Pop a class stream metatable and affect it to the userdata. */
7097 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7098 lua_setmetatable(L, -2);
7099
7100 return 1;
7101
7102 err:
7103 WILL_LJMP(lua_error(L));
7104 return 0;
7105}
7106
7107
7108/*
7109 * Callback of the httpclient, this callback wakes the lua task up, once the
7110 * httpclient receives some data
7111 *
7112 */
7113
William Lallemandbd5739e2021-10-28 15:41:38 +02007114static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007115{
7116 struct hlua *hlua = hc->caller;
7117
7118 if (!hlua || !hlua->task)
7119 return;
7120
7121 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7122}
7123
7124/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007125 * Fill the lua stack with headers from the httpclient response
7126 * This works the same way as the hlua_http_get_headers() function
7127 */
7128__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7129{
7130 struct http_hdr *hdr;
7131
7132 lua_newtable(L);
7133
William Lallemandef574b22021-10-05 16:19:31 +02007134 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007135 struct ist n, v;
7136 int len;
7137
7138 n = hdr->n;
7139 v = hdr->v;
7140
7141 /* Check for existing entry:
7142 * assume that the table is on the top of the stack, and
7143 * push the key in the stack, the function lua_gettable()
7144 * perform the lookup.
7145 */
7146
7147 lua_pushlstring(L, n.ptr, n.len);
7148 lua_gettable(L, -2);
7149
7150 switch (lua_type(L, -1)) {
7151 case LUA_TNIL:
7152 /* Table not found, create it. */
7153 lua_pop(L, 1); /* remove the nil value. */
7154 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7155 lua_newtable(L); /* create and push empty table. */
7156 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7157 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7158 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7159 break;
7160
7161 case LUA_TTABLE:
7162 /* Entry found: push the value in the table. */
7163 len = lua_rawlen(L, -1);
7164 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7165 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7166 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7167 break;
7168
7169 default:
7170 /* Other cases are errors. */
7171 hlua_pusherror(L, "internal error during the parsing of headers.");
7172 WILL_LJMP(lua_error(L));
7173 }
7174 }
7175 return 1;
7176}
7177
7178/*
William Lallemand746e6f32021-10-06 10:57:44 +02007179 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7180 *
7181 * Caller must free the result
7182 */
7183struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7184{
7185 struct http_hdr hdrs[global.tune.max_http_hdr];
7186 struct http_hdr *result = NULL;
7187 uint32_t hdr_num = 0;
7188
7189 lua_pushnil(L);
7190 while (lua_next(L, -2) != 0) {
7191 struct ist name, value;
7192 const char *n, *v;
7193 size_t nlen, vlen;
7194
7195 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7196 /* Skip element if the key is not a string or if the value is not a table */
7197 goto next_hdr;
7198 }
7199
7200 n = lua_tolstring(L, -2, &nlen);
7201 name = ist2(n, nlen);
7202
7203 /* Loop on header's values */
7204 lua_pushnil(L);
7205 while (lua_next(L, -2)) {
7206 if (!lua_isstring(L, -1)) {
7207 /* Skip the value if it is not a string */
7208 goto next_value;
7209 }
7210
7211 v = lua_tolstring(L, -1, &vlen);
7212 value = ist2(v, vlen);
7213 name = ist2(n, nlen);
7214
7215 hdrs[hdr_num].n = istdup(name);
7216 hdrs[hdr_num].v = istdup(value);
7217
7218 hdr_num++;
7219
7220 next_value:
7221 lua_pop(L, 1);
7222 }
7223
7224 next_hdr:
7225 lua_pop(L, 1);
7226
7227 }
7228
7229 if (hdr_num) {
7230 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007231 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007232 if (!result)
7233 goto skip_headers;
7234 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7235
7236 result[hdr_num].n = IST_NULL;
7237 result[hdr_num].v = IST_NULL;
7238 }
7239
7240skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007241
7242 return result;
7243}
7244
7245
William Lallemandbd5739e2021-10-28 15:41:38 +02007246/*
7247 * For each yield, checks if there is some data in the httpclient and push them
7248 * in the lua buffer, once the httpclient finished its job, push the result on
7249 * the stack
7250 */
7251__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7252{
7253 struct buffer *tr;
7254 int res;
7255 struct hlua *hlua = hlua_gethlua(L);
7256 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7257
7258
7259 tr = get_trash_chunk();
7260
7261 res = httpclient_res_xfer(hlua_hc->hc, tr);
7262 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7263
7264 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7265
7266 luaL_pushresult(&hlua_hc->b);
7267 lua_settable(L, -3);
7268
7269 lua_pushstring(L, "status");
7270 lua_pushinteger(L, hlua_hc->hc->res.status);
7271 lua_settable(L, -3);
7272
7273
7274 lua_pushstring(L, "reason");
7275 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7276 lua_settable(L, -3);
7277
7278 lua_pushstring(L, "headers");
7279 hlua_httpclient_get_headers(L, hlua_hc);
7280 lua_settable(L, -3);
7281
7282 return 1;
7283 }
7284
7285 if (httpclient_data(hlua_hc->hc))
7286 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7287
7288 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7289
7290 return 0;
7291}
7292
7293/*
7294 * Call this when trying to stream a body during a request
7295 */
7296__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7297{
7298 struct hlua *hlua;
7299 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7300 const char *body_str = NULL;
7301 int ret;
7302 int end = 0;
7303 size_t buf_len;
7304 size_t to_send = 0;
7305
7306 hlua = hlua_gethlua(L);
7307
7308 if (!hlua || !hlua->task)
7309 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7310 "'frontend', 'backend' or 'task'"));
7311
7312 ret = lua_getfield(L, -1, "body");
7313 if (ret != LUA_TSTRING)
7314 goto rcv;
7315
7316 body_str = lua_tolstring(L, -1, &buf_len);
7317 lua_pop(L, 1);
7318
Christopher Fauletfc591292022-01-12 14:46:03 +01007319 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007320
7321 if ((hlua_hc->sent + to_send) >= buf_len)
7322 end = 1;
7323
7324 /* the end flag is always set since we are using the whole remaining size */
7325 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7326
7327 if (buf_len > hlua_hc->sent) {
7328 /* still need to process the buffer */
7329 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7330 } else {
7331 goto rcv;
7332 /* we sent the whole request buffer we can recv */
7333 }
7334 return 0;
7335
7336rcv:
7337
7338 /* we return a "res" object */
7339 lua_newtable(L);
7340
William Lallemandbd5739e2021-10-28 15:41:38 +02007341 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007342 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007343
William Lallemand933fe392021-11-04 09:45:58 +01007344 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007345 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7346
7347 return 1;
7348}
William Lallemand746e6f32021-10-06 10:57:44 +02007349
William Lallemand3956c4e2021-09-21 16:25:15 +02007350/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007351 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007352 */
7353
William Lallemanddc2cc902021-10-26 11:43:26 +02007354__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007355{
7356 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007357 struct http_hdr *hdrs = NULL;
7358 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007359 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007360 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007361 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007362 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007363 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007364
7365 hlua = hlua_gethlua(L);
7366
7367 if (!hlua || !hlua->task)
7368 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7369 "'frontend', 'backend' or 'task'"));
7370
William Lallemand746e6f32021-10-06 10:57:44 +02007371 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7372 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7373
William Lallemand4f4f2b72022-02-17 20:00:23 +01007374 hlua_hc = hlua_checkhttpclient(L, 1);
7375
William Lallemand7177a952022-03-03 15:33:12 +01007376 lua_pushnil(L); /* first key */
7377 while (lua_next(L, 2)) {
7378 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7379 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7380 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007381
William Lallemand7177a952022-03-03 15:33:12 +01007382 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7383 if (lua_type(L, -1) != LUA_TSTRING)
7384 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7385 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007386
William Lallemand7177a952022-03-03 15:33:12 +01007387 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7388 if (lua_type(L, -1) != LUA_TNUMBER)
7389 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7390 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007391
William Lallemand7177a952022-03-03 15:33:12 +01007392 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7393 if (lua_type(L, -1) != LUA_TTABLE)
7394 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7395 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007396
William Lallemand7177a952022-03-03 15:33:12 +01007397 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7398 if (lua_type(L, -1) != LUA_TSTRING)
7399 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7400 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007401
William Lallemand7177a952022-03-03 15:33:12 +01007402 } else {
7403 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7404 }
7405 /* removes 'value'; keeps 'key' for next iteration */
7406 lua_pop(L, 1);
7407 }
William Lallemanddec25c32021-10-25 19:48:37 +02007408
William Lallemand746e6f32021-10-06 10:57:44 +02007409 if (!url_str) {
7410 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7411 return 0;
7412 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007413
William Lallemand10a37362022-03-02 16:18:26 +01007414 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007415
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007416 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007417 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007418 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007419
7420 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007421 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7422 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7423 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007424 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007425
William Lallemandbd5739e2021-10-28 15:41:38 +02007426 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007427 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007428 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7429 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007430
William Lallemandbd5739e2021-10-28 15:41:38 +02007431 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007432
William Lallemand746e6f32021-10-06 10:57:44 +02007433 /* free the temporary headers array */
7434 hdrs_i = hdrs;
7435 while (hdrs_i && isttest(hdrs_i->n)) {
7436 istfree(&hdrs_i->n);
7437 istfree(&hdrs_i->v);
7438 hdrs_i++;
7439 }
7440 ha_free(&hdrs);
7441
7442
William Lallemand6137a9e2021-10-26 15:01:53 +02007443 if (ret != ERR_NONE) {
7444 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7445 return 0;
7446 }
7447
William Lallemandc2d3db42022-04-26 11:46:13 +02007448 if (!httpclient_start(hlua_hc->hc))
7449 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007450
William Lallemandbd5739e2021-10-28 15:41:38 +02007451 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007452
William Lallemand3956c4e2021-09-21 16:25:15 +02007453 return 0;
7454}
7455
7456/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007457 * Sends an HTTP HEAD request and wait for a response
7458 *
7459 * httpclient:head(url, headers, payload)
7460 */
7461__LJMP static int hlua_httpclient_head(lua_State *L)
7462{
7463 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7464}
7465
7466/*
7467 * Send an HTTP GET request and wait for a response
7468 *
7469 * httpclient:get(url, headers, payload)
7470 */
7471__LJMP static int hlua_httpclient_get(lua_State *L)
7472{
7473 return hlua_httpclient_send(L, HTTP_METH_GET);
7474
7475}
7476
7477/*
7478 * Sends an HTTP PUT request and wait for a response
7479 *
7480 * httpclient:put(url, headers, payload)
7481 */
7482__LJMP static int hlua_httpclient_put(lua_State *L)
7483{
7484 return hlua_httpclient_send(L, HTTP_METH_PUT);
7485}
7486
7487/*
7488 * Send an HTTP POST request and wait for a response
7489 *
7490 * httpclient:post(url, headers, payload)
7491 */
7492__LJMP static int hlua_httpclient_post(lua_State *L)
7493{
7494 return hlua_httpclient_send(L, HTTP_METH_POST);
7495}
7496
7497
7498/*
7499 * Sends an HTTP DELETE request and wait for a response
7500 *
7501 * httpclient:delete(url, headers, payload)
7502 */
7503__LJMP static int hlua_httpclient_delete(lua_State *L)
7504{
7505 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7506}
7507
7508/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007509 *
7510 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007511 * Class TXN
7512 *
7513 *
7514 */
7515
7516/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007517 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007518 */
7519__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7520{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007521 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007522}
7523
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007524__LJMP static int hlua_set_var(lua_State *L)
7525{
7526 struct hlua_txn *htxn;
7527 const char *name;
7528 size_t len;
7529 struct sample smp;
7530
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007531 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7532 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007533
7534 /* It is useles to retrieve the stream, but this function
7535 * runs only in a stream context.
7536 */
7537 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7538 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7539
7540 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007541 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007542 hlua_lua2smp(L, 3, &smp);
7543
7544 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007545 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007546
7547 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7548 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7549 else
7550 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7551
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007552 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007553}
7554
Christopher Faulet85d79c92016-11-09 16:54:56 +01007555__LJMP static int hlua_unset_var(lua_State *L)
7556{
7557 struct hlua_txn *htxn;
7558 const char *name;
7559 size_t len;
7560 struct sample smp;
7561
7562 MAY_LJMP(check_args(L, 2, "unset_var"));
7563
7564 /* It is useles to retrieve the stream, but this function
7565 * runs only in a stream context.
7566 */
7567 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7568 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7569
7570 /* Unset the variable. */
7571 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007572 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7573 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007574}
7575
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007576__LJMP static int hlua_get_var(lua_State *L)
7577{
7578 struct hlua_txn *htxn;
7579 const char *name;
7580 size_t len;
7581 struct sample smp;
7582
7583 MAY_LJMP(check_args(L, 2, "get_var"));
7584
7585 /* It is useles to retrieve the stream, but this function
7586 * runs only in a stream context.
7587 */
7588 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7589 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7590
Willy Tarreau7560dd42016-03-10 16:28:58 +01007591 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007592 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007593 lua_pushnil(L);
7594 return 1;
7595 }
7596
7597 return hlua_smp2lua(L, &smp);
7598}
7599
Willy Tarreau59551662015-03-10 14:23:13 +01007600__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007601{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007602 struct hlua *hlua;
7603
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007604 MAY_LJMP(check_args(L, 2, "set_priv"));
7605
Willy Tarreau87b09662015-04-03 00:22:06 +02007606 /* It is useles to retrieve the stream, but this function
7607 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007608 */
7609 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007610
7611 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007612 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007613 if (!hlua)
7614 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007615
7616 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007617 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007618
7619 /* Get and store new value. */
7620 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7621 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7622
7623 return 0;
7624}
7625
Willy Tarreau59551662015-03-10 14:23:13 +01007626__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007627{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007628 struct hlua *hlua;
7629
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007630 MAY_LJMP(check_args(L, 1, "get_priv"));
7631
Willy Tarreau87b09662015-04-03 00:22:06 +02007632 /* It is useles to retrieve the stream, but this function
7633 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007634 */
7635 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007636
7637 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007638 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007639 if (!hlua) {
7640 lua_pushnil(L);
7641 return 1;
7642 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007643
7644 /* Push configuration index in the stack. */
7645 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7646
7647 return 1;
7648}
7649
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007650/* Create stack entry containing a class TXN. This function
7651 * return 0 if the stack does not contains free slots,
7652 * otherwise it returns 1.
7653 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007654static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007655{
Willy Tarreaude491382015-04-06 11:04:28 +02007656 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007657
7658 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007659 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007660 return 0;
7661
7662 /* NOTE: The allocation never fails. The failure
7663 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007664 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007665 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007666 /* Create the object: obj[0] = userdata. */
7667 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007668 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007669 lua_rawseti(L, -2, 0);
7670
Willy Tarreaude491382015-04-06 11:04:28 +02007671 htxn->s = s;
7672 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007673 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007674 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007675
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007676 /* Create the "f" field that contains a list of fetches. */
7677 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007678 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007679 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007680 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007681
7682 /* Create the "sf" field that contains a list of stringsafe fetches. */
7683 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007684 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007685 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007686 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007687
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007688 /* Create the "c" field that contains a list of converters. */
7689 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007690 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007691 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007692 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007693
7694 /* Create the "sc" field that contains a list of stringsafe converters. */
7695 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007696 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007697 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007698 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007699
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007700 /* Create the "req" field that contains the request channel object. */
7701 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007702 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007703 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007704 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007705
7706 /* Create the "res" field that contains the response channel object. */
7707 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007708 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007709 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007710 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007711
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007712 /* Creates the HTTP object is the current proxy allows http. */
7713 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007714 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007715 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007716 return 0;
7717 }
7718 else
7719 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007720 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007721
Christopher Faulet78c35472020-02-26 17:14:08 +01007722 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7723 /* HTTPMessage object are created when a lua TXN is created from
7724 * a filter context only
7725 */
7726
7727 /* Creates the HTTP-Request object is the current proxy allows http. */
7728 lua_pushstring(L, "http_req");
7729 if (p->mode == PR_MODE_HTTP) {
7730 if (!hlua_http_msg_new(L, &s->txn->req))
7731 return 0;
7732 }
7733 else
7734 lua_pushnil(L);
7735 lua_rawset(L, -3);
7736
7737 /* Creates the HTTP-Response object is the current proxy allows http. */
7738 lua_pushstring(L, "http_res");
7739 if (p->mode == PR_MODE_HTTP) {
7740 if (!hlua_http_msg_new(L, &s->txn->rsp))
7741 return 0;
7742 }
7743 else
7744 lua_pushnil(L);
7745 lua_rawset(L, -3);
7746 }
7747
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007748 /* Pop a class sesison metatable and affect it to the userdata. */
7749 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7750 lua_setmetatable(L, -2);
7751
7752 return 1;
7753}
7754
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007755__LJMP static int hlua_txn_deflog(lua_State *L)
7756{
7757 const char *msg;
7758 struct hlua_txn *htxn;
7759
7760 MAY_LJMP(check_args(L, 2, "deflog"));
7761 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7762 msg = MAY_LJMP(luaL_checkstring(L, 2));
7763
7764 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7765 return 0;
7766}
7767
7768__LJMP static int hlua_txn_log(lua_State *L)
7769{
7770 int level;
7771 const char *msg;
7772 struct hlua_txn *htxn;
7773
7774 MAY_LJMP(check_args(L, 3, "log"));
7775 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7776 level = MAY_LJMP(luaL_checkinteger(L, 2));
7777 msg = MAY_LJMP(luaL_checkstring(L, 3));
7778
7779 if (level < 0 || level >= NB_LOG_LEVELS)
7780 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7781
7782 hlua_sendlog(htxn->s->be, level, msg);
7783 return 0;
7784}
7785
7786__LJMP static int hlua_txn_log_debug(lua_State *L)
7787{
7788 const char *msg;
7789 struct hlua_txn *htxn;
7790
7791 MAY_LJMP(check_args(L, 2, "Debug"));
7792 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7793 msg = MAY_LJMP(luaL_checkstring(L, 2));
7794 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7795 return 0;
7796}
7797
7798__LJMP static int hlua_txn_log_info(lua_State *L)
7799{
7800 const char *msg;
7801 struct hlua_txn *htxn;
7802
7803 MAY_LJMP(check_args(L, 2, "Info"));
7804 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7805 msg = MAY_LJMP(luaL_checkstring(L, 2));
7806 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7807 return 0;
7808}
7809
7810__LJMP static int hlua_txn_log_warning(lua_State *L)
7811{
7812 const char *msg;
7813 struct hlua_txn *htxn;
7814
7815 MAY_LJMP(check_args(L, 2, "Warning"));
7816 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7817 msg = MAY_LJMP(luaL_checkstring(L, 2));
7818 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7819 return 0;
7820}
7821
7822__LJMP static int hlua_txn_log_alert(lua_State *L)
7823{
7824 const char *msg;
7825 struct hlua_txn *htxn;
7826
7827 MAY_LJMP(check_args(L, 2, "Alert"));
7828 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7829 msg = MAY_LJMP(luaL_checkstring(L, 2));
7830 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7831 return 0;
7832}
7833
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007834__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7835{
7836 struct hlua_txn *htxn;
7837 int ll;
7838
7839 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7840 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7841 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7842
7843 if (ll < 0 || ll > 7)
7844 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7845
7846 htxn->s->logs.level = ll;
7847 return 0;
7848}
7849
7850__LJMP static int hlua_txn_set_tos(lua_State *L)
7851{
7852 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007853 int tos;
7854
7855 MAY_LJMP(check_args(L, 2, "set_tos"));
7856 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7857 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7858
Willy Tarreau1a18b542018-12-11 16:37:42 +01007859 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007860 return 0;
7861}
7862
7863__LJMP static int hlua_txn_set_mark(lua_State *L)
7864{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007865 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007866 int mark;
7867
7868 MAY_LJMP(check_args(L, 2, "set_mark"));
7869 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7870 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7871
Lukas Tribus579e3e32019-08-11 18:03:45 +02007872 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007873 return 0;
7874}
7875
Patrick Hemmer268a7072018-05-11 12:52:31 -04007876__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7877{
7878 struct hlua_txn *htxn;
7879
7880 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7881 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7882 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7883 return 0;
7884}
7885
7886__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7887{
7888 struct hlua_txn *htxn;
7889
7890 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7891 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7892 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7893 return 0;
7894}
7895
Christopher Faulet700d9e82020-01-31 12:21:52 +01007896/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007897 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007898 * message and terminate the transaction. It returns 1 on success and 0 on
7899 * error. The Reply must be on top of the stack.
7900 */
7901__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7902{
7903 struct htx *htx;
7904 struct htx_sl *sl;
7905 struct h1m h1m;
7906 const char *status, *reason, *body;
7907 size_t status_len, reason_len, body_len;
7908 int ret, code, flags;
7909
7910 code = 200;
7911 status = "200";
7912 status_len = 3;
7913 ret = lua_getfield(L, -1, "status");
7914 if (ret == LUA_TNUMBER) {
7915 code = lua_tointeger(L, -1);
7916 status = lua_tolstring(L, -1, &status_len);
7917 }
7918 lua_pop(L, 1);
7919
7920 reason = http_get_reason(code);
7921 reason_len = strlen(reason);
7922 ret = lua_getfield(L, -1, "reason");
7923 if (ret == LUA_TSTRING)
7924 reason = lua_tolstring(L, -1, &reason_len);
7925 lua_pop(L, 1);
7926
7927 body = NULL;
7928 body_len = 0;
7929 ret = lua_getfield(L, -1, "body");
7930 if (ret == LUA_TSTRING)
7931 body = lua_tolstring(L, -1, &body_len);
7932 lua_pop(L, 1);
7933
7934 /* Prepare the response before inserting the headers */
7935 h1m_init_res(&h1m);
7936 htx = htx_from_buf(&s->res.buf);
7937 channel_htx_truncate(&s->res, htx);
7938 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7939 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7940 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7941 ist2(status, status_len), ist2(reason, reason_len));
7942 }
7943 else {
7944 flags = HTX_SL_F_IS_RESP;
7945 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7946 ist2(status, status_len), ist2(reason, reason_len));
7947 }
7948 if (!sl)
7949 goto fail;
7950 sl->info.res.status = code;
7951
7952 /* Push in the stack the "headers" entry. */
7953 ret = lua_getfield(L, -1, "headers");
7954 if (ret != LUA_TTABLE)
7955 goto skip_headers;
7956
7957 lua_pushnil(L);
7958 while (lua_next(L, -2) != 0) {
7959 struct ist name, value;
7960 const char *n, *v;
7961 size_t nlen, vlen;
7962
7963 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7964 /* Skip element if the key is not a string or if the value is not a table */
7965 goto next_hdr;
7966 }
7967
7968 n = lua_tolstring(L, -2, &nlen);
7969 name = ist2(n, nlen);
7970 if (isteqi(name, ist("content-length"))) {
7971 /* Always skip content-length header. It will be added
7972 * later with the correct len
7973 */
7974 goto next_hdr;
7975 }
7976
7977 /* Loop on header's values */
7978 lua_pushnil(L);
7979 while (lua_next(L, -2)) {
7980 if (!lua_isstring(L, -1)) {
7981 /* Skip the value if it is not a string */
7982 goto next_value;
7983 }
7984
7985 v = lua_tolstring(L, -1, &vlen);
7986 value = ist2(v, vlen);
7987
7988 if (isteqi(name, ist("transfer-encoding")))
7989 h1_parse_xfer_enc_header(&h1m, value);
7990 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7991 goto fail;
7992
7993 next_value:
7994 lua_pop(L, 1);
7995 }
7996
7997 next_hdr:
7998 lua_pop(L, 1);
7999 }
8000 skip_headers:
8001 lua_pop(L, 1);
8002
8003 /* Update h1m flags: CLEN is set if CHNK is not present */
8004 if (!(h1m.flags & H1_MF_CHNK)) {
8005 const char *clen = ultoa(body_len);
8006
8007 h1m.flags |= H1_MF_CLEN;
8008 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8009 goto fail;
8010 }
8011 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8012 h1m.flags |= H1_MF_XFER_LEN;
8013
8014 /* Update HTX start-line flags */
8015 if (h1m.flags & H1_MF_XFER_ENC)
8016 flags |= HTX_SL_F_XFER_ENC;
8017 if (h1m.flags & H1_MF_XFER_LEN) {
8018 flags |= HTX_SL_F_XFER_LEN;
8019 if (h1m.flags & H1_MF_CHNK)
8020 flags |= HTX_SL_F_CHNK;
8021 else if (h1m.flags & H1_MF_CLEN)
8022 flags |= HTX_SL_F_CLEN;
8023 if (h1m.body_len == 0)
8024 flags |= HTX_SL_F_BODYLESS;
8025 }
8026 sl->flags |= flags;
8027
8028
8029 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008030 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008031 goto fail;
8032
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008033 htx->flags |= HTX_FL_EOM;
8034
Christopher Faulet700d9e82020-01-31 12:21:52 +01008035 /* Now, forward the response and terminate the transaction */
8036 s->txn->status = code;
8037 htx_to_buf(htx, &s->res.buf);
8038 if (!http_forward_proxy_resp(s, 1))
8039 goto fail;
8040
8041 return 1;
8042
8043 fail:
8044 channel_htx_truncate(&s->res, htx);
8045 return 0;
8046}
8047
8048/* Terminate a transaction if called from a lua action. For TCP streams,
8049 * processing is just aborted. Nothing is returned to the client and all
8050 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8051 * is forwarded to the client before terminating the transaction. On success,
8052 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8053 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8054 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008055 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008056__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008057{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008058 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008059 struct stream *s;
8060 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008061
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008062 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008063
Christopher Faulet700d9e82020-01-31 12:21:52 +01008064 /* If the flags NOTERM is set, we cannot terminate the session, so we
8065 * just end the execution of the current lua code. */
8066 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008067 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008068
Christopher Faulet700d9e82020-01-31 12:21:52 +01008069 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008070 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008071 struct channel *req = &s->req;
8072 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008073
Christopher Faulet700d9e82020-01-31 12:21:52 +01008074 channel_auto_read(req);
8075 channel_abort(req);
8076 channel_auto_close(req);
8077 channel_erase(req);
8078
Christopher Faulet700d9e82020-01-31 12:21:52 +01008079 channel_auto_read(res);
8080 channel_auto_close(res);
8081 channel_shutr_now(res);
8082
8083 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8084 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008085 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008086
Christopher Faulet700d9e82020-01-31 12:21:52 +01008087 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8088 /* No reply or invalid reply */
8089 s->txn->status = 0;
8090 http_reply_and_close(s, 0, NULL);
8091 }
8092 else {
8093 /* Remove extra args to have the reply on top of the stack */
8094 if (lua_gettop(L) > 2)
8095 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008096
Christopher Faulet700d9e82020-01-31 12:21:52 +01008097 if (!hlua_txn_forward_reply(L, s)) {
8098 if (!(s->flags & SF_ERR_MASK))
8099 s->flags |= SF_ERR_PRXCOND;
8100 lua_pushinteger(L, ACT_RET_ERR);
8101 WILL_LJMP(hlua_done(L));
8102 return 0; /* Never reached */
8103 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008104 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008105
Christopher Faulet700d9e82020-01-31 12:21:52 +01008106 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8107 if (htxn->dir == SMP_OPT_DIR_REQ) {
8108 /* let's log the request time */
8109 s->logs.tv_request = now;
8110 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008111 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008112 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008113
Christopher Faulet700d9e82020-01-31 12:21:52 +01008114 done:
8115 if (!(s->flags & SF_ERR_MASK))
8116 s->flags |= SF_ERR_LOCAL;
8117 if (!(s->flags & SF_FINST_MASK))
8118 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008119
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008120 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8121 lua_pushinteger(L, -1);
8122 else
8123 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008124 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008125 return 0;
8126}
8127
Christopher Faulet700d9e82020-01-31 12:21:52 +01008128/*
8129 *
8130 *
8131 * Class REPLY
8132 *
8133 *
8134 */
8135
8136/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8137 * free slots, the function fails and returns 0;
8138 */
8139static int hlua_txn_reply_new(lua_State *L)
8140{
8141 struct hlua_txn *htxn;
8142 const char *reason, *body = NULL;
8143 int ret, status;
8144
8145 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008146 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008147 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8148 WILL_LJMP(lua_error(L));
8149 }
8150
8151 /* Default value */
8152 status = 200;
8153 reason = http_get_reason(status);
8154
8155 if (lua_istable(L, 2)) {
8156 /* load status and reason from the table argument at index 2 */
8157 ret = lua_getfield(L, 2, "status");
8158 if (ret == LUA_TNIL)
8159 goto reason;
8160 else if (ret != LUA_TNUMBER) {
8161 /* invalid status: ignore the reason */
8162 goto body;
8163 }
8164 status = lua_tointeger(L, -1);
8165
8166 reason:
8167 lua_pop(L, 1); /* restore the stack: remove status */
8168 ret = lua_getfield(L, 2, "reason");
8169 if (ret == LUA_TSTRING)
8170 reason = lua_tostring(L, -1);
8171
8172 body:
8173 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8174 ret = lua_getfield(L, 2, "body");
8175 if (ret == LUA_TSTRING)
8176 body = lua_tostring(L, -1);
8177 lua_pop(L, 1); /* restore the stack: remove body */
8178 }
8179
8180 /* Create the Reply table */
8181 lua_newtable(L);
8182
8183 /* Add status element */
8184 lua_pushstring(L, "status");
8185 lua_pushinteger(L, status);
8186 lua_settable(L, -3);
8187
8188 /* Add reason element */
8189 reason = http_get_reason(status);
8190 lua_pushstring(L, "reason");
8191 lua_pushstring(L, reason);
8192 lua_settable(L, -3);
8193
8194 /* Add body element, nil if undefined */
8195 lua_pushstring(L, "body");
8196 if (body)
8197 lua_pushstring(L, body);
8198 else
8199 lua_pushnil(L);
8200 lua_settable(L, -3);
8201
8202 /* Add headers element */
8203 lua_pushstring(L, "headers");
8204 lua_newtable(L);
8205
8206 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8207 if (lua_istable(L, 2)) {
8208 /* load headers from the table argument at index 2. If it is a table, copy it. */
8209 ret = lua_getfield(L, 2, "headers");
8210 if (ret == LUA_TTABLE) {
8211 /* stack: [ ... <headers:table>, <table> ] */
8212 lua_pushnil(L);
8213 while (lua_next(L, -2) != 0) {
8214 /* stack: [ ... <headers:table>, <table>, k, v] */
8215 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8216 /* invalid value type, skip it */
8217 lua_pop(L, 1);
8218 continue;
8219 }
8220
8221
8222 /* Duplicate the key and swap it with the value. */
8223 lua_pushvalue(L, -2);
8224 lua_insert(L, -2);
8225 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8226
8227 lua_newtable(L);
8228 lua_insert(L, -2);
8229 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8230
8231 if (lua_isstring(L, -1)) {
8232 /* push the value in the inner table */
8233 lua_rawseti(L, -2, 1);
8234 }
8235 else { /* table */
8236 lua_pushnil(L);
8237 while (lua_next(L, -2) != 0) {
8238 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8239 if (!lua_isstring(L, -1)) {
8240 /* invalid value type, skip it*/
8241 lua_pop(L, 1);
8242 continue;
8243 }
8244 /* push the value in the inner table */
8245 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8246 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8247 }
8248 lua_pop(L, 1);
8249 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8250 }
8251
8252 /* push (k,v) on the stack in the headers table:
8253 * stack: [ ... <headers:table>, <table>, k, k, v ]
8254 */
8255 lua_settable(L, -5);
8256 /* stack: [ ... <headers:table>, <table>, k ] */
8257 }
8258 }
8259 lua_pop(L, 1);
8260 }
8261 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8262 lua_settable(L, -3);
8263 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8264
8265 /* Pop a class sesison metatable and affect it to the userdata. */
8266 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8267 lua_setmetatable(L, -2);
8268 return 1;
8269}
8270
8271/* Set the reply status code, and optionally the reason. If no reason is
8272 * provided, the default one corresponding to the status code is used.
8273 */
8274__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8275{
8276 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8277 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8278
8279 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008280 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008281
8282 if (status < 100 || status > 599) {
8283 lua_pushboolean(L, 0);
8284 return 1;
8285 }
8286 if (!reason)
8287 reason = http_get_reason(status);
8288
8289 lua_pushinteger(L, status);
8290 lua_setfield(L, 1, "status");
8291
8292 lua_pushstring(L, reason);
8293 lua_setfield(L, 1, "reason");
8294
8295 lua_pushboolean(L, 1);
8296 return 1;
8297}
8298
8299/* Add a header into the reply object. Each header name is associated to an
8300 * array of values in the "headers" table. If the header name is not found, a
8301 * new entry is created.
8302 */
8303__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8304{
8305 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8306 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8307 int ret;
8308
8309 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008310 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008311
8312 /* Push in the stack the "headers" entry. */
8313 ret = lua_getfield(L, 1, "headers");
8314 if (ret != LUA_TTABLE) {
8315 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8316 WILL_LJMP(lua_error(L));
8317 }
8318
8319 /* check if the header is already registered. If not, register it. */
8320 ret = lua_getfield(L, -1, name);
8321 if (ret == LUA_TNIL) {
8322 /* Entry not found. */
8323 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8324
8325 /* Insert the new header name in the array in the top of the stack.
8326 * It left the new array in the top of the stack.
8327 */
8328 lua_newtable(L);
8329 lua_pushstring(L, name);
8330 lua_pushvalue(L, -2);
8331 lua_settable(L, -4);
8332 }
8333 else if (ret != LUA_TTABLE) {
8334 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8335 WILL_LJMP(lua_error(L));
8336 }
8337
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008338 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008339 * the header value as new entry.
8340 */
8341 lua_pushstring(L, value);
8342 ret = lua_rawlen(L, -2);
8343 lua_rawseti(L, -2, ret + 1);
8344
8345 lua_pushboolean(L, 1);
8346 return 1;
8347}
8348
8349/* Remove all occurrences of a given header name. */
8350__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8351{
8352 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8353 int ret;
8354
8355 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008356 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008357
8358 /* Push in the stack the "headers" entry. */
8359 ret = lua_getfield(L, 1, "headers");
8360 if (ret != LUA_TTABLE) {
8361 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8362 WILL_LJMP(lua_error(L));
8363 }
8364
8365 lua_pushstring(L, name);
8366 lua_pushnil(L);
8367 lua_settable(L, -3);
8368
8369 lua_pushboolean(L, 1);
8370 return 1;
8371}
8372
8373/* Set the reply's body. Overwrite any existing entry. */
8374__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8375{
8376 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8377
8378 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008379 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008380
8381 lua_pushstring(L, payload);
8382 lua_setfield(L, 1, "body");
8383
8384 lua_pushboolean(L, 1);
8385 return 1;
8386}
8387
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008388__LJMP static int hlua_log(lua_State *L)
8389{
8390 int level;
8391 const char *msg;
8392
8393 MAY_LJMP(check_args(L, 2, "log"));
8394 level = MAY_LJMP(luaL_checkinteger(L, 1));
8395 msg = MAY_LJMP(luaL_checkstring(L, 2));
8396
8397 if (level < 0 || level >= NB_LOG_LEVELS)
8398 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8399
8400 hlua_sendlog(NULL, level, msg);
8401 return 0;
8402}
8403
8404__LJMP static int hlua_log_debug(lua_State *L)
8405{
8406 const char *msg;
8407
8408 MAY_LJMP(check_args(L, 1, "debug"));
8409 msg = MAY_LJMP(luaL_checkstring(L, 1));
8410 hlua_sendlog(NULL, LOG_DEBUG, msg);
8411 return 0;
8412}
8413
8414__LJMP static int hlua_log_info(lua_State *L)
8415{
8416 const char *msg;
8417
8418 MAY_LJMP(check_args(L, 1, "info"));
8419 msg = MAY_LJMP(luaL_checkstring(L, 1));
8420 hlua_sendlog(NULL, LOG_INFO, msg);
8421 return 0;
8422}
8423
8424__LJMP static int hlua_log_warning(lua_State *L)
8425{
8426 const char *msg;
8427
8428 MAY_LJMP(check_args(L, 1, "warning"));
8429 msg = MAY_LJMP(luaL_checkstring(L, 1));
8430 hlua_sendlog(NULL, LOG_WARNING, msg);
8431 return 0;
8432}
8433
8434__LJMP static int hlua_log_alert(lua_State *L)
8435{
8436 const char *msg;
8437
8438 MAY_LJMP(check_args(L, 1, "alert"));
8439 msg = MAY_LJMP(luaL_checkstring(L, 1));
8440 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008441 return 0;
8442}
8443
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008444__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008445{
8446 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008447 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008448 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008449 return 0;
8450}
8451
8452__LJMP static int hlua_sleep(lua_State *L)
8453{
8454 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008455 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008456
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008457 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008458
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008459 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008460 wakeup_ms = tick_add(now_ms, delay);
8461 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008462
Willy Tarreau9635e032018-10-16 17:52:55 +02008463 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008464 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008465}
8466
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008467__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008468{
8469 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008470 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008471
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008472 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008473
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008474 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008475 wakeup_ms = tick_add(now_ms, delay);
8476 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008477
Willy Tarreau9635e032018-10-16 17:52:55 +02008478 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008479 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008480}
8481
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008482/* This functionis an LUA binding. it permits to give back
8483 * the hand at the HAProxy scheduler. It is used when the
8484 * LUA processing consumes a lot of time.
8485 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008486__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008487{
8488 return 0;
8489}
8490
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008491__LJMP static int hlua_yield(lua_State *L)
8492{
Willy Tarreau9635e032018-10-16 17:52:55 +02008493 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008494 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008495}
8496
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008497/* This function change the nice of the currently executed
8498 * task. It is used set low or high priority at the current
8499 * task.
8500 */
Willy Tarreau59551662015-03-10 14:23:13 +01008501__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008502{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008503 struct hlua *hlua;
8504 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008505
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008506 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008507 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008508
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008509 /* Get hlua struct, or NULL if we execute from main lua state */
8510 hlua = hlua_gethlua(L);
8511
8512 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008513 if (!hlua || !hlua->task)
8514 return 0;
8515
8516 if (nice < -1024)
8517 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008518 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008519 nice = 1024;
8520
8521 hlua->task->nice = nice;
8522 return 0;
8523}
8524
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008525/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008526 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8527 * return an E_AGAIN signal, the emmiter of this signal must set a
8528 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008529 *
8530 * Task wrapper are longjmp safe because the only one Lua code
8531 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008532 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008533struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008534{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008535 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008536 enum hlua_exec status;
8537
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008538 if (task->tid < 0)
8539 task->tid = tid;
8540
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008541 /* If it is the first call to the task, we must initialize the
8542 * execution timeouts.
8543 */
8544 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008545 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008546
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008547 /* Execute the Lua code. */
8548 status = hlua_ctx_resume(hlua, 1);
8549
8550 switch (status) {
8551 /* finished or yield */
8552 case HLUA_E_OK:
8553 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008554 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008555 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008556 break;
8557
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008558 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008559 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008560 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008561 break;
8562
8563 /* finished with error. */
8564 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008565 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008566 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008567 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008568 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008569 break;
8570
8571 case HLUA_E_ERR:
8572 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008573 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008574 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008575 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008576 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008577 break;
8578 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008579 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008580}
8581
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008582/* This function is an LUA binding that register LUA function to be
8583 * executed after the HAProxy configuration parsing and before the
8584 * HAProxy scheduler starts. This function expect only one LUA
8585 * argument that is a function. This function returns nothing, but
8586 * throws if an error is encountered.
8587 */
8588__LJMP static int hlua_register_init(lua_State *L)
8589{
8590 struct hlua_init_function *init;
8591 int ref;
8592
8593 MAY_LJMP(check_args(L, 1, "register_init"));
8594
8595 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8596
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008597 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008598 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008599 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008600
8601 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008602 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008603 return 0;
8604}
8605
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008606/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008607 * executed in parallel of the main HAroxy activity. The task is
8608 * created and it is set in the HAProxy scheduler. It can be called
8609 * from the "init" section, "post init" or during the runtime.
8610 *
8611 * Lua prototype:
8612 *
8613 * <none> core.register_task(<function>)
8614 */
8615static int hlua_register_task(lua_State *L)
8616{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008617 struct hlua *hlua = NULL;
8618 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008619 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008620 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008621
8622 MAY_LJMP(check_args(L, 1, "register_task"));
8623
8624 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8625
Thierry Fournier75fc0292020-11-28 13:18:56 +01008626 /* Get the reference state. If the reference is NULL, L is the master
8627 * state, otherwise hlua->T is.
8628 */
8629 hlua = hlua_gethlua(L);
8630 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008631 /* we are in runtime processing */
8632 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008633 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008634 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008635 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008636
Willy Tarreaubafbe012017-11-24 17:34:44 +01008637 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008638 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008639 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008640 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008641
Thierry Fournier59f11be2020-11-29 00:37:41 +01008642 /* We are in the common lua state, execute the task anywhere,
8643 * otherwise, inherit the current thread identifier
8644 */
8645 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008646 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008647 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008648 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008649 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008650 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008651
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008652 task->context = hlua;
8653 task->process = hlua_process_task;
8654
Thierry Fournier021d9862020-11-28 23:42:03 +01008655 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008656 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008657
8658 /* Restore the function in the stack. */
8659 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8660 hlua->nargs = 0;
8661
8662 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008663 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008664
8665 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008666
8667 alloc_error:
8668 task_destroy(task);
8669 hlua_ctx_destroy(hlua);
8670 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8671 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008672}
8673
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008674/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8675 * doesn't allow "yield" functions because the HAProxy engine cannot
8676 * resume converters.
8677 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008678static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008679{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008680 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008681 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008682 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008683
Willy Tarreaube508f12016-03-10 11:47:01 +01008684 if (!stream)
8685 return 0;
8686
Willy Tarreau87b09662015-04-03 00:22:06 +02008687 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008688 * Lua context can be not initialized. This behavior
8689 * permits to save performances because a systematic
8690 * Lua initialization cause 5% performances loss.
8691 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008692 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008693 struct hlua *hlua;
8694
8695 hlua = pool_alloc(pool_head_hlua);
8696 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008697 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8698 return 0;
8699 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008700 HLUA_INIT(hlua);
8701 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008702 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008703 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8704 return 0;
8705 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008706 }
8707
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008708 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008709 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008710
8711 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008712 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008713 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8714 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008715 else
8716 error = "critical error";
8717 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008718 return 0;
8719 }
8720
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008721 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008722 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008723 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008724 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008725 return 0;
8726 }
8727
8728 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008729 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008730
8731 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008732 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008733 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008734 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008735 return 0;
8736 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008737 hlua_smp2lua(stream->hlua->T, smp);
8738 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008739
8740 /* push keywords in the stack. */
8741 if (arg_p) {
8742 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008743 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008744 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008745 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008746 return 0;
8747 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008748 hlua_arg2lua(stream->hlua->T, arg_p);
8749 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008750 }
8751 }
8752
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008753 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008754 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008755
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008756 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008757 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008758 }
8759
8760 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008761 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008762 /* finished. */
8763 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008764 /* If the stack is empty, the function fails. */
8765 if (lua_gettop(stream->hlua->T) <= 0)
8766 return 0;
8767
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008768 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008769 hlua_lua2smp(stream->hlua->T, -1, smp);
8770 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008771 return 1;
8772
8773 /* yield. */
8774 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008775 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008776 return 0;
8777
8778 /* finished with error. */
8779 case HLUA_E_ERRMSG:
8780 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008781 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008782 fcn->name, lua_tostring(stream->hlua->T, -1));
8783 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008784 return 0;
8785
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008786 case HLUA_E_ETMOUT:
8787 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8788 return 0;
8789
8790 case HLUA_E_NOMEM:
8791 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8792 return 0;
8793
8794 case HLUA_E_YIELD:
8795 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8796 return 0;
8797
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008798 case HLUA_E_ERR:
8799 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008800 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008801 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008802
8803 default:
8804 return 0;
8805 }
8806}
8807
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008808/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8809 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008810 * resume sample-fetches. This function will be called by the sample
8811 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008812 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008813static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8814 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008815{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008816 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008817 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008818 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008819 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008820
Willy Tarreaube508f12016-03-10 11:47:01 +01008821 if (!stream)
8822 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008823
Willy Tarreau87b09662015-04-03 00:22:06 +02008824 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008825 * Lua context can be not initialized. This behavior
8826 * permits to save performances because a systematic
8827 * Lua initialization cause 5% performances loss.
8828 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008829 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008830 struct hlua *hlua;
8831
8832 hlua = pool_alloc(pool_head_hlua);
8833 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008834 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8835 return 0;
8836 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008837 hlua->T = NULL;
8838 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008839 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008840 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8841 return 0;
8842 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008843 }
8844
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008845 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008846 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008847
8848 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008849 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008850 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8851 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008852 else
8853 error = "critical error";
8854 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008855 return 0;
8856 }
8857
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008858 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008859 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008860 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008861 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008862 return 0;
8863 }
8864
8865 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008866 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008867
8868 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008869 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008870 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008871 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008872 return 0;
8873 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008874 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008875
8876 /* push keywords in the stack. */
8877 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8878 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008879 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008880 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008881 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008882 return 0;
8883 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008884 hlua_arg2lua(stream->hlua->T, arg_p);
8885 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008886 }
8887
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008888 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008889 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008890
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008891 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008892 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008893 }
8894
8895 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008896 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008897 /* finished. */
8898 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008899 /* If the stack is empty, the function fails. */
8900 if (lua_gettop(stream->hlua->T) <= 0)
8901 return 0;
8902
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008903 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008904 hlua_lua2smp(stream->hlua->T, -1, smp);
8905 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008906
8907 /* Set the end of execution flag. */
8908 smp->flags &= ~SMP_F_MAY_CHANGE;
8909 return 1;
8910
8911 /* yield. */
8912 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008913 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008914 return 0;
8915
8916 /* finished with error. */
8917 case HLUA_E_ERRMSG:
8918 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008919 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008920 fcn->name, lua_tostring(stream->hlua->T, -1));
8921 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008922 return 0;
8923
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008924 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008925 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8926 return 0;
8927
8928 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008929 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8930 return 0;
8931
8932 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008933 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8934 return 0;
8935
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008936 case HLUA_E_ERR:
8937 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008938 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008939 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008940
8941 default:
8942 return 0;
8943 }
8944}
8945
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008946/* This function is an LUA binding used for registering
8947 * "sample-conv" functions. It expects a converter name used
8948 * in the haproxy configuration file, and an LUA function.
8949 */
8950__LJMP static int hlua_register_converters(lua_State *L)
8951{
8952 struct sample_conv_kw_list *sck;
8953 const char *name;
8954 int ref;
8955 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008956 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008957 struct sample_conv *sc;
8958 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008959
8960 MAY_LJMP(check_args(L, 2, "register_converters"));
8961
8962 /* First argument : converter name. */
8963 name = MAY_LJMP(luaL_checkstring(L, 1));
8964
8965 /* Second argument : lua function. */
8966 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8967
Thierry Fournierf67442e2020-11-28 20:41:07 +01008968 /* Check if the converter is already registered */
8969 trash = get_trash_chunk();
8970 chunk_printf(trash, "lua.%s", name);
8971 sc = find_sample_conv(trash->area, trash->data);
8972 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008973 fcn = sc->private;
8974 if (fcn->function_ref[hlua_state_id] != -1) {
8975 ha_warning("Trying to register converter 'lua.%s' more than once. "
8976 "This will become a hard error in version 2.5.\n", name);
8977 }
8978 fcn->function_ref[hlua_state_id] = ref;
8979 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008980 }
8981
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008982 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008983 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008984 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008985 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008986 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008987 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008988 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008989
8990 /* Fill fcn. */
8991 fcn->name = strdup(name);
8992 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008993 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008994 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008995
8996 /* List head */
8997 sck->list.n = sck->list.p = NULL;
8998
8999 /* converter keyword. */
9000 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009001 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009002 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009003 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009004
9005 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9006 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009007 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 +01009008 sck->kw[0].val_args = NULL;
9009 sck->kw[0].in_type = SMP_T_STR;
9010 sck->kw[0].out_type = SMP_T_STR;
9011 sck->kw[0].private = fcn;
9012
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009013 /* Register this new converter */
9014 sample_register_convs(sck);
9015
9016 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009017
9018 alloc_error:
9019 release_hlua_function(fcn);
9020 ha_free(&sck);
9021 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9022 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009023}
9024
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009025/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009026 * "sample-fetch" functions. It expects a converter name used
9027 * in the haproxy configuration file, and an LUA function.
9028 */
9029__LJMP static int hlua_register_fetches(lua_State *L)
9030{
9031 const char *name;
9032 int ref;
9033 int len;
9034 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009035 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009036 struct sample_fetch *sf;
9037 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009038
9039 MAY_LJMP(check_args(L, 2, "register_fetches"));
9040
9041 /* First argument : sample-fetch name. */
9042 name = MAY_LJMP(luaL_checkstring(L, 1));
9043
9044 /* Second argument : lua function. */
9045 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9046
Thierry Fournierf67442e2020-11-28 20:41:07 +01009047 /* Check if the sample-fetch is already registered */
9048 trash = get_trash_chunk();
9049 chunk_printf(trash, "lua.%s", name);
9050 sf = find_sample_fetch(trash->area, trash->data);
9051 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009052 fcn = sf->private;
9053 if (fcn->function_ref[hlua_state_id] != -1) {
9054 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9055 "This will become a hard error in version 2.5.\n", name);
9056 }
9057 fcn->function_ref[hlua_state_id] = ref;
9058 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009059 }
9060
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009061 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009062 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009063 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009064 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009065 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009066 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009067 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009068
9069 /* Fill fcn. */
9070 fcn->name = strdup(name);
9071 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009072 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009073 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009074
9075 /* List head */
9076 sfk->list.n = sfk->list.p = NULL;
9077
9078 /* sample-fetch keyword. */
9079 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009080 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009081 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009082 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009083
9084 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9085 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009086 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 +01009087 sfk->kw[0].val_args = NULL;
9088 sfk->kw[0].out_type = SMP_T_STR;
9089 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9090 sfk->kw[0].val = 0;
9091 sfk->kw[0].private = fcn;
9092
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009093 /* Register this new fetch. */
9094 sample_register_fetches(sfk);
9095
9096 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009097
9098 alloc_error:
9099 release_hlua_function(fcn);
9100 ha_free(&sfk);
9101 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9102 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009103}
9104
Christopher Faulet501465d2020-02-26 14:54:16 +01009105/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009106 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009107__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009108{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009109 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009110 unsigned int delay;
9111 unsigned int wakeup_ms;
9112
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009113 /* Get hlua struct, or NULL if we execute from main lua state */
9114 hlua = hlua_gethlua(L);
9115 if (!hlua) {
9116 return 0;
9117 }
9118
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009119 MAY_LJMP(check_args(L, 1, "wake_time"));
9120
9121 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9122 wakeup_ms = tick_add(now_ms, delay);
9123 hlua->wake_time = wakeup_ms;
9124 return 0;
9125}
9126
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009127/* This function is a wrapper to execute each LUA function declared as an action
9128 * wrapper during the initialisation period. This function may return any
9129 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9130 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9131 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009132 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009133static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009134 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009135{
9136 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009137 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009138 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009139 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009140
9141 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009142 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9143 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9144 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9145 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009146 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009147 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009148 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009149 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009150
Willy Tarreau87b09662015-04-03 00:22:06 +02009151 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009152 * Lua context can be not initialized. This behavior
9153 * permits to save performances because a systematic
9154 * Lua initialization cause 5% performances loss.
9155 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009156 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009157 struct hlua *hlua;
9158
9159 hlua = pool_alloc(pool_head_hlua);
9160 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009161 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009162 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009163 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009164 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009165 HLUA_INIT(hlua);
9166 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009167 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 +01009168 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009169 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009170 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009171 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009172 }
9173
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009174 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009175 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009176
9177 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009178 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009179 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9180 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009181 else
9182 error = "critical error";
9183 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009184 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009185 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009186 }
9187
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009188 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009189 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009190 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009191 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009192 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009193 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009194 }
9195
9196 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009197 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 +01009198
Willy Tarreau87b09662015-04-03 00:22:06 +02009199 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009200 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009201 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009202 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009203 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009204 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009205 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009206 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009207
9208 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009209 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009210 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009211 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009212 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009213 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009214 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009215 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009216 lua_pushstring(s->hlua->T, *arg);
9217 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009218 }
9219
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009220 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009221 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009222
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009223 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009224 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009225 }
9226
9227 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009228 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009229 /* finished. */
9230 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009231 /* Catch the return value */
9232 if (lua_gettop(s->hlua->T) > 0)
9233 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009234
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009235 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009236 if (act_ret == ACT_RET_YIELD) {
9237 if (flags & ACT_OPT_FINAL)
9238 goto err_yield;
9239
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009240 if (dir == SMP_OPT_DIR_REQ)
9241 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9242 s->hlua->wake_time);
9243 else
9244 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9245 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009246 }
9247 goto end;
9248
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009249 /* yield. */
9250 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009251 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009252 if (dir == SMP_OPT_DIR_REQ)
9253 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9254 s->hlua->wake_time);
9255 else
9256 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9257 s->hlua->wake_time);
9258
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009259 /* Some actions can be wake up when a "write" event
9260 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009261 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009262 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009263 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009264 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009265 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009266 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009267 act_ret = ACT_RET_YIELD;
9268 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009269
9270 /* finished with error. */
9271 case HLUA_E_ERRMSG:
9272 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009273 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009274 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009275 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009276 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009277
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009278 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009279 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009280 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009281
9282 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009283 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009284 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009285
9286 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009287 err_yield:
9288 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009289 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009290 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009291 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009292
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009293 case HLUA_E_ERR:
9294 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009295 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009296 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009297
9298 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009299 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009300 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009301
9302 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009303 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009304 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009305 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009306}
9307
Willy Tarreau144f84a2021-03-02 16:09:26 +01009308struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009309{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009310 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009311
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009312 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009313 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009314 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009315}
9316
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009317static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009318{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009319 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009320 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009321 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009322 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009323 struct task *task;
9324 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009325 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009326
Willy Tarreaubafbe012017-11-24 17:34:44 +01009327 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009328 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009329 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009330 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009331 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009332 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009333 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009334 tcp_ctx->hlua = hlua;
9335 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009336
9337 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009338 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009339 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009340 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009341 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009342 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343 }
9344 task->nice = 0;
9345 task->context = ctx;
9346 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009347 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009348
9349 /* In the execution wrappers linked with a stream, the
9350 * Lua context can be not initialized. This behavior
9351 * permits to save performances because a systematic
9352 * Lua initialization cause 5% performances loss.
9353 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009354 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 +01009355 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009356 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009357 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358 }
9359
9360 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009361 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009362
9363 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009364 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009365 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9366 error = lua_tostring(hlua->T, -1);
9367 else
9368 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009369 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009370 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009371 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372 }
9373
9374 /* Check stack available size. */
9375 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009376 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009377 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009378 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009379 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009380 }
9381
9382 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009383 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009384
9385 /* Create and and push object stream in the stack. */
9386 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009387 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009388 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009389 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009390 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009391 }
9392 hlua->nargs = 1;
9393
9394 /* push keywords in the stack. */
9395 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9396 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009397 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009398 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009399 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009400 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009401 }
9402 lua_pushstring(hlua->T, *arg);
9403 hlua->nargs++;
9404 }
9405
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009406 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009407
9408 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009409 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009410 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009411
Christopher Fauletc9929382022-05-12 11:52:27 +02009412 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009413}
9414
Willy Tarreau60409db2019-08-21 14:14:50 +02009415void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009416{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009417 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009418 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009419 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009420 struct act_rule *rule = ctx->rule;
9421 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009422 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009423
9424 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009425 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009426 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009427 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009428 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009429 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009430
9431 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009432 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009433 return;
9434
9435 /* Execute the function. */
9436 switch (hlua_ctx_resume(hlua, 1)) {
9437 /* finished. */
9438 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009439 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009440
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009441 /* eat the whole request */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009442 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Willy Tarreau3e7be362022-05-27 10:35:27 +02009443 sc_shutr(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009444 return;
9445
9446 /* yield. */
9447 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009448 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009449 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009450 return;
9451
9452 /* finished with error. */
9453 case HLUA_E_ERRMSG:
9454 /* Display log. */
9455 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009456 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009457 lua_pop(hlua->T, 1);
9458 goto error;
9459
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009460 case HLUA_E_ETMOUT:
9461 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009462 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009463 goto error;
9464
9465 case HLUA_E_NOMEM:
9466 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009467 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009468 goto error;
9469
9470 case HLUA_E_YIELD: /* unexpected */
9471 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009472 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009473 goto error;
9474
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009475 case HLUA_E_ERR:
9476 /* Display log. */
9477 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009478 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009479 goto error;
9480
9481 default:
9482 goto error;
9483 }
9484
9485error:
9486
9487 /* For all other cases, just close the stream. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009488 sc_shutw(sc);
9489 sc_shutr(sc);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009490 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009491}
9492
9493static void hlua_applet_tcp_release(struct appctx *ctx)
9494{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009495 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9496
9497 task_destroy(tcp_ctx->task);
9498 tcp_ctx->task = NULL;
9499 hlua_ctx_destroy(tcp_ctx->hlua);
9500 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009501}
9502
Christopher Fauletc9929382022-05-12 11:52:27 +02009503/* The function returns 0 if the initialisation is complete or -1 if
9504 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009505 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009506static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009507{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009508 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009509 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009510 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009511 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009512 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009513 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009514 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009515 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009516
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009517 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009518 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009519 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009520 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009521 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009522 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009523 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009524 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009525 http_ctx->hlua = hlua;
9526 http_ctx->left_bytes = -1;
9527 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009528
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009529 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009530 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009531
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009532 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009533 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009534 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009535 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009536 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009537 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009538 }
9539 task->nice = 0;
9540 task->context = ctx;
9541 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009542 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009543
9544 /* In the execution wrappers linked with a stream, the
9545 * Lua context can be not initialized. This behavior
9546 * permits to save performances because a systematic
9547 * Lua initialization cause 5% performances loss.
9548 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009549 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 +01009550 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009551 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009552 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009553 }
9554
9555 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009556 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009557
9558 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009559 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009560 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9561 error = lua_tostring(hlua->T, -1);
9562 else
9563 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009564 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009565 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009566 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009567 }
9568
9569 /* Check stack available size. */
9570 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009571 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009572 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009573 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009574 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009575 }
9576
9577 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009578 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009579
9580 /* Create and and push object stream in the stack. */
9581 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009582 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009583 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009584 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009585 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009586 }
9587 hlua->nargs = 1;
9588
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009589 /* push keywords in the stack. */
9590 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9591 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009592 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009593 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009594 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009595 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009596 }
9597 lua_pushstring(hlua->T, *arg);
9598 hlua->nargs++;
9599 }
9600
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009601 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009602
9603 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009604 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009605
Christopher Fauletc9929382022-05-12 11:52:27 +02009606 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009607}
9608
Willy Tarreau60409db2019-08-21 14:14:50 +02009609void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009610{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009611 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009612 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009613 struct stream *strm = __sc_strm(sc);
9614 struct channel *req = sc_oc(sc);
9615 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009616 struct act_rule *rule = ctx->rule;
9617 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009618 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009619 struct htx *req_htx, *res_htx;
9620
9621 res_htx = htx_from_buf(&res->buf);
9622
9623 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02009624 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009625 goto out;
9626
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009627 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009628 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009629 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009630 goto out;
9631 }
9632 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009633 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009634 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009635
9636 /* Set the currently running flag. */
9637 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009638 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009639 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009640 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009641 goto out;
9642 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009643 }
9644
9645 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009646 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009647
9648 /* Execute the function. */
9649 switch (hlua_ctx_resume(hlua, 1)) {
9650 /* finished. */
9651 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009652 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009653 break;
9654
9655 /* yield. */
9656 case HLUA_E_AGAIN:
9657 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009658 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009659 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009660
9661 /* finished with error. */
9662 case HLUA_E_ERRMSG:
9663 /* Display log. */
9664 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009665 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009666 lua_pop(hlua->T, 1);
9667 goto error;
9668
9669 case HLUA_E_ETMOUT:
9670 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009671 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009672 goto error;
9673
9674 case HLUA_E_NOMEM:
9675 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009676 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009677 goto error;
9678
9679 case HLUA_E_YIELD: /* unexpected */
9680 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009681 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009682 goto error;
9683
9684 case HLUA_E_ERR:
9685 /* Display log. */
9686 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009687 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009688 goto error;
9689
9690 default:
9691 goto error;
9692 }
9693 }
9694
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009695 if (http_ctx->flags & APPLET_DONE) {
9696 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009697 goto done;
9698
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009699 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009700 goto error;
9701
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009702 /* no more data are expected. If the response buffer is empty
9703 * for a chunked message, be sure to add something (EOT block in
9704 * this case) to have something to send. It is important to be
9705 * sure the EOM flags will be handled by the endpoint.
9706 */
9707 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9708 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009709 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009710 goto out;
9711 }
9712 channel_add_input(res, 1);
9713 }
9714
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009715 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009716 res->flags |= CF_EOI;
Willy Tarreaud869e132022-05-17 18:05:31 +02009717 se_fl_set(ctx->sedesc, SE_FL_EOI);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009718 strm->txn->status = http_ctx->status;
9719 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009720 }
9721
9722 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009723 if (http_ctx->flags & APPLET_DONE) {
Christopher Fauletb08c5252023-02-20 07:55:19 +01009724 if (!(res->flags & CF_SHUTR))
Willy Tarreau3e7be362022-05-27 10:35:27 +02009725 sc_shutr(sc);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009726
9727 /* eat the whole request */
9728 if (co_data(req)) {
9729 req_htx = htx_from_buf(&req->buf);
9730 co_htx_skip(req, req_htx, co_data(req));
9731 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009732 }
9733 }
9734
9735 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009736 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009737 return;
9738
9739 error:
9740
9741 /* If we are in HTTP mode, and we are not send any
9742 * data, return a 500 server error in best effort:
9743 * if there is no room available in the buffer,
9744 * just close the connection.
9745 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009746 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009747 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009748
9749 channel_erase(res);
9750 res->buf.data = b_data(err);
9751 memcpy(res->buf.area, b_head(err), b_data(err));
9752 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009753 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009754 }
9755 if (!(strm->flags & SF_ERR_MASK))
9756 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009757 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009758 goto done;
9759}
9760
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009761static void hlua_applet_http_release(struct appctx *ctx)
9762{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009763 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9764
9765 task_destroy(http_ctx->task);
9766 http_ctx->task = NULL;
9767 hlua_ctx_destroy(http_ctx->hlua);
9768 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009769}
9770
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009771/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009772 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009773 *
9774 * This function can fail with an abort() due to an Lua critical error.
9775 * We are in the configuration parsing process of HAProxy, this abort() is
9776 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009777 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009778static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9779 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009780{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009781 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009782 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009783
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009784 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009785 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009786 if (!rule->arg.hlua_rule) {
9787 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009788 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009789 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009790
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009791 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009792 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9793 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009794 if (!rule->arg.hlua_rule->args) {
9795 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009796 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009797 }
9798
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009799 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009800 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009801
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009802 /* Expect some arguments */
9803 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009804 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009805 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009806 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009807 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009808 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009809 if (!rule->arg.hlua_rule->args[i]) {
9810 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009811 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009812 }
9813 (*cur_arg)++;
9814 }
9815 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009816
Thierry FOURNIER42148732015-09-02 17:17:33 +02009817 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009818 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009819 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009820
9821 error:
9822 if (rule->arg.hlua_rule) {
9823 if (rule->arg.hlua_rule->args) {
9824 for (i = 0; i < fcn->nargs; i++)
9825 ha_free(&rule->arg.hlua_rule->args[i]);
9826 ha_free(&rule->arg.hlua_rule->args);
9827 }
9828 ha_free(&rule->arg.hlua_rule);
9829 }
9830 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009831}
9832
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009833static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9834 struct act_rule *rule, char **err)
9835{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009836 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009837
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009838 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009839 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009840 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009841 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009842 * the call of this analyzer.
9843 */
9844 if (rule->from != ACT_F_HTTP_REQ) {
9845 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9846 return ACT_RET_PRS_ERR;
9847 }
9848
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009849 /* Memory for the rule. */
9850 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9851 if (!rule->arg.hlua_rule) {
9852 memprintf(err, "out of memory error");
9853 return ACT_RET_PRS_ERR;
9854 }
9855
9856 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009857 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009858
9859 /* TODO: later accept arguments. */
9860 rule->arg.hlua_rule->args = NULL;
9861
9862 /* Add applet pointer in the rule. */
9863 rule->applet.obj_type = OBJ_TYPE_APPLET;
9864 rule->applet.name = fcn->name;
9865 rule->applet.init = hlua_applet_http_init;
9866 rule->applet.fct = hlua_applet_http_fct;
9867 rule->applet.release = hlua_applet_http_release;
9868 rule->applet.timeout = hlua_timeout_applet;
9869
9870 return ACT_RET_PRS_OK;
9871}
9872
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009873/* This function is an LUA binding used for registering
9874 * "sample-conv" functions. It expects a converter name used
9875 * in the haproxy configuration file, and an LUA function.
9876 */
9877__LJMP static int hlua_register_action(lua_State *L)
9878{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009879 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009880 const char *name;
9881 int ref;
9882 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009883 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009884 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009885 struct buffer *trash;
9886 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009887
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009888 /* Initialise the number of expected arguments at 0. */
9889 nargs = 0;
9890
9891 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9892 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009893
9894 /* First argument : converter name. */
9895 name = MAY_LJMP(luaL_checkstring(L, 1));
9896
9897 /* Second argument : environment. */
9898 if (lua_type(L, 2) != LUA_TTABLE)
9899 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9900
9901 /* Third argument : lua function. */
9902 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9903
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009904 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009905 if (lua_gettop(L) >= 4)
9906 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9907
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009908 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009909 lua_pushnil(L);
9910 while (lua_next(L, 2) != 0) {
9911 if (lua_type(L, -1) != LUA_TSTRING)
9912 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9913
Thierry Fournierf67442e2020-11-28 20:41:07 +01009914 /* Check if action exists */
9915 trash = get_trash_chunk();
9916 chunk_printf(trash, "lua.%s", name);
9917 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9918 akw = tcp_req_cont_action(trash->area);
9919 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9920 akw = tcp_res_cont_action(trash->area);
9921 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9922 akw = action_http_req_custom(trash->area);
9923 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9924 akw = action_http_res_custom(trash->area);
9925 } else {
9926 akw = NULL;
9927 }
9928 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009929 fcn = akw->private;
9930 if (fcn->function_ref[hlua_state_id] != -1) {
9931 ha_warning("Trying to register action 'lua.%s' more than once. "
9932 "This will become a hard error in version 2.5.\n", name);
9933 }
9934 fcn->function_ref[hlua_state_id] = ref;
9935
9936 /* pop the environment string. */
9937 lua_pop(L, 1);
9938 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009939 }
9940
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009941 /* Check required environment. Only accepted "http" or "tcp". */
9942 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009943 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009944 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009945 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009946 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009947 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009948 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009949
9950 /* Fill fcn. */
9951 fcn->name = strdup(name);
9952 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009953 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009954 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009955
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009956 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009957 fcn->nargs = nargs;
9958
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009959 /* List head */
9960 akl->list.n = akl->list.p = NULL;
9961
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009962 /* action keyword. */
9963 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009964 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009965 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009966 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009967
9968 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9969
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009970 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009971 akl->kw[0].private = fcn;
9972 akl->kw[0].parse = action_register_lua;
9973
9974 /* select the action registering point. */
9975 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9976 tcp_req_cont_keywords_register(akl);
9977 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9978 tcp_res_cont_keywords_register(akl);
9979 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9980 http_req_keywords_register(akl);
9981 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9982 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009983 else {
9984 release_hlua_function(fcn);
9985 if (akl)
9986 ha_free((char **)&(akl->kw[0].kw));
9987 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009988 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009989 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9990 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009991 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009992
9993 /* pop the environment string. */
9994 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009995
9996 /* reset for next loop */
9997 akl = NULL;
9998 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009999 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010000 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010001
10002 alloc_error:
10003 release_hlua_function(fcn);
10004 ha_free(&akl);
10005 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10006 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010007}
10008
10009static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10010 struct act_rule *rule, char **err)
10011{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010012 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010013
Christopher Faulet280f85b2019-07-15 15:02:04 +020010014 if (px->mode == PR_MODE_HTTP) {
10015 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010016 return ACT_RET_PRS_ERR;
10017 }
10018
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010019 /* Memory for the rule. */
10020 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10021 if (!rule->arg.hlua_rule) {
10022 memprintf(err, "out of memory error");
10023 return ACT_RET_PRS_ERR;
10024 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010025
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010026 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010027 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010028
10029 /* TODO: later accept arguments. */
10030 rule->arg.hlua_rule->args = NULL;
10031
10032 /* Add applet pointer in the rule. */
10033 rule->applet.obj_type = OBJ_TYPE_APPLET;
10034 rule->applet.name = fcn->name;
10035 rule->applet.init = hlua_applet_tcp_init;
10036 rule->applet.fct = hlua_applet_tcp_fct;
10037 rule->applet.release = hlua_applet_tcp_release;
10038 rule->applet.timeout = hlua_timeout_applet;
10039
10040 return 0;
10041}
10042
10043/* This function is an LUA binding used for registering
10044 * "sample-conv" functions. It expects a converter name used
10045 * in the haproxy configuration file, and an LUA function.
10046 */
10047__LJMP static int hlua_register_service(lua_State *L)
10048{
10049 struct action_kw_list *akl;
10050 const char *name;
10051 const char *env;
10052 int ref;
10053 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010054 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010055 struct buffer *trash;
10056 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010057
10058 MAY_LJMP(check_args(L, 3, "register_service"));
10059
10060 /* First argument : converter name. */
10061 name = MAY_LJMP(luaL_checkstring(L, 1));
10062
10063 /* Second argument : environment. */
10064 env = MAY_LJMP(luaL_checkstring(L, 2));
10065
10066 /* Third argument : lua function. */
10067 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10068
Thierry Fournierf67442e2020-11-28 20:41:07 +010010069 /* Check for service already registered */
10070 trash = get_trash_chunk();
10071 chunk_printf(trash, "lua.%s", name);
10072 akw = service_find(trash->area);
10073 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010074 fcn = akw->private;
10075 if (fcn->function_ref[hlua_state_id] != -1) {
10076 ha_warning("Trying to register service 'lua.%s' more than once. "
10077 "This will become a hard error in version 2.5.\n", name);
10078 }
10079 fcn->function_ref[hlua_state_id] = ref;
10080 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010081 }
10082
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010083 /* Allocate and fill the sample fetch keyword struct. */
10084 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10085 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010086 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010087 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010088 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010089 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010090
10091 /* Fill fcn. */
10092 len = strlen("<lua.>") + strlen(name) + 1;
10093 fcn->name = calloc(1, len);
10094 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010095 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010096 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010097 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010098
10099 /* List head */
10100 akl->list.n = akl->list.p = NULL;
10101
10102 /* converter keyword. */
10103 len = strlen("lua.") + strlen(name) + 1;
10104 akl->kw[0].kw = calloc(1, len);
10105 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010106 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010107
10108 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10109
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010110 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010111 if (strcmp(env, "tcp") == 0)
10112 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010113 else if (strcmp(env, "http") == 0)
10114 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010115 else {
10116 release_hlua_function(fcn);
10117 if (akl)
10118 ha_free((char **)&(akl->kw[0].kw));
10119 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010120 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010121 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010122 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010123
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010124 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010125 akl->kw[0].private = fcn;
10126
10127 /* End of array. */
10128 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10129
10130 /* Register this new converter */
10131 service_keywords_register(akl);
10132
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010133 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010134
10135 alloc_error:
10136 release_hlua_function(fcn);
10137 ha_free(&akl);
10138 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10139 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010140}
10141
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010142/* This function initialises Lua cli handler. It copies the
10143 * arguments in the Lua stack and create channel IO objects.
10144 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010145static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010146{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010147 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010148 struct hlua *hlua;
10149 struct hlua_function *fcn;
10150 int i;
10151 const char *error;
10152
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010153 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010154 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010155
Willy Tarreaubafbe012017-11-24 17:34:44 +010010156 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010157 if (!hlua) {
10158 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010159 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010160 }
10161 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010162 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010163
10164 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010165 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010166 * applet_http. It is absolutely compatible.
10167 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010168 ctx->task = task_new_here();
10169 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010170 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010171 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010172 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010173 ctx->task->nice = 0;
10174 ctx->task->context = appctx;
10175 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010176
10177 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010178 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010179 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010180 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010181 }
10182
10183 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010184 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010185 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10186 error = lua_tostring(hlua->T, -1);
10187 else
10188 error = "critical error";
10189 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10190 goto error;
10191 }
10192
10193 /* Check stack available size. */
10194 if (!lua_checkstack(hlua->T, 2)) {
10195 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10196 goto error;
10197 }
10198
10199 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010200 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010201
10202 /* Once the arguments parsed, the CLI is like an AppletTCP,
10203 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010204 */
10205 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10206 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10207 goto error;
10208 }
10209 hlua->nargs = 1;
10210
10211 /* push keywords in the stack. */
10212 for (i = 0; *args[i]; i++) {
10213 /* Check stack available size. */
10214 if (!lua_checkstack(hlua->T, 1)) {
10215 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10216 goto error;
10217 }
10218 lua_pushstring(hlua->T, args[i]);
10219 hlua->nargs++;
10220 }
10221
10222 /* We must initialize the execution timeouts. */
10223 hlua->max_time = hlua_timeout_session;
10224
10225 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010226 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010227
10228 /* It's ok */
10229 return 0;
10230
10231 /* It's not ok. */
10232error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010233 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010234 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010235 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010236 return 1;
10237}
10238
10239static int hlua_cli_io_handler_fct(struct appctx *appctx)
10240{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010241 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010242 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010243 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010244 struct hlua_function *fcn;
10245
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010246 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010247 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010248 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010249
10250 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010251 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010252 return 1;
10253
10254 /* Execute the function. */
10255 switch (hlua_ctx_resume(hlua, 1)) {
10256
10257 /* finished. */
10258 case HLUA_E_OK:
10259 return 1;
10260
10261 /* yield. */
10262 case HLUA_E_AGAIN:
10263 /* We want write. */
10264 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010265 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010266 /* Set the timeout. */
10267 if (hlua->wake_time != TICK_ETERNITY)
10268 task_schedule(hlua->task, hlua->wake_time);
10269 return 0;
10270
10271 /* finished with error. */
10272 case HLUA_E_ERRMSG:
10273 /* Display log. */
10274 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10275 fcn->name, lua_tostring(hlua->T, -1));
10276 lua_pop(hlua->T, 1);
10277 return 1;
10278
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010279 case HLUA_E_ETMOUT:
10280 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10281 fcn->name);
10282 return 1;
10283
10284 case HLUA_E_NOMEM:
10285 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10286 fcn->name);
10287 return 1;
10288
10289 case HLUA_E_YIELD: /* unexpected */
10290 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10291 fcn->name);
10292 return 1;
10293
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010294 case HLUA_E_ERR:
10295 /* Display log. */
10296 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10297 fcn->name);
10298 return 1;
10299
10300 default:
10301 return 1;
10302 }
10303
10304 return 1;
10305}
10306
10307static void hlua_cli_io_release_fct(struct appctx *appctx)
10308{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010309 struct hlua_cli_ctx *ctx = appctx->svcctx;
10310
10311 hlua_ctx_destroy(ctx->hlua);
10312 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010313}
10314
10315/* This function is an LUA binding used for registering
10316 * new keywords in the cli. It expects a list of keywords
10317 * which are the "path". It is limited to 5 keywords. A
10318 * description of the command, a function to be executed
10319 * for the parsing and a function for io handlers.
10320 */
10321__LJMP static int hlua_register_cli(lua_State *L)
10322{
10323 struct cli_kw_list *cli_kws;
10324 const char *message;
10325 int ref_io;
10326 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010327 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010328 int index;
10329 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010330 struct buffer *trash;
10331 const char *kw[5];
10332 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010333 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010334
10335 MAY_LJMP(check_args(L, 3, "register_cli"));
10336
10337 /* First argument : an array of maximum 5 keywords. */
10338 if (!lua_istable(L, 1))
10339 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10340
10341 /* Second argument : string with contextual message. */
10342 message = MAY_LJMP(luaL_checkstring(L, 2));
10343
10344 /* Third and fourth argument : lua function. */
10345 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10346
Thierry Fournierf67442e2020-11-28 20:41:07 +010010347 /* Check for CLI service already registered */
10348 trash = get_trash_chunk();
10349 index = 0;
10350 lua_pushnil(L);
10351 memset(kw, 0, sizeof(kw));
10352 while (lua_next(L, 1) != 0) {
10353 if (index >= CLI_PREFIX_KW_NB)
10354 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10355 if (lua_type(L, -1) != LUA_TSTRING)
10356 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10357 kw[index] = lua_tostring(L, -1);
10358 if (index == 0)
10359 chunk_printf(trash, "%s", kw[index]);
10360 else
10361 chunk_appendf(trash, " %s", kw[index]);
10362 index++;
10363 lua_pop(L, 1);
10364 }
10365 cli_kw = cli_find_kw_exact((char **)kw);
10366 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010367 fcn = cli_kw->private;
10368 if (fcn->function_ref[hlua_state_id] != -1) {
10369 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10370 "This will become a hard error in version 2.5.\n", trash->area);
10371 }
10372 fcn->function_ref[hlua_state_id] = ref_io;
10373 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010374 }
10375
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010376 /* Allocate and fill the sample fetch keyword struct. */
10377 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010378 if (!cli_kws) {
10379 errmsg = "Lua out of memory error.";
10380 goto error;
10381 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010382 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010383 if (!fcn) {
10384 errmsg = "Lua out of memory error.";
10385 goto error;
10386 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010387
10388 /* Fill path. */
10389 index = 0;
10390 lua_pushnil(L);
10391 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010392 if (index >= 5) {
10393 errmsg = "1st argument must be a table with a maximum of 5 entries";
10394 goto error;
10395 }
10396 if (lua_type(L, -1) != LUA_TSTRING) {
10397 errmsg = "1st argument must be a table filled with strings";
10398 goto error;
10399 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010400 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010401 if (!cli_kws->kw[0].str_kw[index]) {
10402 errmsg = "Lua out of memory error.";
10403 goto error;
10404 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010405 index++;
10406 lua_pop(L, 1);
10407 }
10408
10409 /* Copy help message. */
10410 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010411 if (!cli_kws->kw[0].usage) {
10412 errmsg = "Lua out of memory error.";
10413 goto error;
10414 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010415
10416 /* Fill fcn io handler. */
10417 len = strlen("<lua.cli>") + 1;
10418 for (i = 0; i < index; i++)
10419 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10420 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010421 if (!fcn->name) {
10422 errmsg = "Lua out of memory error.";
10423 goto error;
10424 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010425 strncat((char *)fcn->name, "<lua.cli", len);
10426 for (i = 0; i < index; i++) {
10427 strncat((char *)fcn->name, ".", len);
10428 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10429 }
10430 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010431 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010432
10433 /* Fill last entries. */
10434 cli_kws->kw[0].private = fcn;
10435 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10436 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10437 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10438
10439 /* Register this new converter */
10440 cli_register_kw(cli_kws);
10441
10442 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010443
10444 error:
10445 release_hlua_function(fcn);
10446 if (cli_kws) {
10447 for (i = 0; i < index; i++)
10448 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10449 ha_free((char **)&(cli_kws->kw[0].usage));
10450 }
10451 ha_free(&cli_kws);
10452 WILL_LJMP(luaL_error(L, errmsg));
10453 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010454}
10455
Christopher Faulet69c581a2021-05-31 08:54:04 +020010456static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10457{
10458 struct hlua_flt_config *conf = fconf->conf;
10459 lua_State *L;
10460 int error, pos, state_id, flt_ref;
10461
10462 state_id = reg_flt_to_stack_id(conf->reg);
10463 L = hlua_states[state_id];
10464 pos = lua_gettop(L);
10465
10466 /* The filter parsing function */
10467 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10468
10469 /* Push the filter class on the stack and resolve all callbacks */
10470 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10471
10472 /* Duplicate the filter class so each filter will have its own copy */
10473 lua_newtable(L);
10474 lua_pushnil(L);
10475
10476 while (lua_next(L, pos+2)) {
10477 lua_pushvalue(L, -2);
10478 lua_insert(L, -2);
10479 lua_settable(L, -4);
10480 }
10481 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10482
10483 /* Remove the original lua filter class from the stack */
10484 lua_pop(L, 1);
10485
10486 /* Push the copy on the stack */
10487 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10488
10489 /* extra args are pushed in a table */
10490 lua_newtable(L);
10491 for (pos = 0; conf->args[pos]; pos++) {
10492 /* Check stack available size. */
10493 if (!lua_checkstack(L, 1)) {
10494 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10495 goto error;
10496 }
10497 lua_pushstring(L, conf->args[pos]);
10498 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10499 }
10500
10501 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10502 switch (error) {
10503 case LUA_OK:
10504 /* replace the filter ref */
10505 conf->ref[state_id] = flt_ref;
10506 break;
10507 case LUA_ERRRUN:
10508 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10509 goto error;
10510 case LUA_ERRMEM:
10511 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10512 goto error;
10513 case LUA_ERRERR:
10514 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10515 goto error;
10516#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10517 case LUA_ERRGCMM:
10518 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10519 goto error;
10520#endif
10521 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010522 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010523 goto error;
10524 }
10525
10526 lua_settop(L, 0);
10527 return 0;
10528
10529 error:
10530 lua_settop(L, 0);
10531 return -1;
10532}
10533
10534static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10535{
10536 struct hlua_flt_config *conf = fconf->conf;
10537 lua_State *L;
10538 int state_id;
10539
10540 if (!conf)
10541 return;
10542
10543 state_id = reg_flt_to_stack_id(conf->reg);
10544 L = hlua_states[state_id];
10545 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10546}
10547
10548static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10549{
10550 struct hlua_flt_config *conf = fconf->conf;
10551 int state_id = reg_flt_to_stack_id(conf->reg);
10552
10553 /* Rely on per-thread init for global scripts */
10554 if (!state_id)
10555 return hlua_filter_init_per_thread(px, fconf);
10556 return 0;
10557}
10558
10559static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10560{
10561
10562 if (fconf->conf) {
10563 struct hlua_flt_config *conf = fconf->conf;
10564 int state_id = reg_flt_to_stack_id(conf->reg);
10565 int pos;
10566
10567 /* Rely on per-thread deinit for global scripts */
10568 if (!state_id)
10569 hlua_filter_deinit_per_thread(px, fconf);
10570
10571 for (pos = 0; conf->args[pos]; pos++)
10572 free(conf->args[pos]);
10573 free(conf->args);
10574 }
10575 ha_free(&fconf->conf);
10576 ha_free((char **)&fconf->id);
10577 ha_free(&fconf->ops);
10578}
10579
10580static int hlua_filter_new(struct stream *s, struct filter *filter)
10581{
10582 struct hlua_flt_config *conf = FLT_CONF(filter);
10583 struct hlua_flt_ctx *flt_ctx = NULL;
10584 int ret = 1;
10585
10586 /* In the execution wrappers linked with a stream, the
10587 * Lua context can be not initialized. This behavior
10588 * permits to save performances because a systematic
10589 * Lua initialization cause 5% performances loss.
10590 */
10591 if (!s->hlua) {
10592 struct hlua *hlua;
10593
10594 hlua = pool_alloc(pool_head_hlua);
10595 if (!hlua) {
10596 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10597 conf->reg->name);
10598 ret = 0;
10599 goto end;
10600 }
10601 HLUA_INIT(hlua);
10602 s->hlua = hlua;
10603 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10604 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10605 conf->reg->name);
10606 ret = 0;
10607 goto end;
10608 }
10609 }
10610
10611 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10612 if (!flt_ctx) {
10613 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10614 conf->reg->name);
10615 ret = 0;
10616 goto end;
10617 }
10618 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10619 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10620 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10621 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10622 conf->reg->name);
10623 ret = 0;
10624 goto end;
10625 }
10626 HLUA_INIT(flt_ctx->hlua[0]);
10627 HLUA_INIT(flt_ctx->hlua[1]);
10628 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10629 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10630 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10631 conf->reg->name);
10632 ret = 0;
10633 goto end;
10634 }
10635
10636 if (!HLUA_IS_RUNNING(s->hlua)) {
10637 /* The following Lua calls can fail. */
10638 if (!SET_SAFE_LJMP(s->hlua)) {
10639 const char *error;
10640
10641 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10642 error = lua_tostring(s->hlua->T, -1);
10643 else
10644 error = "critical error";
10645 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10646 ret = 0;
10647 goto end;
10648 }
10649
10650 /* Check stack size. */
10651 if (!lua_checkstack(s->hlua->T, 1)) {
10652 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010653 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010654 ret = 0;
10655 goto end;
10656 }
10657
10658 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10659 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10660 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10661 conf->reg->name);
10662 RESET_SAFE_LJMP(s->hlua);
10663 ret = 0;
10664 goto end;
10665 }
10666 lua_insert(s->hlua->T, -2);
10667
10668 /* Push the copy on the stack */
10669 s->hlua->nargs = 1;
10670
10671 /* We must initialize the execution timeouts. */
10672 s->hlua->max_time = hlua_timeout_session;
10673
10674 /* At this point the execution is safe. */
10675 RESET_SAFE_LJMP(s->hlua);
10676 }
10677
10678 switch (hlua_ctx_resume(s->hlua, 0)) {
10679 case HLUA_E_OK:
10680 /* Nothing returned or not a table, ignore the filter for current stream */
10681 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10682 ret = 0;
10683 goto end;
10684 }
10685
10686 /* Attached the filter pointer to the ctx */
10687 lua_pushstring(s->hlua->T, "__filter");
10688 lua_pushlightuserdata(s->hlua->T, filter);
10689 lua_settable(s->hlua->T, -3);
10690
10691 /* Save a ref on the filter ctx */
10692 lua_pushvalue(s->hlua->T, 1);
10693 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10694 filter->ctx = flt_ctx;
10695 break;
10696 case HLUA_E_ERRMSG:
10697 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10698 ret = -1;
10699 goto end;
10700 case HLUA_E_ETMOUT:
10701 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10702 ret = 0;
10703 goto end;
10704 case HLUA_E_NOMEM:
10705 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10706 ret = 0;
10707 goto end;
10708 case HLUA_E_AGAIN:
10709 case HLUA_E_YIELD:
10710 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10711 " are not allowed from 'new' function.\n", conf->reg->name);
10712 ret = 0;
10713 goto end;
10714 case HLUA_E_ERR:
10715 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10716 ret = 0;
10717 goto end;
10718 default:
10719 ret = 0;
10720 goto end;
10721 }
10722
10723 end:
10724 if (s->hlua)
10725 lua_settop(s->hlua->T, 0);
10726 if (ret <= 0) {
10727 if (flt_ctx) {
10728 hlua_ctx_destroy(flt_ctx->hlua[0]);
10729 hlua_ctx_destroy(flt_ctx->hlua[1]);
10730 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10731 }
10732 }
10733 return ret;
10734}
10735
10736static void hlua_filter_delete(struct stream *s, struct filter *filter)
10737{
10738 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10739
10740 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10741 hlua_ctx_destroy(flt_ctx->hlua[0]);
10742 hlua_ctx_destroy(flt_ctx->hlua[1]);
10743 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10744 filter->ctx = NULL;
10745}
10746
Christopher Faulet9f55a502020-02-25 15:21:02 +010010747static int hlua_filter_from_payload(struct filter *filter)
10748{
10749 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10750
10751 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10752}
10753
Christopher Fauletc404f112020-02-26 15:03:09 +010010754static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10755 int dir, unsigned int flags)
10756{
10757 struct hlua *flt_hlua;
10758 struct hlua_flt_config *conf = FLT_CONF(filter);
10759 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10760 unsigned int hflags = HLUA_TXN_FLT_CTX;
10761 int ret = 1;
10762
10763 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10764 if (!flt_hlua)
10765 goto end;
10766
10767 if (!HLUA_IS_RUNNING(flt_hlua)) {
10768 int extra_idx = lua_gettop(flt_hlua->T);
10769
10770 /* The following Lua calls can fail. */
10771 if (!SET_SAFE_LJMP(flt_hlua)) {
10772 const char *error;
10773
10774 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10775 error = lua_tostring(flt_hlua->T, -1);
10776 else
10777 error = "critical error";
10778 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10779 goto end;
10780 }
10781
10782 /* Check stack size. */
10783 if (!lua_checkstack(flt_hlua->T, 3)) {
10784 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10785 RESET_SAFE_LJMP(flt_hlua);
10786 goto end;
10787 }
10788
10789 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10790 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10791 RESET_SAFE_LJMP(flt_hlua);
10792 goto end;
10793 }
10794 lua_insert(flt_hlua->T, -2);
10795
10796 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10797 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10798 RESET_SAFE_LJMP(flt_hlua);
10799 goto end;
10800 }
10801 flt_hlua->nargs = 2;
10802
10803 if (flags & HLUA_FLT_CB_ARG_CHN) {
10804 if (dir == SMP_OPT_DIR_REQ)
10805 lua_getfield(flt_hlua->T, -1, "req");
10806 else
10807 lua_getfield(flt_hlua->T, -1, "res");
10808 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10809 lua_pushstring(flt_hlua->T, "__filter");
10810 lua_pushlightuserdata(flt_hlua->T, filter);
10811 lua_settable(flt_hlua->T, -3);
10812 }
10813 flt_hlua->nargs++;
10814 }
10815 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010816 if (dir == SMP_OPT_DIR_REQ)
10817 lua_getfield(flt_hlua->T, -1, "http_req");
10818 else
10819 lua_getfield(flt_hlua->T, -1, "http_res");
10820 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10821 lua_pushstring(flt_hlua->T, "__filter");
10822 lua_pushlightuserdata(flt_hlua->T, filter);
10823 lua_settable(flt_hlua->T, -3);
10824 }
10825 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010826 }
10827
10828 /* Check stack size. */
10829 if (!lua_checkstack(flt_hlua->T, 1)) {
10830 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10831 RESET_SAFE_LJMP(flt_hlua);
10832 goto end;
10833 }
10834
10835 while (extra_idx--) {
10836 lua_pushvalue(flt_hlua->T, 1);
10837 lua_remove(flt_hlua->T, 1);
10838 flt_hlua->nargs++;
10839 }
10840
10841 /* We must initialize the execution timeouts. */
10842 flt_hlua->max_time = hlua_timeout_session;
10843
10844 /* At this point the execution is safe. */
10845 RESET_SAFE_LJMP(flt_hlua);
10846 }
10847
10848 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10849 case HLUA_E_OK:
10850 /* Catch the return value if it required */
10851 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10852 ret = lua_tointeger(flt_hlua->T, -1);
10853 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10854 }
10855
10856 /* Set timeout in the required channel. */
10857 if (flt_hlua->wake_time != TICK_ETERNITY) {
10858 if (dir == SMP_OPT_DIR_REQ)
10859 s->req.analyse_exp = flt_hlua->wake_time;
10860 else
10861 s->res.analyse_exp = flt_hlua->wake_time;
10862 }
10863 break;
10864 case HLUA_E_AGAIN:
10865 /* Set timeout in the required channel. */
10866 if (flt_hlua->wake_time != TICK_ETERNITY) {
10867 if (dir == SMP_OPT_DIR_REQ)
10868 s->req.analyse_exp = flt_hlua->wake_time;
10869 else
10870 s->res.analyse_exp = flt_hlua->wake_time;
10871 }
10872 /* Some actions can be wake up when a "write" event
10873 * is detected on a response channel. This is useful
10874 * only for actions targeted on the requests.
10875 */
10876 if (HLUA_IS_WAKERESWR(flt_hlua))
10877 s->res.flags |= CF_WAKE_WRITE;
10878 if (HLUA_IS_WAKEREQWR(flt_hlua))
10879 s->req.flags |= CF_WAKE_WRITE;
10880 ret = 0;
10881 goto end;
10882 case HLUA_E_ERRMSG:
10883 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10884 ret = -1;
10885 goto end;
10886 case HLUA_E_ETMOUT:
10887 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10888 goto end;
10889 case HLUA_E_NOMEM:
10890 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10891 goto end;
10892 case HLUA_E_YIELD:
10893 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10894 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10895 goto end;
10896 case HLUA_E_ERR:
10897 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10898 goto end;
10899 default:
10900 goto end;
10901 }
10902
10903
10904 end:
10905 return ret;
10906}
10907
10908static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10909{
10910 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10911
10912 flt_ctx->flags = 0;
10913 return hlua_filter_callback(s, filter, "start_analyze",
10914 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10915 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10916}
10917
10918static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10919{
10920 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10921
10922 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10923 return hlua_filter_callback(s, filter, "end_analyze",
10924 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10925 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10926}
10927
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010928static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10929{
10930 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10931
10932 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10933 return hlua_filter_callback(s, filter, "http_headers",
10934 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10935 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10936}
10937
10938static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10939 unsigned int offset, unsigned int len)
10940{
10941 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10942 struct hlua *flt_hlua;
10943 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10944 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10945 int ret;
10946
10947 flt_hlua = flt_ctx->hlua[idx];
10948 flt_ctx->cur_off[idx] = offset;
10949 flt_ctx->cur_len[idx] = len;
10950 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10951 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10952 if (ret != -1) {
10953 ret = flt_ctx->cur_len[idx];
10954 if (lua_gettop(flt_hlua->T) > 0) {
10955 ret = lua_tointeger(flt_hlua->T, -1);
10956 if (ret > flt_ctx->cur_len[idx])
10957 ret = flt_ctx->cur_len[idx];
10958 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10959 }
10960 }
10961 return ret;
10962}
10963
10964static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10965{
10966 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10967
10968 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10969 return hlua_filter_callback(s, filter, "http_end",
10970 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10971 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10972}
10973
Christopher Fauletc404f112020-02-26 15:03:09 +010010974static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10975 unsigned int offset, unsigned int len)
10976{
10977 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10978 struct hlua *flt_hlua;
10979 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10980 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10981 int ret;
10982
10983 flt_hlua = flt_ctx->hlua[idx];
10984 flt_ctx->cur_off[idx] = offset;
10985 flt_ctx->cur_len[idx] = len;
10986 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10987 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10988 if (ret != -1) {
10989 ret = flt_ctx->cur_len[idx];
10990 if (lua_gettop(flt_hlua->T) > 0) {
10991 ret = lua_tointeger(flt_hlua->T, -1);
10992 if (ret > flt_ctx->cur_len[idx])
10993 ret = flt_ctx->cur_len[idx];
10994 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10995 }
10996 }
10997 return ret;
10998}
10999
Christopher Faulet69c581a2021-05-31 08:54:04 +020011000static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11001 struct flt_conf *fconf, char **err, void *private)
11002{
11003 struct hlua_reg_filter *reg_flt = private;
11004 lua_State *L;
11005 struct hlua_flt_config *conf = NULL;
11006 const char *flt_id = NULL;
11007 int state_id, pos, flt_flags = 0;
11008 struct flt_ops *hlua_flt_ops = NULL;
11009
11010 state_id = reg_flt_to_stack_id(reg_flt);
11011 L = hlua_states[state_id];
11012
11013 /* Initialize the filter ops with default callbacks */
11014 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011015 if (!hlua_flt_ops)
11016 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011017 hlua_flt_ops->init = hlua_filter_init;
11018 hlua_flt_ops->deinit = hlua_filter_deinit;
11019 if (state_id) {
11020 /* Set per-thread callback if script is loaded per-thread */
11021 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11022 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11023 }
11024 hlua_flt_ops->attach = hlua_filter_new;
11025 hlua_flt_ops->detach = hlua_filter_delete;
11026
11027 /* Push the filter class on the stack and resolve all callbacks */
11028 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11029
Christopher Fauletc404f112020-02-26 15:03:09 +010011030 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11031 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11032 lua_pop(L, 1);
11033 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11034 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11035 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011036 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11037 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11038 lua_pop(L, 1);
11039 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11040 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11041 lua_pop(L, 1);
11042 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11043 hlua_flt_ops->http_end = hlua_filter_http_end;
11044 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011045 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11046 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11047 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011048
11049 /* Get id and flags of the filter class */
11050 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11051 flt_id = lua_tostring(L, -1);
11052 lua_pop(L, 1);
11053 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11054 flt_flags = lua_tointeger(L, -1);
11055 lua_pop(L, 1);
11056
11057 /* Create the filter config */
11058 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011059 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011060 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011061 conf->reg = reg_flt;
11062
11063 /* duplicate args */
11064 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11065 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011066 if (!conf->args)
11067 goto error;
11068 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011069 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011070 if (!conf->args[pos])
11071 goto error;
11072 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011073 conf->args[pos] = NULL;
11074 *cur_arg += pos + 1;
11075
Christopher Fauletc86bb872021-08-13 08:33:57 +020011076 if (flt_id) {
11077 fconf->id = strdup(flt_id);
11078 if (!fconf->id)
11079 goto error;
11080 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011081 fconf->flags = flt_flags;
11082 fconf->conf = conf;
11083 fconf->ops = hlua_flt_ops;
11084
11085 lua_settop(L, 0);
11086 return 0;
11087
11088 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011089 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011090 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011091 if (conf && conf->args) {
11092 for (pos = 0; conf->args[pos]; pos++)
11093 free(conf->args[pos]);
11094 free(conf->args);
11095 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011096 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011097 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011098 lua_settop(L, 0);
11099 return -1;
11100}
11101
Christopher Fauletc404f112020-02-26 15:03:09 +010011102__LJMP static int hlua_register_data_filter(lua_State *L)
11103{
11104 struct filter *filter;
11105 struct channel *chn;
11106
11107 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11108 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11109 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11110
11111 lua_getfield(L, 1, "__filter");
11112 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11113 filter = lua_touserdata (L, -1);
11114 lua_pop(L, 1);
11115
11116 register_data_filter(chn_strm(chn), chn, filter);
11117 return 1;
11118}
11119
11120__LJMP static int hlua_unregister_data_filter(lua_State *L)
11121{
11122 struct filter *filter;
11123 struct channel *chn;
11124
11125 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11126 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11127 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11128
11129 lua_getfield(L, 1, "__filter");
11130 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11131 filter = lua_touserdata (L, -1);
11132 lua_pop(L, 1);
11133
11134 unregister_data_filter(chn_strm(chn), chn, filter);
11135 return 1;
11136}
11137
Christopher Faulet69c581a2021-05-31 08:54:04 +020011138/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011139 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011140 * parse configuration arguments.
11141 */
11142__LJMP static int hlua_register_filter(lua_State *L)
11143{
11144 struct buffer *trash;
11145 struct flt_kw_list *fkl;
11146 struct flt_kw *fkw;
11147 const char *name;
11148 struct hlua_reg_filter *reg_flt= NULL;
11149 int flt_ref, fun_ref;
11150 int len;
11151
11152 MAY_LJMP(check_args(L, 3, "register_filter"));
11153
11154 /* First argument : filter name. */
11155 name = MAY_LJMP(luaL_checkstring(L, 1));
11156
11157 /* Second argument : The filter class */
11158 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11159
11160 /* Third argument : lua function. */
11161 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11162
11163 trash = get_trash_chunk();
11164 chunk_printf(trash, "lua.%s", name);
11165 fkw = flt_find_kw(trash->area);
11166 if (fkw != NULL) {
11167 reg_flt = fkw->private;
11168 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11169 ha_warning("Trying to register filter 'lua.%s' more than once. "
11170 "This will become a hard error in version 2.5.\n", name);
11171 }
11172 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11173 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11174 return 0;
11175 }
11176
11177 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11178 if (!fkl)
11179 goto alloc_error;
11180 fkl->scope = "HLUA";
11181
11182 reg_flt = new_hlua_reg_filter(name);
11183 if (!reg_flt)
11184 goto alloc_error;
11185
11186 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11187 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11188
11189 /* The filter keyword */
11190 len = strlen("lua.") + strlen(name) + 1;
11191 fkl->kw[0].kw = calloc(1, len);
11192 if (!fkl->kw[0].kw)
11193 goto alloc_error;
11194
11195 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11196
11197 fkl->kw[0].parse = hlua_filter_parse_fct;
11198 fkl->kw[0].private = reg_flt;
11199 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11200
11201 /* Register this new filter */
11202 flt_register_keywords(fkl);
11203
11204 return 0;
11205
11206 alloc_error:
11207 release_hlua_reg_filter(reg_flt);
11208 ha_free(&fkl);
11209 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11210 return 0; /* Never reached */
11211}
11212
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011213static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011214 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011215 char **err, unsigned int *timeout)
11216{
11217 const char *error;
11218
11219 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011220 if (error == PARSE_TIME_OVER) {
11221 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11222 args[1], args[0]);
11223 return -1;
11224 }
11225 else if (error == PARSE_TIME_UNDER) {
11226 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11227 args[1], args[0]);
11228 return -1;
11229 }
11230 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011231 memprintf(err, "%s: invalid timeout", args[0]);
11232 return -1;
11233 }
11234 return 0;
11235}
11236
11237static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011238 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011239 char **err)
11240{
11241 return hlua_read_timeout(args, section_type, curpx, defpx,
11242 file, line, err, &hlua_timeout_session);
11243}
11244
11245static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011246 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011247 char **err)
11248{
11249 return hlua_read_timeout(args, section_type, curpx, defpx,
11250 file, line, err, &hlua_timeout_task);
11251}
11252
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011253static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011254 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011255 char **err)
11256{
11257 return hlua_read_timeout(args, section_type, curpx, defpx,
11258 file, line, err, &hlua_timeout_applet);
11259}
11260
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011261static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011262 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011263 char **err)
11264{
11265 char *error;
11266
11267 hlua_nb_instruction = strtoll(args[1], &error, 10);
11268 if (*error != '\0') {
11269 memprintf(err, "%s: invalid number", args[0]);
11270 return -1;
11271 }
11272 return 0;
11273}
11274
Willy Tarreau32f61e22015-03-18 17:54:59 +010011275static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011276 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011277 char **err)
11278{
11279 char *error;
11280
11281 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011282 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011283 return -1;
11284 }
11285 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11286 if (*error != '\0') {
11287 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11288 return -1;
11289 }
11290 return 0;
11291}
11292
11293
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011294/* This function is called by the main configuration key "lua-load". It loads and
11295 * execute an lua file during the parsing of the HAProxy configuration file. It is
11296 * the main lua entry point.
11297 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011298 * This function runs with the HAProxy keywords API. It returns -1 if an error
11299 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011300 *
11301 * In some error case, LUA set an error message in top of the stack. This function
11302 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011303 *
11304 * This function can fail with an abort() due to an Lua critical error.
11305 * We are in the configuration parsing process of HAProxy, this abort() is
11306 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011307 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011308static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011309{
11310 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011311 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011312
11313 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011314 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011315 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011316 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011317 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011318 return -1;
11319 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011320
11321 /* Push args in the Lua stack, except the first one which is the filename */
11322 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011323 /* Check stack size. */
11324 if (!lua_checkstack(L, 1)) {
11325 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11326 return -1;
11327 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011328 lua_pushstring(L, args[nargs]);
11329 }
11330 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011331
11332 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011333 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011334 switch (error) {
11335 case LUA_OK:
11336 break;
11337 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011338 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011339 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011340 return -1;
11341 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011342 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011343 return -1;
11344 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011345 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011346 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011347 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011348#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011349 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011350 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011351 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011352 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011353#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011354 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011355 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011356 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011357 return -1;
11358 }
11359
11360 return 0;
11361}
11362
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011363static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011364 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011365 char **err)
11366{
11367 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011368 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011369 return -1;
11370 }
11371
Thierry Fournier59f11be2020-11-29 00:37:41 +010011372 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011373 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011374 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011375 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011376}
11377
Thierry Fournier59f11be2020-11-29 00:37:41 +010011378static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011379 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011380 char **err)
11381{
11382 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011383 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011384
11385 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011386 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011387 return -1;
11388 }
11389
11390 if (per_thread_load == NULL) {
11391 /* allocate the first entry large enough to store the final NULL */
11392 per_thread_load = calloc(1, sizeof(*per_thread_load));
11393 if (per_thread_load == NULL) {
11394 memprintf(err, "out of memory error");
11395 return -1;
11396 }
11397 }
11398
11399 /* count used entries */
11400 for (len = 0; per_thread_load[len] != NULL; len++)
11401 ;
11402
11403 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11404 if (per_thread_load == NULL) {
11405 memprintf(err, "out of memory error");
11406 return -1;
11407 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011408 per_thread_load[len + 1] = NULL;
11409
Thierry Fournierae6b5682022-09-19 09:04:16 +020011410 /* count args excepting the first, allocate array and copy args */
11411 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011412 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011413 if (per_thread_load[len] == NULL) {
11414 memprintf(err, "out of memory error");
11415 return -1;
11416 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011417 for (i = 1; *(args[i]) != 0; i++) {
11418 per_thread_load[len][i - 1] = strdup(args[i]);
11419 if (per_thread_load[len][i - 1] == NULL) {
11420 memprintf(err, "out of memory error");
11421 return -1;
11422 }
11423 }
11424 per_thread_load[len][i - 1] = strdup("");
11425 if (per_thread_load[len][i - 1] == NULL) {
11426 memprintf(err, "out of memory error");
11427 return -1;
11428 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011429
11430 /* loading for thread 1 only */
11431 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011432 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011433 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011434}
11435
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011436/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11437 * in the given <ctx>.
11438 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011439static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011440{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011441 lua_getglobal(L, "package"); /* push package variable */
11442 lua_pushstring(L, path); /* push given path */
11443 lua_pushstring(L, ";"); /* push semicolon */
11444 lua_getfield(L, -3, type); /* push old path */
11445 lua_concat(L, 3); /* concatenate to new path */
11446 lua_setfield(L, -2, type); /* store new path */
11447 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011448
11449 return 0;
11450}
11451
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011452static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011453 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011454 char **err)
11455{
11456 char *path;
11457 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011458 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011459 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011460
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011461 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011462 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011463 }
11464
11465 if (!(*args[1])) {
11466 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011467 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011468 }
11469 path = args[1];
11470
11471 if (*args[2]) {
11472 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11473 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011474 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011475 }
11476 type = args[2];
11477 }
11478
Thierry Fournier59f11be2020-11-29 00:37:41 +010011479 p = calloc(1, sizeof(*p));
11480 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011481 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011482 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011483 }
11484 p->path = strdup(path);
11485 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011486 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011487 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011488 }
11489 p->type = strdup(type);
11490 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011491 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011492 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011493 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011494 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011495
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011496 /* Handle the global state and the per-thread state for the first
11497 * thread. The remaining threads will be initialized based on
11498 * prepend_path_list.
11499 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011500 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011501 lua_State *L = hlua_states[i];
11502 const char *error;
11503
11504 if (setjmp(safe_ljmp_env) != 0) {
11505 lua_atpanic(L, hlua_panic_safe);
11506 if (lua_type(L, -1) == LUA_TSTRING)
11507 error = lua_tostring(L, -1);
11508 else
11509 error = "critical error";
11510 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11511 exit(1);
11512 } else {
11513 lua_atpanic(L, hlua_panic_ljmp);
11514 }
11515
11516 hlua_prepend_path(L, type, path);
11517
11518 lua_atpanic(L, hlua_panic_safe);
11519 }
11520
Thierry Fournier59f11be2020-11-29 00:37:41 +010011521 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011522
11523err2:
11524 free(p->type);
11525 free(p->path);
11526err:
11527 free(p);
11528 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011529}
11530
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011531/* configuration keywords declaration */
11532static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011533 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011534 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011535 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011536 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11537 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011538 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011539 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011540 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011541 { 0, NULL, NULL },
11542}};
11543
Willy Tarreau0108d902018-11-25 19:14:37 +010011544INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11545
William Lallemand52139182022-03-30 15:05:42 +020011546#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011547
William Lallemand30fcca12022-03-30 12:03:12 +020011548/*
11549 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11550 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11551 * difference is that the yield in lua and for the CLI is not handled the same
11552 * way.
11553 */
11554__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11555{
11556 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11557 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11558 struct ckch_inst *ckchi = *lua_ckchi;
11559 struct ckch_store *old_ckchs = lua_ckchs[0];
11560 struct ckch_store *new_ckchs = lua_ckchs[1];
11561 struct hlua *hlua;
11562 char *err = NULL;
11563 int y = 1;
11564
11565 hlua = hlua_gethlua(L);
11566
11567 /* get the first ckchi to copy */
11568 if (ckchi == NULL)
11569 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11570
11571 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11572 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11573 struct ckch_inst *new_inst;
11574
11575 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11576 if (y % 10 == 0) {
11577
11578 *lua_ckchi = ckchi;
11579
11580 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11581 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11582 }
11583
11584 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11585 goto error;
11586
11587 /* link the new ckch_inst to the duplicate */
11588 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11589 y++;
11590 }
11591
11592 /* The generation is finished, we can insert everything */
11593 ckch_store_replace(old_ckchs, new_ckchs);
11594
11595 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11596
11597 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11598
11599 return 0;
11600
11601error:
11602 ckch_store_free(new_ckchs);
11603 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11604 WILL_LJMP(luaL_error(L, "%s", err));
11605 free(err);
11606
11607 return 0;
11608}
11609
11610/*
11611 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11612 * from the table in parameter.
11613 *
11614 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11615 * means it does not need to have a transaction since everything is done in the
11616 * same function.
11617 *
11618 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11619 *
11620 */
11621__LJMP static int hlua_ckch_set(lua_State *L)
11622{
11623 struct hlua *hlua;
11624 struct ckch_inst **lua_ckchi;
11625 struct ckch_store **lua_ckchs;
11626 struct ckch_store *old_ckchs = NULL;
11627 struct ckch_store *new_ckchs = NULL;
11628 int errcode = 0;
11629 char *err = NULL;
11630 struct cert_exts *cert_ext = NULL;
11631 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010011632 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020011633 int ret;
11634
11635 if (lua_type(L, -1) != LUA_TTABLE)
11636 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11637
11638 hlua = hlua_gethlua(L);
11639
11640 /* FIXME: this should not return an error but should come back later */
11641 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11642 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11643
11644 ret = lua_getfield(L, -1, "filename");
11645 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011646 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011647 errcode |= ERR_ALERT | ERR_FATAL;
11648 goto end;
11649 }
11650 filename = (char *)lua_tostring(L, -1);
11651
11652
11653 /* look for the filename in the tree */
11654 old_ckchs = ckchs_lookup(filename);
11655 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011656 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011657 errcode |= ERR_ALERT | ERR_FATAL;
11658 goto end;
11659 }
11660 /* TODO: handle extra_files_noext */
11661
11662 new_ckchs = ckchs_dup(old_ckchs);
11663 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011664 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011665 errcode |= ERR_ALERT | ERR_FATAL;
11666 goto end;
11667 }
11668
William Lallemand52ddd992022-11-22 11:51:53 +010011669 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020011670
11671 /* loop on the field in the table, which have the same name as the
11672 * possible extensions of files */
11673 lua_pushnil(L);
11674 while (lua_next(L, 1)) {
11675 int i;
11676 const char *field = lua_tostring(L, -2);
11677 char *payload = (char *)lua_tostring(L, -1);
11678
11679 if (!field || strcmp(field, "filename") == 0) {
11680 lua_pop(L, 1);
11681 continue;
11682 }
11683
11684 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11685 if (strcmp(field, cert_exts[i].ext) == 0) {
11686 cert_ext = &cert_exts[i];
11687 break;
11688 }
11689 }
11690
11691 /* this is the default type, the field is not supported */
11692 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011693 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011694 errcode |= ERR_ALERT | ERR_FATAL;
11695 goto end;
11696 }
11697
11698 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010011699 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011700 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011701 errcode |= ERR_ALERT | ERR_FATAL;
11702 goto end;
11703 }
11704 lua_pop(L, 1);
11705 }
11706
11707 /* store the pointers on the lua stack */
11708 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11709 lua_ckchs[0] = old_ckchs;
11710 lua_ckchs[1] = new_ckchs;
11711 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11712 *lua_ckchi = NULL;
11713
11714 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11715 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11716
11717end:
11718 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11719
11720 if (errcode & ERR_CODE) {
11721 ckch_store_free(new_ckchs);
11722 WILL_LJMP(luaL_error(L, "%s", err));
11723 }
11724 free(err);
11725
11726 return 0;
11727}
11728
William Lallemand52139182022-03-30 15:05:42 +020011729#else
11730
11731__LJMP static int hlua_ckch_set(lua_State *L)
11732{
11733 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11734
11735 return 0;
11736}
11737#endif /* ! USE_OPENSSL */
11738
11739
11740
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011741/* This function can fail with an abort() due to an Lua critical error.
11742 * We are in the initialisation process of HAProxy, this abort() is
11743 * tolerated.
11744 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011745int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011746{
11747 struct hlua_init_function *init;
11748 const char *msg;
11749 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011750 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011751 const char *kind;
11752 const char *trace;
11753 int return_status = 1;
11754#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11755 int nres;
11756#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011757
Willy Tarreaucdb53462020-12-02 12:12:00 +010011758 /* disable memory limit checks if limit is not set */
11759 if (!hlua_global_allocator.limit)
11760 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11761
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011762 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011763 if (setjmp(safe_ljmp_env) != 0) {
11764 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011765 if (lua_type(L, -1) == LUA_TSTRING)
11766 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011767 else
11768 error = "critical error";
11769 fprintf(stderr, "Lua post-init: %s.\n", error);
11770 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011771 } else {
11772 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011773 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011774
Thierry Fournierb8cef172020-11-28 15:37:17 +010011775 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011776
Thierry Fournierc7492592020-11-28 23:57:24 +010011777 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011778 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011779
11780#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011781 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011782#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011783 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011784#endif
11785 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011786 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011787
11788 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011789 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011790 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011791
11792 case LUA_ERRERR:
11793 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011794 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011795 case LUA_ERRRUN:
11796 if (!kind)
11797 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011798 msg = lua_tostring(L, -1);
11799 lua_settop(L, 0); /* Empty the stack. */
11800 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011801 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011802 if (msg)
11803 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11804 else
11805 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11806 return_status = 0;
11807 break;
11808
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011809 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011810 /* Unknown error */
11811 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011812 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011813 case LUA_YIELD:
11814 /* yield is not configured at this step, this state doesn't happen */
11815 if (!kind)
11816 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010011817 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011818 case LUA_ERRMEM:
11819 if (!kind)
11820 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011821 lua_settop(L, 0);
11822 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011823 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011824 ha_alert("Lua init: %s: %s\n", kind, trace);
11825 return_status = 0;
11826 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011827 }
Thierry Fournier670db242020-11-28 10:49:59 +010011828 if (!return_status)
11829 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011830 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011831
11832 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011833 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011834}
11835
Thierry Fournierb8cef172020-11-28 15:37:17 +010011836int hlua_post_init()
11837{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011838 int ret;
11839 int i;
11840 int errors;
11841 char *err = NULL;
11842 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011843 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011844
Willy Tarreaub1310492021-08-30 09:35:18 +020011845#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011846 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011847 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011848 int saved_used_backed = global.ssl_used_backend;
11849 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011850 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011851 global.ssl_used_backend = saved_used_backed;
11852 }
11853#endif
11854
Thierry Fournierc7492592020-11-28 23:57:24 +010011855 /* Perform post init of common thread */
11856 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011857 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011858 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11859 if (ret == 0)
11860 return 0;
11861
11862 /* init remaining lua states and load files */
11863 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11864
11865 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011866 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011867
11868 /* Init lua state */
11869 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11870
11871 /* Load lua files */
11872 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11873 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11874 if (ret != 0) {
11875 ha_alert("Lua init: %s\n", err);
11876 return 0;
11877 }
11878 }
11879 }
11880
11881 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011882 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011883
11884 /* Execute post init for all states */
11885 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11886
11887 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011888 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011889
11890 /* run post init */
11891 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11892 if (ret == 0)
11893 return 0;
11894 }
11895
11896 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011897 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011898
11899 /* control functions registering. Each function must have:
11900 * - only the function_ref[0] set positive and all other to -1
11901 * - only the function_ref[0] set to -1 and all other positive
11902 * This ensure a same reference is not used both in shared
11903 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011904 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011905 * complicated to found for the end user.
11906 */
11907 errors = 0;
11908 list_for_each_entry(fcn, &referenced_functions, l) {
11909 ret = 0;
11910 for (i = 1; i < global.nbthread + 1; i++) {
11911 if (fcn->function_ref[i] == -1)
11912 ret--;
11913 else
11914 ret++;
11915 }
11916 if (abs(ret) != global.nbthread) {
11917 ha_alert("Lua function '%s' is not referenced in all thread. "
11918 "Expect function in all thread or in none thread.\n", fcn->name);
11919 errors++;
11920 continue;
11921 }
11922
11923 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011924 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11925 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011926 "exclusive.\n", fcn->name);
11927 errors++;
11928 }
11929 }
11930
Christopher Faulet69c581a2021-05-31 08:54:04 +020011931 /* Do the same with registered filters */
11932 list_for_each_entry(reg_flt, &referenced_filters, l) {
11933 ret = 0;
11934 for (i = 1; i < global.nbthread + 1; i++) {
11935 if (reg_flt->flt_ref[i] == -1)
11936 ret--;
11937 else
11938 ret++;
11939 }
11940 if (abs(ret) != global.nbthread) {
11941 ha_alert("Lua filter '%s' is not referenced in all thread. "
11942 "Expect function in all thread or in none thread.\n", reg_flt->name);
11943 errors++;
11944 continue;
11945 }
11946
11947 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11948 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11949 "and per-thread Lua context (through lua-load-per-thread). these two context "
11950 "exclusive.\n", fcn->name);
11951 errors++;
11952 }
11953 }
11954
11955
Thierry Fournier59f11be2020-11-29 00:37:41 +010011956 if (errors > 0)
11957 return 0;
11958
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011959 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011960 * -1 in order to have probably a segfault if someone use it
11961 */
11962 hlua_state_id = -1;
11963
11964 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011965}
11966
Willy Tarreau32f61e22015-03-18 17:54:59 +010011967/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11968 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11969 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011970 * allocation. <nsize> is the requested new size. A new allocation is
11971 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011972 * zero. This one verifies that the limits are respected but is optimized
11973 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011974 *
11975 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11976 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11977 * that and will simply allocate zero as if it were the result of malloc(0),
11978 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11979 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011980 */
11981static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11982{
11983 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011984 size_t limit, old, new;
11985
11986 /* a limit of ~0 means unlimited and boot complete, so there's no need
11987 * for accounting anymore.
11988 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011989 if (likely(~zone->limit == 0)) {
11990 if (!nsize)
11991 ha_free(&ptr);
11992 else
11993 ptr = realloc(ptr, nsize);
11994 return ptr;
11995 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011996
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011997 if (!ptr)
11998 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011999
Willy Tarreaucdb53462020-12-02 12:12:00 +010012000 /* enforce strict limits across all threads */
12001 limit = zone->limit;
12002 old = _HA_ATOMIC_LOAD(&zone->allocated);
12003 do {
12004 new = old + nsize - osize;
12005 if (unlikely(nsize && limit && new > limit))
12006 return NULL;
12007 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012008
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012009 if (!nsize)
12010 ha_free(&ptr);
12011 else
12012 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012013
12014 if (unlikely(!ptr && nsize)) // failed
12015 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12016
12017 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012018 return ptr;
12019}
12020
Thierry Fournierecb83c22020-11-28 15:49:44 +010012021/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012022 * We are in the initialisation process of HAProxy, this abort() is
12023 * tolerated.
12024 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012025lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012026{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012027 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012028 int idx;
12029 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012030 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012031 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012032 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012033 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012034 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012035 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012036
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012037 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012038 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012039
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012040 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012041 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012042 *context = NULL;
12043
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012044 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012045 * the Lua function can fail with an abort. We are in the initialisation
12046 * process of HAProxy, this abort() is tolerated.
12047 */
12048
Thierry Fournier3c539322020-11-28 16:05:05 +010012049 /* Call post initialisation function in safe environment. */
12050 if (setjmp(safe_ljmp_env) != 0) {
12051 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012052 if (lua_type(L, -1) == LUA_TSTRING)
12053 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012054 else
12055 error_msg = "critical error";
12056 fprintf(stderr, "Lua init: %s.\n", error_msg);
12057 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012058 } else {
12059 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012060 }
12061
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012062 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012063 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012064#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12065#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12066#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012067 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012068#endif
12069#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012070 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012071#endif
12072#undef HLUA_PREPEND_PATH_TOSTRING
12073#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012074
Thierry Fournier59f11be2020-11-29 00:37:41 +010012075 /* Apply configured prepend path */
12076 list_for_each_entry(pp, &prepend_path_list, l)
12077 hlua_prepend_path(L, pp->type, pp->path);
12078
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012079 /*
12080 *
12081 * Create "core" object.
12082 *
12083 */
12084
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012085 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012087
Thierry Fournierecb83c22020-11-28 15:49:44 +010012088 /* set the thread id */
12089 hlua_class_const_int(L, "thread", thread_num);
12090
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012091 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012092 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012093 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012094
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012095 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012096 hlua_class_function(L, "register_init", hlua_register_init);
12097 hlua_class_function(L, "register_task", hlua_register_task);
12098 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12099 hlua_class_function(L, "register_converters", hlua_register_converters);
12100 hlua_class_function(L, "register_action", hlua_register_action);
12101 hlua_class_function(L, "register_service", hlua_register_service);
12102 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012103 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012104 hlua_class_function(L, "yield", hlua_yield);
12105 hlua_class_function(L, "set_nice", hlua_set_nice);
12106 hlua_class_function(L, "sleep", hlua_sleep);
12107 hlua_class_function(L, "msleep", hlua_msleep);
12108 hlua_class_function(L, "add_acl", hlua_add_acl);
12109 hlua_class_function(L, "del_acl", hlua_del_acl);
12110 hlua_class_function(L, "set_map", hlua_set_map);
12111 hlua_class_function(L, "del_map", hlua_del_map);
12112 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012113 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012114 hlua_class_function(L, "log", hlua_log);
12115 hlua_class_function(L, "Debug", hlua_log_debug);
12116 hlua_class_function(L, "Info", hlua_log_info);
12117 hlua_class_function(L, "Warning", hlua_log_warning);
12118 hlua_class_function(L, "Alert", hlua_log_alert);
12119 hlua_class_function(L, "done", hlua_done);
12120 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012121
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012122 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012123
12124 /*
12125 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012126 * Create "act" object.
12127 *
12128 */
12129
12130 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012131 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012132
12133 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012134 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12135 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12136 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12137 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12138 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12139 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12140 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12141 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012142
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012143 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012144
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012145 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012146
12147 /*
12148 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012149 * Create "Filter" object.
12150 *
12151 */
12152
12153 /* This table entry is the object "filter" base. */
12154 lua_newtable(L);
12155
12156 /* push flags and constants */
12157 hlua_class_const_int(L, "CONTINUE", 1);
12158 hlua_class_const_int(L, "WAIT", 0);
12159 hlua_class_const_int(L, "ERROR", -1);
12160
12161 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12162
Christopher Fauletc404f112020-02-26 15:03:09 +010012163 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12164 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12165 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12166
Christopher Faulet69c581a2021-05-31 08:54:04 +020012167 lua_setglobal(L, "filter");
12168
12169 /*
12170 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012171 * Register class Map
12172 *
12173 */
12174
12175 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012176 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012177
12178 /* register pattern types. */
12179 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012181 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012182 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012183 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012184 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012185
12186 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012187 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012188
12189 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012190 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012191
Ilya Shipitsind4259502020-04-08 01:07:56 +050012192 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012193 lua_pushstring(L, "__index");
12194 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012195
12196 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012197 hlua_class_function(L, "lookup", hlua_map_lookup);
12198 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012199
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012201
Thierry Fournier45e78d72016-02-19 18:34:46 +010012202 /* Register previous table in the registry with reference and named entry.
12203 * The function hlua_register_metatable() pops the stack, so we
12204 * previously create a copy of the table.
12205 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012206 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12207 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012208
12209 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012210 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012211
12212 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012213 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012214
12215 /*
12216 *
William Lallemand30fcca12022-03-30 12:03:12 +020012217 * Register "CertCache" class
12218 *
12219 */
12220
12221 /* Create and fill the metatable. */
12222 lua_newtable(L);
12223 /* Register */
12224 hlua_class_function(L, "set", hlua_ckch_set);
12225 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12226
12227 /*
12228 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012229 * Register class Channel
12230 *
12231 */
12232
12233 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012234 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012235
Ilya Shipitsind4259502020-04-08 01:07:56 +050012236 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012237 lua_pushstring(L, "__index");
12238 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012239
12240 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012241 hlua_class_function(L, "data", hlua_channel_get_data);
12242 hlua_class_function(L, "line", hlua_channel_get_line);
12243 hlua_class_function(L, "set", hlua_channel_set_data);
12244 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012245 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012246 hlua_class_function(L, "prepend", hlua_channel_prepend);
12247 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012248 hlua_class_function(L, "send", hlua_channel_send);
12249 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012250 hlua_class_function(L, "input", hlua_channel_get_in_len);
12251 hlua_class_function(L, "output", hlua_channel_get_out_len);
12252 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012253 hlua_class_function(L, "is_full", hlua_channel_is_full);
12254 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012255
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012256 /* Deprecated API */
12257 hlua_class_function(L, "get", hlua_channel_get);
12258 hlua_class_function(L, "dup", hlua_channel_dup);
12259 hlua_class_function(L, "getline", hlua_channel_getline);
12260 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12261 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12262
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012263 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012264
12265 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012266 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012267
12268 /*
12269 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012270 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012271 *
12272 */
12273
12274 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012275 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012276
Ilya Shipitsind4259502020-04-08 01:07:56 +050012277 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012278 lua_pushstring(L, "__index");
12279 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012280
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012281 /* Browse existing fetches and create the associated
12282 * object method.
12283 */
12284 sf = NULL;
12285 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012286 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12287 * by an underscore.
12288 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012289 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012290 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012291 if (*p == '.' || *p == '-' || *p == '+')
12292 *p = '_';
12293
12294 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012295 lua_pushstring(L, trash.area);
12296 lua_pushlightuserdata(L, sf);
12297 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12298 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012299 }
12300
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012301 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012302
12303 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012304 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012305
12306 /*
12307 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012308 * Register class Converters
12309 *
12310 */
12311
12312 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012313 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012314
12315 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012316 lua_pushstring(L, "__index");
12317 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012318
12319 /* Browse existing converters and create the associated
12320 * object method.
12321 */
12322 sc = NULL;
12323 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012324 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12325 * by an underscore.
12326 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012327 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012328 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012329 if (*p == '.' || *p == '-' || *p == '+')
12330 *p = '_';
12331
12332 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012333 lua_pushstring(L, trash.area);
12334 lua_pushlightuserdata(L, sc);
12335 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12336 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012337 }
12338
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012339 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012340
12341 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012342 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012343
12344 /*
12345 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012346 * Register class HTTP
12347 *
12348 */
12349
12350 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012351 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012352
Ilya Shipitsind4259502020-04-08 01:07:56 +050012353 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012354 lua_pushstring(L, "__index");
12355 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012356
12357 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012358 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12359 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12360 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12361 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12362 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12363 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12364 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12365 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12366 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12367 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012368
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012369 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12370 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12371 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12372 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12373 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12374 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12375 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012376
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012377 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012378
12379 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012380 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012381
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012382 /*
12383 *
12384 * Register class HTTPMessage
12385 *
12386 */
12387
12388 /* Create and fill the metatable. */
12389 lua_newtable(L);
12390
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012391 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012392 lua_pushstring(L, "__index");
12393 lua_newtable(L);
12394
12395 /* Register Lua functions. */
12396 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12397 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12398 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12399 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12400 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12401 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12402 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12403 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12404 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12405 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12406 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12407 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12408 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12409 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12410 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12411 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12412 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12413 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12414
12415 hlua_class_function(L, "body", hlua_http_msg_get_body);
12416 hlua_class_function(L, "set", hlua_http_msg_set_data);
12417 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12418 hlua_class_function(L, "append", hlua_http_msg_append);
12419 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12420 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12421 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12422 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12423
12424 hlua_class_function(L, "send", hlua_http_msg_send);
12425 hlua_class_function(L, "forward", hlua_http_msg_forward);
12426
12427 lua_rawset(L, -3);
12428
12429 /* Register previous table in the registry with reference and named entry. */
12430 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012431
12432 /*
12433 *
12434 * Register class HTTPClient
12435 *
12436 */
12437
12438 /* Create and fill the metatable. */
12439 lua_newtable(L);
12440 lua_pushstring(L, "__index");
12441 lua_newtable(L);
12442 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012443 hlua_class_function(L, "head", hlua_httpclient_head);
12444 hlua_class_function(L, "put", hlua_httpclient_put);
12445 hlua_class_function(L, "post", hlua_httpclient_post);
12446 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012447 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012448 /* Register the garbage collector entry. */
12449 lua_pushstring(L, "__gc");
12450 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12451 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12452
William Lallemand3956c4e2021-09-21 16:25:15 +020012453
12454
12455 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012456 /*
12457 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012458 * Register class AppletTCP
12459 *
12460 */
12461
12462 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012463 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012464
Ilya Shipitsind4259502020-04-08 01:07:56 +050012465 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012466 lua_pushstring(L, "__index");
12467 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012468
12469 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012470 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12471 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12472 hlua_class_function(L, "send", hlua_applet_tcp_send);
12473 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12474 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12475 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12476 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12477 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012478
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012479 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012480
12481 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012482 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012483
12484 /*
12485 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012486 * Register class AppletHTTP
12487 *
12488 */
12489
12490 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012491 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012492
Ilya Shipitsind4259502020-04-08 01:07:56 +050012493 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012494 lua_pushstring(L, "__index");
12495 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012496
12497 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012498 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12499 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12500 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12501 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12502 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12503 hlua_class_function(L, "getline", hlua_applet_http_getline);
12504 hlua_class_function(L, "receive", hlua_applet_http_recv);
12505 hlua_class_function(L, "send", hlua_applet_http_send);
12506 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12507 hlua_class_function(L, "set_status", hlua_applet_http_status);
12508 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012509
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012510 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012511
12512 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012513 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012514
12515 /*
12516 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012517 * Register class TXN
12518 *
12519 */
12520
12521 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012522 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012523
Ilya Shipitsind4259502020-04-08 01:07:56 +050012524 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012525 lua_pushstring(L, "__index");
12526 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012527
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012528 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012529 hlua_class_function(L, "set_priv", hlua_set_priv);
12530 hlua_class_function(L, "get_priv", hlua_get_priv);
12531 hlua_class_function(L, "set_var", hlua_set_var);
12532 hlua_class_function(L, "unset_var", hlua_unset_var);
12533 hlua_class_function(L, "get_var", hlua_get_var);
12534 hlua_class_function(L, "done", hlua_txn_done);
12535 hlua_class_function(L, "reply", hlua_txn_reply_new);
12536 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12537 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12538 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12539 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12540 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12541 hlua_class_function(L, "deflog", hlua_txn_deflog);
12542 hlua_class_function(L, "log", hlua_txn_log);
12543 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12544 hlua_class_function(L, "Info", hlua_txn_log_info);
12545 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12546 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012547
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012548 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012549
12550 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012551 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012552
12553 /*
12554 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012555 * Register class reply
12556 *
12557 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012558 lua_newtable(L);
12559 lua_pushstring(L, "__index");
12560 lua_newtable(L);
12561 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12562 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12563 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12564 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12565 lua_settable(L, -3); /* Sets the __index entry. */
12566 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012567
12568
12569 /*
12570 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012571 * Register class Socket
12572 *
12573 */
12574
12575 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012576 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012577
Ilya Shipitsind4259502020-04-08 01:07:56 +050012578 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012579 lua_pushstring(L, "__index");
12580 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012581
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012582#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012583 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012584#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012585 hlua_class_function(L, "connect", hlua_socket_connect);
12586 hlua_class_function(L, "send", hlua_socket_send);
12587 hlua_class_function(L, "receive", hlua_socket_receive);
12588 hlua_class_function(L, "close", hlua_socket_close);
12589 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12590 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12591 hlua_class_function(L, "setoption", hlua_socket_setoption);
12592 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012593
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012594 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012595
12596 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012597 lua_pushstring(L, "__gc");
12598 lua_pushcclosure(L, hlua_socket_gc, 0);
12599 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012600
12601 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012602 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012603
Thierry Fournieraafc7772020-12-04 11:47:47 +010012604 lua_atpanic(L, hlua_panic_safe);
12605
12606 return L;
12607}
12608
12609void hlua_init(void) {
12610 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012611 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012612#ifdef USE_OPENSSL
12613 struct srv_kw *kw;
12614 int tmp_error;
12615 char *error;
12616 char *args[] = { /* SSL client configuration. */
12617 "ssl",
12618 "verify",
12619 "none",
12620 NULL
12621 };
12622#endif
12623
12624 /* Init post init function list head */
12625 for (i = 0; i < MAX_THREADS + 1; i++)
12626 LIST_INIT(&hlua_init_functions[i]);
12627
12628 /* Init state for common/shared lua parts */
12629 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012630 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012631 hlua_states[0] = hlua_init_state(0);
12632
12633 /* Init state 1 for thread 0. We have at least one thread. */
12634 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012635 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012636 hlua_states[1] = hlua_init_state(1);
12637
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012638 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012639 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012640 if (!socket_proxy) {
12641 fprintf(stderr, "Lua init: %s\n", errmsg);
12642 exit(1);
12643 }
12644 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012645
12646 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012647 socket_tcp = new_server(socket_proxy);
12648 if (!socket_tcp) {
12649 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12650 exit(1);
12651 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012652
12653#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012654 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012655 socket_ssl = new_server(socket_proxy);
12656 if (!socket_ssl) {
12657 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12658 exit(1);
12659 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012660
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012661 socket_ssl->use_ssl = 1;
12662 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012663
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012664 for (i = 0; args[i] != NULL; i++) {
12665 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012666 /*
12667 *
12668 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012669 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012670 * features like client certificates and ssl_verify.
12671 *
12672 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012673 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012674 if (tmp_error != 0) {
12675 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12676 abort(); /* This must be never arrives because the command line
12677 not editable by the user. */
12678 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012679 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012680 }
12681 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012682#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012683
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012684}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012685
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012686static void hlua_deinit()
12687{
Willy Tarreau186f3762020-12-04 11:48:12 +010012688 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012689 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12690
12691 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12692 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012693
12694 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12695 if (hlua_states[thr])
12696 lua_close(hlua_states[thr]);
12697 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012698
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012699 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012700
Willy Tarreau0f143af2021-03-05 10:41:48 +010012701#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012702 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012703#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012704
12705 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012706}
12707
12708REGISTER_POST_DEINIT(hlua_deinit);
12709
Willy Tarreau80713382018-11-26 10:19:54 +010012710static void hlua_register_build_options(void)
12711{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012712 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012713
Willy Tarreaubb57d942016-12-21 19:04:56 +010012714 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12715 hap_register_build_opts(ptr, 1);
12716}
Willy Tarreau80713382018-11-26 10:19:54 +010012717
12718INITCALL0(STG_REGISTER, hlua_register_build_options);