blob: 3962381abd0cb04594832dde6feb0a6af6ec9c69 [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
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100475 * error if the argument is not a "function".
476 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100477 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100478__LJMP int hlua_checkfunction(lua_State *L, int argno)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100479{
480 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100481 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100482 WILL_LJMP(luaL_argerror(L, argno, msg));
483 }
484 lua_pushvalue(L, argno);
485 return luaL_ref(L, LUA_REGISTRYINDEX);
486}
487
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100488/* Used to check an Lua table type in the stack. It creates and
489 * returns a reference of the table. This function throws an
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100490 * error if the argument is not a "table".
491 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100492 */
Aurelien DARRAGON9ee0d042023-03-20 18:36:08 +0100493__LJMP int hlua_checktable(lua_State *L, int argno)
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100494{
495 if (!lua_istable(L, argno)) {
496 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
497 WILL_LJMP(luaL_argerror(L, argno, msg));
498 }
499 lua_pushvalue(L, argno);
500 return luaL_ref(L, LUA_REGISTRYINDEX);
501}
502
Aurelien DARRAGONf8f8a2b2023-03-02 17:50:49 +0100503/* Get a reference to the object that is at the top of the stack
504 * The referenced object will be popped from the stack
505 *
506 * The function returns the reference to the object which must
507 * be cleared using hlua_unref() when no longer used
508 */
509__LJMP int hlua_ref(lua_State *L)
510{
511 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
512}
513
514/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
515 * on <L> stack
516 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
517 *
518 * When the reference is no longer used, it should be released by calling
519 * hlua_unref()
520 *
521 * <L> can be from any co-routine as long as it belongs to the same lua
522 * parent state that the one used to get the reference.
523 */
524void hlua_pushref(lua_State *L, int ref)
525{
526 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
527}
528
529/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
530 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
531 *
532 * This will allow the reference to be reused and the referred object
533 * to be garbage collected.
534 *
535 * <L> can be from any co-routine as long as it belongs to the same lua
536 * parent state that the one used to get the reference.
537 */
538void hlua_unref(lua_State *L, int ref)
539{
540 luaL_unref(L, LUA_REGISTRYINDEX, ref);
541}
542
Christopher Fauletd09cc512021-03-24 14:48:45 +0100543__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200544{
545 lua_Debug ar;
546 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200547 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200548
549 while (lua_getstack(L, level++, &ar)) {
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200550 /* Fill fields:
551 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
552 * 'l': fills in the field currentline;
553 * 'n': fills in the field name and namewhat;
554 * 't': fills in the field istailcall;
555 */
556 lua_getinfo(L, "Slnt", &ar);
557
Willy Tarreau5c143402022-06-19 17:35:53 +0200558 /* skip these empty entries, usually they come from deep C functions */
559 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
560 continue;
561
562 /* Add separator */
563 if (b_data(msg))
564 chunk_appendf(msg, "%s", sep);
565
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200566 /* Append code localisation */
567 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100568 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200569 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100570 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200571
572 /*
573 * Get function name
574 *
575 * if namewhat is no empty, name is defined.
576 * what contains "Lua" for Lua function, "C" for C function,
577 * or "main" for main code.
578 */
579 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100580 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200581
582 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100583 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200584
585 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100586 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200587
588 else /* nothing left... */
589 chunk_appendf(msg, "?");
590
591
592 /* Display tailed call */
593 if (ar.istailcall)
594 chunk_appendf(msg, " ...");
595 }
596
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200597 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200598}
599
600
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100601/* This function check the number of arguments available in the
602 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500603 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100604 */
605__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
606{
607 if (lua_gettop(L) == nb)
608 return;
609 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
610}
611
Mark Lakes22154b42018-01-29 14:38:40 -0800612/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100613 * and the line number where the error is encountered.
614 */
615static int hlua_pusherror(lua_State *L, const char *fmt, ...)
616{
617 va_list argp;
618 va_start(argp, fmt);
619 luaL_where(L, 1);
620 lua_pushvfstring(L, fmt, argp);
621 va_end(argp);
622 lua_concat(L, 2);
623 return 1;
624}
625
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100626/* This functions is used with sample fetch and converters. It
627 * converts the HAProxy configuration argument in a lua stack
628 * values.
629 *
630 * It takes an array of "arg", and each entry of the array is
631 * converted and pushed in the LUA stack.
632 */
633static int hlua_arg2lua(lua_State *L, const struct arg *arg)
634{
635 switch (arg->type) {
636 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100637 case ARGT_TIME:
638 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100639 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100640 break;
641
642 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200643 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100644 break;
645
646 case ARGT_IPV4:
647 case ARGT_IPV6:
648 case ARGT_MSK4:
649 case ARGT_MSK6:
650 case ARGT_FE:
651 case ARGT_BE:
652 case ARGT_TAB:
653 case ARGT_SRV:
654 case ARGT_USR:
655 case ARGT_MAP:
656 default:
657 lua_pushnil(L);
658 break;
659 }
660 return 1;
661}
662
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500663/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500665 * with sample fetch wrappers. The input arguments are given to the
666 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 */
668static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
669{
670 switch (lua_type(L, ud)) {
671
672 case LUA_TNUMBER:
673 case LUA_TBOOLEAN:
674 arg->type = ARGT_SINT;
675 arg->data.sint = lua_tointeger(L, ud);
676 break;
677
678 case LUA_TSTRING:
679 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200680 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200681 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200682 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200683 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100684 break;
685
686 case LUA_TUSERDATA:
687 case LUA_TNIL:
688 case LUA_TTABLE:
689 case LUA_TFUNCTION:
690 case LUA_TTHREAD:
691 case LUA_TLIGHTUSERDATA:
692 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200693 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100694 break;
695 }
696 return 1;
697}
698
699/* the following functions are used to convert a struct sample
700 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500701 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100702 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100703static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100704{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200705 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100706 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100707 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200708 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100709 break;
710
711 case SMP_T_BIN:
712 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200713 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100714 break;
715
716 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200717 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100718 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
719 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
720 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
721 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
722 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
723 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
724 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
725 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
726 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200727 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100728 break;
729 default:
730 lua_pushnil(L);
731 break;
732 }
733 break;
734
735 case SMP_T_IPV4:
736 case SMP_T_IPV6:
737 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200738 if (sample_casts[smp->data.type][SMP_T_STR] &&
739 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200740 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100741 else
742 lua_pushnil(L);
743 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100744 default:
745 lua_pushnil(L);
746 break;
747 }
748 return 1;
749}
750
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100751/* the following functions are used to convert a struct sample
752 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500753 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100754 */
755static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
756{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200757 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100758
759 case SMP_T_BIN:
760 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200761 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100762 break;
763
764 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200765 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100766 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
767 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
768 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
769 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
770 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
771 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
772 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
773 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
774 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200775 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100776 break;
777 default:
778 lua_pushstring(L, "");
779 break;
780 }
781 break;
782
783 case SMP_T_SINT:
784 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100785 case SMP_T_IPV4:
786 case SMP_T_IPV6:
787 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200788 if (sample_casts[smp->data.type][SMP_T_STR] &&
789 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200790 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100791 else
792 lua_pushstring(L, "");
793 break;
794 default:
795 lua_pushstring(L, "");
796 break;
797 }
798 return 1;
799}
800
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100801/* the following functions are used to convert an Lua type in a
802 * struct sample. This is useful to provide data from a converter
803 * to the LUA code.
804 */
805static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
806{
807 switch (lua_type(L, ud)) {
808
809 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200810 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200811 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100812 break;
813
814
815 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200816 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200817 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100818 break;
819
820 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200821 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100822 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200823 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200824 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200825 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200826 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100827 break;
828
829 case LUA_TUSERDATA:
830 case LUA_TNIL:
831 case LUA_TTABLE:
832 case LUA_TFUNCTION:
833 case LUA_TTHREAD:
834 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200835 case LUA_TNONE:
836 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200837 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200838 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100839 break;
840 }
841 return 1;
842}
843
Ilya Shipitsind4259502020-04-08 01:07:56 +0500844/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800845 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100846 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500848 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200849 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100850 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100851__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100852 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100853{
854 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200855 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100856 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200857 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200858 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200859 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200860 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100861
862 idx = 0;
863 min_arg = ARGM(mask);
864 mask >>= ARGM_BITS;
865
866 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200867 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100868
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100869 /* Check for mandatory arguments. */
870 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100871 if (idx < min_arg) {
872
873 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200874 if (idx > 0) {
875 msg = "Mandatory argument expected";
876 goto error;
877 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100878
879 /* If first argument have a certain type, some default values
880 * may be used. See the function smp_resolve_args().
881 */
882 switch (mask & ARGT_MASK) {
883
884 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200885 if (!(p->cap & PR_CAP_FE)) {
886 msg = "Mandatory argument expected";
887 goto error;
888 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100889 argp[idx].data.prx = p;
890 argp[idx].type = ARGT_FE;
891 argp[idx+1].type = ARGT_STOP;
892 break;
893
894 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200895 if (!(p->cap & PR_CAP_BE)) {
896 msg = "Mandatory argument expected";
897 goto error;
898 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100899 argp[idx].data.prx = p;
900 argp[idx].type = ARGT_BE;
901 argp[idx+1].type = ARGT_STOP;
902 break;
903
904 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +0200905 if (!p->table) {
906 msg = "Mandatory argument expected";
907 goto error;
908 }
909 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100910 argp[idx].type = ARGT_TAB;
911 argp[idx+1].type = ARGT_STOP;
912 break;
913
914 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200915 msg = "Mandatory argument expected";
916 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100917 break;
918 }
919 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200920 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100921 }
922
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500923 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100924 if ((mask & ARGT_MASK) == ARGT_STOP &&
925 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200926 msg = "Last argument expected";
927 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100928 }
929
930 if ((mask & ARGT_MASK) == ARGT_STOP &&
931 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200932 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100933 }
934
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200935 /* Convert some argument types. All string in argp[] are for not
936 * duplicated yet.
937 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100938 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100939 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200940 if (argp[idx].type != ARGT_SINT) {
941 msg = "integer expected";
942 goto error;
943 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100944 argp[idx].type = ARGT_SINT;
945 break;
946
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100947 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200948 if (argp[idx].type != ARGT_SINT) {
949 msg = "integer expected";
950 goto error;
951 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200952 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100953 break;
954
955 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200956 if (argp[idx].type != ARGT_SINT) {
957 msg = "integer expected";
958 goto error;
959 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200960 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100961 break;
962
963 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200964 if (argp[idx].type != ARGT_STR) {
965 msg = "string expected";
966 goto error;
967 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200969 if (!argp[idx].data.prx) {
970 msg = "frontend doesn't exist";
971 goto error;
972 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100973 argp[idx].type = ARGT_FE;
974 break;
975
976 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200977 if (argp[idx].type != ARGT_STR) {
978 msg = "string expected";
979 goto error;
980 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200981 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200982 if (!argp[idx].data.prx) {
983 msg = "backend doesn't exist";
984 goto error;
985 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100986 argp[idx].type = ARGT_BE;
987 break;
988
989 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200990 if (argp[idx].type != ARGT_STR) {
991 msg = "string expected";
992 goto error;
993 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200994 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200995 if (!argp[idx].data.t) {
996 msg = "table doesn't exist";
997 goto error;
998 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100999 argp[idx].type = ARGT_TAB;
1000 break;
1001
1002 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001003 if (argp[idx].type != ARGT_STR) {
1004 msg = "string expected";
1005 goto error;
1006 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001007 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001008 if (sname) {
1009 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001010 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001011 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001012 if (!px) {
1013 msg = "backend doesn't exist";
1014 goto error;
1015 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001016 }
1017 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001018 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001019 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001020 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001021 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001022 if (!argp[idx].data.srv) {
1023 msg = "server doesn't exist";
1024 goto error;
1025 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001026 argp[idx].type = ARGT_SRV;
1027 break;
1028
1029 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001030 if (argp[idx].type != ARGT_STR) {
1031 msg = "string expected";
1032 goto error;
1033 }
1034 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1035 msg = "invalid IPv4 address";
1036 goto error;
1037 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001038 argp[idx].type = ARGT_IPV4;
1039 break;
1040
1041 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001042 if (argp[idx].type == ARGT_SINT)
1043 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1044 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001045 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1046 msg = "invalid IPv4 mask";
1047 goto error;
1048 }
1049 }
1050 else {
1051 msg = "integer or string expected";
1052 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001053 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001054 argp[idx].type = ARGT_MSK4;
1055 break;
1056
1057 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001058 if (argp[idx].type != ARGT_STR) {
1059 msg = "string expected";
1060 goto error;
1061 }
1062 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1063 msg = "invalid IPv6 address";
1064 goto error;
1065 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001066 argp[idx].type = ARGT_IPV6;
1067 break;
1068
1069 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001070 if (argp[idx].type == ARGT_SINT)
1071 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1072 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001073 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1074 msg = "invalid IPv6 mask";
1075 goto error;
1076 }
1077 }
1078 else {
1079 msg = "integer or string expected";
1080 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001081 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001082 argp[idx].type = ARGT_MSK6;
1083 break;
1084
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001085 case ARGT_REG:
1086 if (argp[idx].type != ARGT_STR) {
1087 msg = "string expected";
1088 goto error;
1089 }
1090 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1091 if (!reg) {
1092 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1093 argp[idx].data.str.area, err);
1094 free(err);
1095 goto error;
1096 }
1097 argp[idx].type = ARGT_REG;
1098 argp[idx].data.reg = reg;
1099 break;
1100
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001101 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001102 if (argp[idx].type != ARGT_STR) {
1103 msg = "string expected";
1104 goto error;
1105 }
1106 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001107 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001108 ul = p->uri_auth->userlist;
1109 else
1110 ul = auth_find_userlist(argp[idx].data.str.area);
1111
1112 if (!ul) {
1113 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1114 goto error;
1115 }
1116 argp[idx].type = ARGT_USR;
1117 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001118 break;
1119
1120 case ARGT_STR:
1121 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1122 msg = "unable to duplicate string arg";
1123 goto error;
1124 }
1125 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001126 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001127
Christopher Fauletd25d9262020-08-06 11:04:46 +02001128 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001129 msg = "type not yet supported";
1130 goto error;
1131 break;
1132
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001133 }
1134
1135 /* Check for type of argument. */
1136 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001137 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1138 arg_type_names[(mask & ARGT_MASK)],
1139 arg_type_names[argp[idx].type & ARGT_MASK]);
1140 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001141 }
1142
1143 /* Next argument. */
1144 mask >>= ARGT_BITS;
1145 idx++;
1146 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001147 return 0;
1148
1149 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001150 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001151 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001152 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1153 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001154}
1155
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001156/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001157 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001158 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001159 *
1160 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 * - hlua_sethlua : create the association between hlua context and lua_state.
1162 */
1163static inline struct hlua *hlua_gethlua(lua_State *L)
1164{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001165 struct hlua **hlua = lua_getextraspace(L);
1166 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167}
1168static inline void hlua_sethlua(struct hlua *hlua)
1169{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001170 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1171 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001172}
1173
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001174/* Will return a non-NULL string indicating the Lua call trace if the caller
1175 * currently is executing from within a Lua function. One line per entry will
1176 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1177 * Lua function is not detected, NULL is returned.
1178 */
1179const char *hlua_show_current_location(const char *pfx)
1180{
1181 lua_State *L;
1182 lua_Debug ar;
1183
1184 /* global or per-thread stack initializing ? */
1185 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1186 return hlua_traceback(L, pfx);
1187
1188 /* per-thread stack running ? */
1189 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1190 return hlua_traceback(L, pfx);
1191
1192 /* global stack running ? */
1193 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1194 return hlua_traceback(L, pfx);
1195
1196 return NULL;
1197}
1198
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001199/* This function is used to send logs. It try to send on screen (stderr)
1200 * and on the default syslog server.
1201 */
1202static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1203{
1204 struct tm tm;
1205 char *p;
1206
1207 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001208 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001209 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001210 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001211 /* Break the message if exceed the buffer size. */
1212 *(p-4) = ' ';
1213 *(p-3) = '.';
1214 *(p-2) = '.';
1215 *(p-1) = '.';
1216 break;
1217 }
Willy Tarreau90807112020-02-25 08:16:33 +01001218 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001219 *p = *msg;
1220 else
1221 *p = '.';
1222 }
1223 *p = '\0';
1224
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001225 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001226 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001227 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1228 return;
1229
Willy Tarreaua678b432015-08-28 10:14:59 +02001230 get_localtime(date.tv_sec, &tm);
1231 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001232 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001233 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001234 fflush(stderr);
1235 }
1236}
1237
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001238/* This function just ensure that the yield will be always
1239 * returned with a timeout and permit to set some flags
1240 */
1241__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001242 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001243{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001244 struct hlua *hlua;
1245
1246 /* Get hlua struct, or NULL if we execute from main lua state */
1247 hlua = hlua_gethlua(L);
1248 if (!hlua) {
1249 return;
1250 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001251
1252 /* Set the wake timeout. If timeout is required, we set
1253 * the expiration time.
1254 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001255 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001256
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001257 hlua->flags |= flags;
1258
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001259 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001260 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001261}
1262
Willy Tarreau87b09662015-04-03 00:22:06 +02001263/* This function initialises the Lua environment stored in the stream.
1264 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001265 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001266 *
1267 * This function is particular. it initialises a new Lua thread. If the
1268 * initialisation fails (example: out of memory error), the lua function
1269 * throws an error (longjmp).
1270 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001271 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001272 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001273 * threads appear, the safe environment set a lock to ensure only one
1274 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001275 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001276 *
1277 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001278 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001279 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001280 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001281 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001282 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001283 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001284 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001285int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001286{
1287 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001288 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001289 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001290 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001291 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001292 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001293 MT_LIST_INIT(&lua->hc_list);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001294 if (!already_safe) {
1295 if (!SET_SAFE_LJMP_PARENT(lua)) {
1296 lua->Tref = LUA_REFNIL;
1297 return 0;
1298 }
1299 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001300 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001301 if (!lua->T) {
1302 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001303 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001304 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001305 return 0;
1306 }
1307 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001308 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001309 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001310 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001311 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001312 return 1;
1313}
1314
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001315/* kill all associated httpclient to this hlua task
1316 * We must take extra precautions as we're manipulating lua-exposed
1317 * objects without the main lua lock.
1318 */
William Lallemandbb581422022-10-20 10:57:28 +02001319static void hlua_httpclient_destroy_all(struct hlua *hlua)
1320{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001321 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001322
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001323 /* use thread-safe accessors for hc_list since GC cycle initiated by
1324 * another thread sharing the same main lua stack (lua coroutine)
1325 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1326 * in parallel: Lua GC applies on the main stack, it is not limited to
1327 * a single coroutine stack, see Github issue #2037 for reference.
1328 * Remember, coroutines created using lua_newthread() are not meant to
1329 * be thread safe in Lua. (From lua co-author:
1330 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1331 *
1332 * This security measure is superfluous when 'lua-load-per-thread' is used
1333 * since in this case coroutines exclusively run on the same thread
1334 * (main stack is not shared between OS threads).
1335 */
1336 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1337 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001338 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001339 }
1340}
1341
1342
Willy Tarreau87b09662015-04-03 00:22:06 +02001343/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001344 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001345 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001346 */
1347void hlua_ctx_destroy(struct hlua *lua)
1348{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001349 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001350 return;
1351
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001352 if (!lua->T)
1353 goto end;
1354
William Lallemandbb581422022-10-20 10:57:28 +02001355 /* clean all running httpclient */
1356 hlua_httpclient_destroy_all(lua);
1357
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001358 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001359 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001360
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001361 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001362 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001363 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001364 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001365
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001366 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001367 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001368 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001369 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001370 /* Forces a garbage collecting process. If the Lua program is finished
1371 * without error, we run the GC on the thread pointer. Its freed all
1372 * the unused memory.
1373 * If the thread is finnish with an error or is currently yielded,
1374 * it seems that the GC applied on the thread doesn't clean anything,
1375 * so e run the GC on the main thread.
1376 * NOTE: maybe this action locks all the Lua threads untiml the en of
1377 * the garbage collection.
1378 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001379 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001380 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001381 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001382 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001383 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001384 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001385
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001386 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001387
1388end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001389 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001390}
1391
1392/* This function is used to restore the Lua context when a coroutine
1393 * fails. This function copy the common memory between old coroutine
1394 * and the new coroutine. The old coroutine is destroyed, and its
1395 * replaced by the new coroutine.
1396 * If the flag "keep_msg" is set, the last entry of the old is assumed
1397 * as string error message and it is copied in the new stack.
1398 */
1399static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1400{
1401 lua_State *T;
1402 int new_ref;
1403
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001404 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001405 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001406 if (!T)
1407 return 0;
1408
1409 /* Copy last error message. */
1410 if (keep_msg)
1411 lua_xmove(lua->T, T, 1);
1412
1413 /* Copy data between the coroutines. */
1414 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1415 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001416 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001417
1418 /* Destroy old data. */
1419 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1420
1421 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001422 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001423
1424 /* Fill the struct with the new coroutine values. */
1425 lua->Mref = new_ref;
1426 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001427 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001428
1429 /* Set context. */
1430 hlua_sethlua(lua);
1431
1432 return 1;
1433}
1434
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001435void hlua_hook(lua_State *L, lua_Debug *ar)
1436{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001437 struct hlua *hlua;
1438
1439 /* Get hlua struct, or NULL if we execute from main lua state */
1440 hlua = hlua_gethlua(L);
1441 if (!hlua)
1442 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001443
1444 /* Lua cannot yield when its returning from a function,
1445 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001446 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001447 */
1448 if (lua_gethookmask(L) & LUA_MASKRET) {
1449 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1450 return;
1451 }
1452
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001453 /* If we interrupt the Lua processing in yieldable state, we yield.
1454 * If the state is not yieldable, trying yield causes an error.
1455 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001456 if (lua_isyieldable(L)) {
1457 /* note: for converters/fetches.. where yielding is not allowed
1458 * hlua_ctx_resume() will simply perform a goto resume_execution
1459 * instead of rescheduling hlua->task.
1460 * also: hlua_ctx_resume() will take care of checking execution
1461 * timeout and re-applying the hook as needed.
1462 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001463 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001464 /* lua docs says that the hook should return immediately after lua_yieldk
1465 *
1466 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1467 *
1468 * Moreover, it seems that we don't want to continue after the yield
1469 * because the end of the function is about handling unyieldable function,
1470 * which is not the case here.
1471 *
1472 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1473 * in the function.
1474 */
1475 return;
1476 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001477
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001478 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001479 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001480 hlua->run_time += now_ms - hlua->start_time;
1481 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001482 lua_pushfstring(L, "execution timeout");
1483 WILL_LJMP(lua_error(L));
1484 }
1485
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001486 /* Update the start time. */
1487 hlua->start_time = now_ms;
1488
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001489 /* Try to interrupt the process at the end of the current
1490 * unyieldable function.
1491 */
1492 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001493}
1494
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001495/* This function start or resumes the Lua stack execution. If the flag
1496 * "yield_allowed" if no set and the LUA stack execution returns a yield
1497 * The function return an error.
1498 *
1499 * The function can returns 4 values:
1500 * - HLUA_E_OK : The execution is terminated without any errors.
1501 * - HLUA_E_AGAIN : The execution must continue at the next associated
1502 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001503 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001504 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001505 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001506 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001507 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001508 * LUA code.
1509 */
1510static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1511{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001512#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1513 int nres;
1514#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001515 int ret;
1516 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001517 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001518
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001519 /* Initialise run time counter. */
1520 if (!HLUA_IS_RUNNING(lua))
1521 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001522
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001523 /* Lock the whole Lua execution. This lock must be before the
1524 * label "resume_execution".
1525 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001526 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001527 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001528
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001529resume_execution:
1530
1531 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1532 * instructions. it is used for preventing infinite loops.
1533 */
1534 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1535
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001536 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001537 HLUA_SET_RUN(lua);
1538 HLUA_CLR_CTRLYIELD(lua);
1539 HLUA_CLR_WAKERESWR(lua);
1540 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001541 HLUA_CLR_NOYIELD(lua);
1542 if (!yield_allowed)
1543 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001544
Christopher Fauletbc275a92020-02-26 14:55:16 +01001545 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001546 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001547 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001548
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001549 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001550#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001551 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001552#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001553 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001554#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001555 switch (ret) {
1556
1557 case LUA_OK:
1558 ret = HLUA_E_OK;
1559 break;
1560
1561 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001562 /* Check if the execution timeout is expired. It it is the case, we
1563 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001564 */
Willy Tarreau55542642021-10-08 09:33:24 +02001565 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001566 lua->run_time += now_ms - lua->start_time;
1567 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001568 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001569 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001570 break;
1571 }
1572 /* Process the forced yield. if the general yield is not allowed or
1573 * if no task were associated this the current Lua execution
1574 * coroutine, we resume the execution. Else we want to return in the
1575 * scheduler and we want to be waked up again, to continue the
1576 * current Lua execution. So we schedule our own task.
1577 */
1578 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001579 if (!yield_allowed || !lua->task)
1580 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001581 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001582 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001583 if (!yield_allowed) {
1584 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001585 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001586 break;
1587 }
1588 ret = HLUA_E_AGAIN;
1589 break;
1590
1591 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001592
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001593 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001594 * because the errors ares the only one mean to return immediately
1595 * from and lua execution.
1596 */
1597 if (lua->flags & HLUA_EXIT) {
1598 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001599 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001600 break;
1601 }
1602
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001603 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001604 if (!lua_checkstack(lua->T, 1)) {
1605 ret = HLUA_E_ERR;
1606 break;
1607 }
1608 msg = lua_tostring(lua->T, -1);
1609 lua_settop(lua->T, 0); /* Empty the stack. */
1610 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001611 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001612 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001613 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001614 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001615 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001616 ret = HLUA_E_ERRMSG;
1617 break;
1618
1619 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001620 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001621 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001622 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001623 break;
1624
1625 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001626 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001627 if (!lua_checkstack(lua->T, 1)) {
1628 ret = HLUA_E_ERR;
1629 break;
1630 }
1631 msg = lua_tostring(lua->T, -1);
1632 lua_settop(lua->T, 0); /* Empty the stack. */
1633 lua_pop(lua->T, 1);
1634 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001635 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001636 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001637 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001638 ret = HLUA_E_ERRMSG;
1639 break;
1640
1641 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001642 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001643 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001644 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001645 break;
1646 }
1647
1648 switch (ret) {
1649 case HLUA_E_AGAIN:
1650 break;
1651
1652 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001653 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001654 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001655 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001656 break;
1657
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001658 case HLUA_E_ETMOUT:
1659 case HLUA_E_NOMEM:
1660 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001661 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001662 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001663 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001664 hlua_ctx_renew(lua, 0);
1665 break;
1666
1667 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001668 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001669 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001670 break;
1671 }
1672
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001673 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001674 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001675 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001676
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001677 return ret;
1678}
1679
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001680/* This function exit the current code. */
1681__LJMP static int hlua_done(lua_State *L)
1682{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001683 struct hlua *hlua;
1684
1685 /* Get hlua struct, or NULL if we execute from main lua state */
1686 hlua = hlua_gethlua(L);
1687 if (!hlua)
1688 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001689
1690 hlua->flags |= HLUA_EXIT;
1691 WILL_LJMP(lua_error(L));
1692
1693 return 0;
1694}
1695
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001696/* This function is an LUA binding. It provides a function
1697 * for deleting ACL from a referenced ACL file.
1698 */
1699__LJMP static int hlua_del_acl(lua_State *L)
1700{
1701 const char *name;
1702 const char *key;
1703 struct pat_ref *ref;
1704
1705 MAY_LJMP(check_args(L, 2, "del_acl"));
1706
1707 name = MAY_LJMP(luaL_checkstring(L, 1));
1708 key = MAY_LJMP(luaL_checkstring(L, 2));
1709
1710 ref = pat_ref_lookup(name);
1711 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001712 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001713
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001714 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001715 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001716 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001717 return 0;
1718}
1719
1720/* This function is an LUA binding. It provides a function
1721 * for deleting map entry from a referenced map file.
1722 */
1723static int hlua_del_map(lua_State *L)
1724{
1725 const char *name;
1726 const char *key;
1727 struct pat_ref *ref;
1728
1729 MAY_LJMP(check_args(L, 2, "del_map"));
1730
1731 name = MAY_LJMP(luaL_checkstring(L, 1));
1732 key = MAY_LJMP(luaL_checkstring(L, 2));
1733
1734 ref = pat_ref_lookup(name);
1735 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001736 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001737
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001738 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001739 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001740 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001741 return 0;
1742}
1743
1744/* This function is an LUA binding. It provides a function
1745 * for adding ACL pattern from a referenced ACL file.
1746 */
1747static int hlua_add_acl(lua_State *L)
1748{
1749 const char *name;
1750 const char *key;
1751 struct pat_ref *ref;
1752
1753 MAY_LJMP(check_args(L, 2, "add_acl"));
1754
1755 name = MAY_LJMP(luaL_checkstring(L, 1));
1756 key = MAY_LJMP(luaL_checkstring(L, 2));
1757
1758 ref = pat_ref_lookup(name);
1759 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001760 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001761
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001762 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001763 if (pat_ref_find_elt(ref, key) == NULL)
1764 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001765 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001766 return 0;
1767}
1768
1769/* This function is an LUA binding. It provides a function
1770 * for setting map pattern and sample from a referenced map
1771 * file.
1772 */
1773static int hlua_set_map(lua_State *L)
1774{
1775 const char *name;
1776 const char *key;
1777 const char *value;
1778 struct pat_ref *ref;
1779
1780 MAY_LJMP(check_args(L, 3, "set_map"));
1781
1782 name = MAY_LJMP(luaL_checkstring(L, 1));
1783 key = MAY_LJMP(luaL_checkstring(L, 2));
1784 value = MAY_LJMP(luaL_checkstring(L, 3));
1785
1786 ref = pat_ref_lookup(name);
1787 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001788 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001789
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001790 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001791 if (pat_ref_find_elt(ref, key) != NULL)
1792 pat_ref_set(ref, key, value, NULL);
1793 else
1794 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001795 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001796 return 0;
1797}
1798
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001799/* A class is a lot of memory that contain data. This data can be a table,
1800 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001801 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001802 * the name of the object (_G[<name>] = <metable> ).
1803 *
1804 * A metable is a table that modify the standard behavior of a standard
1805 * access to the associated data. The entries of this new metatable are
1806 * defined as is:
1807 *
1808 * http://lua-users.org/wiki/MetatableEvents
1809 *
1810 * __index
1811 *
1812 * we access an absent field in a table, the result is nil. This is
1813 * true, but it is not the whole truth. Actually, such access triggers
1814 * the interpreter to look for an __index metamethod: If there is no
1815 * such method, as usually happens, then the access results in nil;
1816 * otherwise, the metamethod will provide the result.
1817 *
1818 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1819 * the key does not appear in the table, but the metatable has an __index
1820 * property:
1821 *
1822 * - if the value is a function, the function is called, passing in the
1823 * table and the key; the return value of that function is returned as
1824 * the result.
1825 *
1826 * - if the value is another table, the value of the key in that table is
1827 * asked for and returned (and if it doesn't exist in that table, but that
1828 * table's metatable has an __index property, then it continues on up)
1829 *
1830 * - Use "rawget(myTable,key)" to skip this metamethod.
1831 *
1832 * http://www.lua.org/pil/13.4.1.html
1833 *
1834 * __newindex
1835 *
1836 * Like __index, but control property assignment.
1837 *
1838 * __mode - Control weak references. A string value with one or both
1839 * of the characters 'k' and 'v' which specifies that the the
1840 * keys and/or values in the table are weak references.
1841 *
1842 * __call - Treat a table like a function. When a table is followed by
1843 * parenthesis such as "myTable( 'foo' )" and the metatable has
1844 * a __call key pointing to a function, that function is invoked
1845 * (passing any specified arguments) and the return value is
1846 * returned.
1847 *
1848 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1849 * called, if the metatable for myTable has a __metatable
1850 * key, the value of that key is returned instead of the
1851 * actual metatable.
1852 *
1853 * __tostring - Control string representation. When the builtin
1854 * "tostring( myTable )" function is called, if the metatable
1855 * for myTable has a __tostring property set to a function,
1856 * that function is invoked (passing myTable to it) and the
1857 * return value is used as the string representation.
1858 *
1859 * __len - Control table length. When the table length is requested using
1860 * the length operator ( '#' ), if the metatable for myTable has
1861 * a __len key pointing to a function, that function is invoked
1862 * (passing myTable to it) and the return value used as the value
1863 * of "#myTable".
1864 *
1865 * __gc - Userdata finalizer code. When userdata is set to be garbage
1866 * collected, if the metatable has a __gc field pointing to a
1867 * function, that function is first invoked, passing the userdata
1868 * to it. The __gc metamethod is not called for tables.
1869 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1870 *
1871 * Special metamethods for redefining standard operators:
1872 * http://www.lua.org/pil/13.1.html
1873 *
1874 * __add "+"
1875 * __sub "-"
1876 * __mul "*"
1877 * __div "/"
1878 * __unm "!"
1879 * __pow "^"
1880 * __concat ".."
1881 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001882 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001883 * http://www.lua.org/pil/13.2.html
1884 *
1885 * __eq "=="
1886 * __lt "<"
1887 * __le "<="
1888 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889
1890/*
1891 *
1892 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001893 * Class Map
1894 *
1895 *
1896 */
1897
1898/* Returns a struct hlua_map if the stack entry "ud" is
1899 * a class session, otherwise it throws an error.
1900 */
1901__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1902{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001903 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001904}
1905
1906/* This function is the map constructor. It don't need
1907 * the class Map object. It creates and return a new Map
1908 * object. It must be called only during "body" or "init"
1909 * context because it process some filesystem accesses.
1910 */
1911__LJMP static int hlua_map_new(struct lua_State *L)
1912{
1913 const char *fn;
1914 int match = PAT_MATCH_STR;
1915 struct sample_conv conv;
1916 const char *file = "";
1917 int line = 0;
1918 lua_Debug ar;
1919 char *err = NULL;
1920 struct arg args[2];
1921
1922 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1923 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1924
1925 fn = MAY_LJMP(luaL_checkstring(L, 1));
1926
1927 if (lua_gettop(L) >= 2) {
1928 match = MAY_LJMP(luaL_checkinteger(L, 2));
1929 if (match < 0 || match >= PAT_MATCH_NUM)
1930 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1931 }
1932
1933 /* Get Lua filename and line number. */
1934 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1935 lua_getinfo(L, "Sl", &ar); /* get info about it */
1936 if (ar.currentline > 0) { /* is there info? */
1937 file = ar.short_src;
1938 line = ar.currentline;
1939 }
1940 }
1941
1942 /* fill fake sample_conv struct. */
1943 conv.kw = ""; /* unused. */
1944 conv.process = NULL; /* unused. */
1945 conv.arg_mask = 0; /* unused. */
1946 conv.val_args = NULL; /* unused. */
1947 conv.out_type = SMP_T_STR;
1948 conv.private = (void *)(long)match;
1949 switch (match) {
1950 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1951 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1952 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1953 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1954 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1955 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1956 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001957 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001958 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1959 default:
1960 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1961 }
1962
1963 /* fill fake args. */
1964 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001965 args[0].data.str.area = strdup(fn);
1966 args[0].data.str.data = strlen(fn);
1967 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001968 args[1].type = ARGT_STOP;
1969
1970 /* load the map. */
1971 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001972 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001973 * free the err variable.
1974 */
1975 luaL_where(L, 1);
1976 lua_pushfstring(L, "'new': %s.", err);
1977 lua_concat(L, 2);
1978 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001979 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001980 WILL_LJMP(lua_error(L));
1981 }
1982
1983 /* create the lua object. */
1984 lua_newtable(L);
1985 lua_pushlightuserdata(L, args[0].data.map);
1986 lua_rawseti(L, -2, 0);
1987
1988 /* Pop a class Map metatable and affect it to the userdata. */
1989 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1990 lua_setmetatable(L, -2);
1991
1992
1993 return 1;
1994}
1995
1996__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1997{
1998 struct map_descriptor *desc;
1999 struct pattern *pat;
2000 struct sample smp;
2001
2002 MAY_LJMP(check_args(L, 2, "lookup"));
2003 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002004 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002005 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002006 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002007 }
2008 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002009 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002010 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002011 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 +01002012 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002013 }
2014
2015 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002016 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002017 if (str)
2018 lua_pushstring(L, "");
2019 else
2020 lua_pushnil(L);
2021 return 1;
2022 }
2023
2024 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002025 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002026 return 1;
2027}
2028
2029__LJMP static int hlua_map_lookup(struct lua_State *L)
2030{
2031 return _hlua_map_lookup(L, 0);
2032}
2033
2034__LJMP static int hlua_map_slookup(struct lua_State *L)
2035{
2036 return _hlua_map_lookup(L, 1);
2037}
2038
2039/*
2040 *
2041 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002042 * Class Socket
2043 *
2044 *
2045 */
2046
2047__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2048{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002049 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002050}
2051
2052/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002053 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002054 * received.
2055 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002056static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057{
Willy Tarreau5321da92022-05-06 11:57:34 +02002058 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002059 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002060
Christopher Faulet31572222023-03-31 11:13:48 +02002061 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
2062 notification_wake(&ctx->wake_on_read);
2063 notification_wake(&ctx->wake_on_write);
2064 return;
2065 }
2066
Willy Tarreau5321da92022-05-06 11:57:34 +02002067 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002068 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002069 notification_wake(&ctx->wake_on_read);
2070 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002071 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002072 }
2073
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002074 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002075 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002076 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002077
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002078 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002079 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002080 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002081
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002082 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002083 * to be notified whenever the connection completes.
2084 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002085 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002086 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002087 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002088 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002089 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002090 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002091
2092 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002093 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002095 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002096 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002097 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002098
2099 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002100 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002101 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002102
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002103 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002104 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002105 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002106 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002107 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108}
2109
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002110static int hlua_socket_init(struct appctx *appctx)
2111{
2112 struct hlua_csk_ctx *ctx = appctx->svcctx;
2113 struct stream *s;
2114
2115 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2116 goto error;
2117
2118 s = appctx_strm(appctx);
2119
Willy Tarreau4596fe22022-05-17 19:07:51 +02002120 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002121 * and retrieve data from the server. The connection is initialized
2122 * with the "struct server".
2123 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002124 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002125
2126 /* Force destination server. */
2127 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2128 s->target = &socket_tcp->obj_type;
2129
2130 ctx->appctx = appctx;
2131 return 0;
2132
2133 error:
2134 return -1;
2135}
2136
Willy Tarreau87b09662015-04-03 00:22:06 +02002137/* This function is called when the "struct stream" is destroyed.
2138 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139 * Wake all the pending signals.
2140 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002141static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142{
Willy Tarreau5321da92022-05-06 11:57:34 +02002143 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002144 struct xref *peer;
2145
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002146 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002147 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002148 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002149 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150
2151 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002152 notification_wake(&ctx->wake_on_read);
2153 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002154}
2155
2156/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002157 * uses this object. If the stream does not exists, just quit.
2158 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002159 * pending signal can rest in the read and write lists. destroy
2160 * it.
2161 */
2162__LJMP static int hlua_socket_gc(lua_State *L)
2163{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002164 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002165 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002166 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002168 MAY_LJMP(check_args(L, 1, "__gc"));
2169
2170 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002171 peer = xref_get_peer_and_lock(&socket->xref);
2172 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002174
2175 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002177 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002178 ctx->die = 1;
2179 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002181 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002182 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183 return 0;
2184}
2185
2186/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002187 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 */
sada05ed3302018-05-11 11:48:18 -07002189__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002191 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002192 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002193 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002194 struct hlua *hlua;
2195
2196 /* Get hlua struct, or NULL if we execute from main lua state */
2197 hlua = hlua_gethlua(L);
2198 if (!hlua)
2199 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002201 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002202
2203 /* Check if we run on the same thread than the xreator thread.
2204 * We cannot access to the socket if the thread is different.
2205 */
2206 if (socket->tid != tid)
2207 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2208
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002209 peer = xref_get_peer_and_lock(&socket->xref);
2210 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002212
2213 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002214 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002216 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002217 ctx->die = 1;
2218 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002220 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002221 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002222 return 0;
2223}
2224
sada05ed3302018-05-11 11:48:18 -07002225/* The close function calls close_helper.
2226 */
2227__LJMP static int hlua_socket_close(lua_State *L)
2228{
2229 MAY_LJMP(check_args(L, 1, "close"));
2230 return hlua_socket_close_helper(L);
2231}
2232
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002233/* This Lua function assumes that the stack contain three parameters.
2234 * 1 - USERDATA containing a struct socket
2235 * 2 - INTEGER with values of the macro defined below
2236 * If the integer is -1, we must read at most one line.
2237 * If the integer is -2, we ust read all the data until the
2238 * end of the stream.
2239 * If the integer is positive value, we must read a number of
2240 * bytes corresponding to this value.
2241 */
2242#define HLSR_READ_LINE (-1)
2243#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002244__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245{
2246 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2247 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002248 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002249 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002251 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002253 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002254 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002255 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002256 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002257 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002258 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002259 struct stream *s;
2260 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002261 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002263 /* Get hlua struct, or NULL if we execute from main lua state */
2264 hlua = hlua_gethlua(L);
2265
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266 /* Check if this lua stack is schedulable. */
2267 if (!hlua || !hlua->task)
2268 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2269 "'frontend', 'backend' or 'task'"));
2270
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002271 /* Check if we run on the same thread than the xreator thread.
2272 * We cannot access to the socket if the thread is different.
2273 */
2274 if (socket->tid != tid)
2275 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2276
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002277 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002278 peer = xref_get_peer_and_lock(&socket->xref);
2279 if (!peer)
2280 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002281
2282 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2283 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002284 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002286 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002289 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290 if (nblk < 0) /* Connection close. */
2291 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002292 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002294
2295 /* remove final \r\n. */
2296 if (nblk == 1) {
2297 if (blk1[len1-1] == '\n') {
2298 len1--;
2299 skip_at_end++;
2300 if (blk1[len1-1] == '\r') {
2301 len1--;
2302 skip_at_end++;
2303 }
2304 }
2305 }
2306 else {
2307 if (blk2[len2-1] == '\n') {
2308 len2--;
2309 skip_at_end++;
2310 if (blk2[len2-1] == '\r') {
2311 len2--;
2312 skip_at_end++;
2313 }
2314 }
2315 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 }
2317
2318 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002320 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 if (nblk < 0) /* Connection close. */
2322 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002323 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 goto connection_empty;
2325 }
2326
2327 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002329 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330 if (nblk < 0) /* Connection close. */
2331 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002332 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333 goto connection_empty;
2334
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002335 missing_bytes = wanted - socket->b.n;
2336 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002338 len1 = missing_bytes;
2339 } if (nblk == 2 && len1 + len2 > missing_bytes)
2340 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341 }
2342
2343 len = len1;
2344
2345 luaL_addlstring(&socket->b, blk1, len1);
2346 if (nblk == 2) {
2347 len += len2;
2348 luaL_addlstring(&socket->b, blk2, len2);
2349 }
2350
2351 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002352 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002353
2354 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002355 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356
2357 /* If the pattern reclaim to read all the data
2358 * in the connection, got out.
2359 */
2360 if (wanted == HLSR_READ_ALL)
2361 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002362 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002363 goto connection_empty;
2364
2365 /* Return result. */
2366 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002367 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368 return 1;
2369
2370connection_closed:
2371
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002372 xref_unlock(&socket->xref, peer);
2373
2374no_peer:
2375
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 /* If the buffer containds data. */
2377 if (socket->b.n > 0) {
2378 luaL_pushresult(&socket->b);
2379 return 1;
2380 }
2381 lua_pushnil(L);
2382 lua_pushstring(L, "connection closed.");
2383 return 2;
2384
2385connection_empty:
2386
Willy Tarreau5321da92022-05-06 11:57:34 +02002387 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002388 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002390 }
2391 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002392 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 return 0;
2394}
2395
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002396/* This Lua function gets two parameters. The first one can be string
2397 * or a number. If the string is "*l", the user requires one line. If
2398 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 * If the value is a number, the user require a number of bytes equal
2400 * to the value. The default value is "*l" (a line).
2401 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002402 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002403 * integer takes this values:
2404 * -1 : read a line
2405 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002406 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002408 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 * concatenated with the read data.
2410 */
2411__LJMP static int hlua_socket_receive(struct lua_State *L)
2412{
2413 int wanted = HLSR_READ_LINE;
2414 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002415 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416 char *error;
2417 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002418 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419
2420 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2421 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2422
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002423 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002424
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002425 /* Check if we run on the same thread than the xreator thread.
2426 * We cannot access to the socket if the thread is different.
2427 */
2428 if (socket->tid != tid)
2429 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2430
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431 /* check for pattern. */
2432 if (lua_gettop(L) >= 2) {
2433 type = lua_type(L, 2);
2434 if (type == LUA_TSTRING) {
2435 pattern = lua_tostring(L, 2);
2436 if (strcmp(pattern, "*a") == 0)
2437 wanted = HLSR_READ_ALL;
2438 else if (strcmp(pattern, "*l") == 0)
2439 wanted = HLSR_READ_LINE;
2440 else {
2441 wanted = strtoll(pattern, &error, 10);
2442 if (*error != '\0')
2443 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2444 }
2445 }
2446 else if (type == LUA_TNUMBER) {
2447 wanted = lua_tointeger(L, 2);
2448 if (wanted < 0)
2449 WILL_LJMP(luaL_error(L, "Unsupported size."));
2450 }
2451 }
2452
2453 /* Set pattern. */
2454 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002455
2456 /* Check if we would replace the top by itself. */
2457 if (lua_gettop(L) != 2)
2458 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002459
Christopher Fauletc31b2002021-05-03 10:11:13 +02002460 /* Save index of the top of the stack because since buffers are used, it
2461 * may change
2462 */
2463 lastarg = lua_gettop(L);
2464
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002465 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002466 luaL_buffinit(L, &socket->b);
2467
2468 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002469 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470 if (lua_type(L, 3) != LUA_TSTRING)
2471 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2472 pattern = lua_tolstring(L, 3, &len);
2473 luaL_addlstring(&socket->b, pattern, len);
2474 }
2475
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002476 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002477}
2478
2479/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002480 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002481 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002483{
2484 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002485 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002486 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002487 struct appctx *appctx;
2488 size_t buf_len;
2489 const char *buf;
2490 int len;
2491 int send_len;
2492 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002493 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002494 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002495 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002496
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002497 /* Get hlua struct, or NULL if we execute from main lua state */
2498 hlua = hlua_gethlua(L);
2499
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 /* Check if this lua stack is schedulable. */
2501 if (!hlua || !hlua->task)
2502 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2503 "'frontend', 'backend' or 'task'"));
2504
2505 /* Get object */
2506 socket = MAY_LJMP(hlua_checksocket(L, 1));
2507 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002508 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002510 /* Check if we run on the same thread than the xreator thread.
2511 * We cannot access to the socket if the thread is different.
2512 */
2513 if (socket->tid != tid)
2514 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2515
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002516 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002517 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002518 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002519 lua_pushinteger(L, -1);
2520 return 1;
2521 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002522
2523 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2524 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002525 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002526 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002527
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002529 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002530 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002531 lua_pushinteger(L, -1);
2532 return 1;
2533 }
2534
2535 /* Update the input buffer data. */
2536 buf += sent;
2537 send_len = buf_len - sent;
2538
2539 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002540 if (sent >= buf_len) {
2541 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002543 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002545 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002546 * the request buffer if its not required.
2547 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002548 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002549 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002550 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002551 }
2552
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002553 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002554 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002555 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002556 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002557 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002558
2559 /* send data */
2560 if (len < send_len)
2561 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002562 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002563
2564 /* "Not enough space" (-1), "Buffer too little to contain
2565 * the data" (-2) are not expected because the available length
2566 * is tested.
2567 * Other unknown error are also not expected.
2568 */
2569 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002570 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002571 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002572
sada05ed3302018-05-11 11:48:18 -07002573 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002575 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002576 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002577 return 1;
2578 }
2579
2580 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002581 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002582
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002583 /* Update length sent. */
2584 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002585 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002586
2587 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002588 if (sent + len >= buf_len) {
2589 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002590 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002591 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002592
2593hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002594 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002595 xref_unlock(&socket->xref, peer);
2596 WILL_LJMP(luaL_error(L, "out of memory"));
2597 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002598 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002599 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002600 return 0;
2601}
2602
2603/* This function initiate the send of data. It just check the input
2604 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002605 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606 * "hlua_socket_write_yield" that can yield.
2607 *
2608 * The Lua function gets between 3 and 4 parameters. The first one is
2609 * the associated object. The second is a string buffer. The third is
2610 * a facultative integer that represents where is the buffer position
2611 * of the start of the data that can send. The first byte is the
2612 * position "1". The default value is "1". The fourth argument is a
2613 * facultative integer that represents where is the buffer position
2614 * of the end of the data that can send. The default is the last byte.
2615 */
2616static int hlua_socket_send(struct lua_State *L)
2617{
2618 int i;
2619 int j;
2620 const char *buf;
2621 size_t buf_len;
2622
2623 /* Check number of arguments. */
2624 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2625 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2626
2627 /* Get the string. */
2628 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2629
2630 /* Get and check j. */
2631 if (lua_gettop(L) == 4) {
2632 j = MAY_LJMP(luaL_checkinteger(L, 4));
2633 if (j < 0)
2634 j = buf_len + j + 1;
2635 if (j > buf_len)
2636 j = buf_len + 1;
2637 lua_pop(L, 1);
2638 }
2639 else
2640 j = buf_len;
2641
2642 /* Get and check i. */
2643 if (lua_gettop(L) == 3) {
2644 i = MAY_LJMP(luaL_checkinteger(L, 3));
2645 if (i < 0)
2646 i = buf_len + i + 1;
2647 if (i > buf_len)
2648 i = buf_len + 1;
2649 lua_pop(L, 1);
2650 } else
2651 i = 1;
2652
2653 /* Check bth i and j. */
2654 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002655 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656 return 1;
2657 }
2658 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002659 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002660 return 1;
2661 }
2662 if (i == 0)
2663 i = 1;
2664 if (j == 0)
2665 j = 1;
2666
2667 /* Pop the string. */
2668 lua_pop(L, 1);
2669
2670 /* Update the buffer length. */
2671 buf += i - 1;
2672 buf_len = j - i + 1;
2673 lua_pushlstring(L, buf, buf_len);
2674
2675 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002676 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002678 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002679}
2680
Willy Tarreau22b0a682015-06-17 19:43:49 +02002681#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002682__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002683{
2684 static char buffer[SOCKET_INFO_MAX_LEN];
2685 int ret;
2686 int len;
2687 char *p;
2688
2689 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2690 if (ret <= 0) {
2691 lua_pushnil(L);
2692 return 1;
2693 }
2694
2695 if (ret == AF_UNIX) {
2696 lua_pushstring(L, buffer+1);
2697 return 1;
2698 }
2699 else if (ret == AF_INET6) {
2700 buffer[0] = '[';
2701 len = strlen(buffer);
2702 buffer[len] = ']';
2703 len++;
2704 buffer[len] = ':';
2705 len++;
2706 p = buffer;
2707 }
2708 else if (ret == AF_INET) {
2709 p = buffer + 1;
2710 len = strlen(p);
2711 p[len] = ':';
2712 len++;
2713 }
2714 else {
2715 lua_pushnil(L);
2716 return 1;
2717 }
2718
2719 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2720 lua_pushnil(L);
2721 return 1;
2722 }
2723
2724 lua_pushstring(L, p);
2725 return 1;
2726}
2727
2728/* Returns information about the peer of the connection. */
2729__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2730{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002731 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002732 struct xref *peer;
2733 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002734 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002735 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002736 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002737
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002738 MAY_LJMP(check_args(L, 1, "getpeername"));
2739
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002740 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002741
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002742 /* Check if we run on the same thread than the xreator thread.
2743 * We cannot access to the socket if the thread is different.
2744 */
2745 if (socket->tid != tid)
2746 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2747
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002748 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002749 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002750 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002751 lua_pushnil(L);
2752 return 1;
2753 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002754
2755 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002756 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002757 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002758 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002759 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002760 lua_pushnil(L);
2761 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002762 }
2763
Christopher Faulet16f16af2021-10-27 09:34:56 +02002764 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002765 xref_unlock(&socket->xref, peer);
2766 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002767}
2768
2769/* Returns information about my connection side. */
2770static int hlua_socket_getsockname(struct lua_State *L)
2771{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002772 struct hlua_socket *socket;
2773 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002774 struct appctx *appctx;
2775 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002776 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002777 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002778
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002779 MAY_LJMP(check_args(L, 1, "getsockname"));
2780
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002781 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002782
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002783 /* Check if we run on the same thread than the xreator thread.
2784 * We cannot access to the socket if the thread is different.
2785 */
2786 if (socket->tid != tid)
2787 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2788
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002789 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002790 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002791 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002792 lua_pushnil(L);
2793 return 1;
2794 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002795
2796 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002797 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002798
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002799 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002800 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002801 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002802 lua_pushnil(L);
2803 return 1;
2804 }
2805
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002806 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002807 xref_unlock(&socket->xref, peer);
2808 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002809}
2810
2811/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002812static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813 .obj_type = OBJ_TYPE_APPLET,
2814 .name = "<LUA_TCP>",
2815 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002816 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002817 .release = hlua_socket_release,
2818};
2819
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002820__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002821{
2822 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002823 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002824 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002825 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002826 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002827 struct stream *s;
2828
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002829 /* Get hlua struct, or NULL if we execute from main lua state */
2830 hlua = hlua_gethlua(L);
2831 if (!hlua)
2832 return 0;
2833
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002834 /* Check if we run on the same thread than the xreator thread.
2835 * We cannot access to the socket if the thread is different.
2836 */
2837 if (socket->tid != tid)
2838 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2839
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002840 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002841 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002842 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002843 lua_pushnil(L);
2844 lua_pushstring(L, "Can't connect");
2845 return 2;
2846 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002847
2848 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2849 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002850 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002851
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002852 /* Check if we run on the same thread than the xreator thread.
2853 * We cannot access to the socket if the thread is different.
2854 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002855 if (socket->tid != tid) {
2856 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002857 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002858 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002859
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002860 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002861 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002862 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002863 lua_pushnil(L);
2864 lua_pushstring(L, "Can't connect");
2865 return 2;
2866 }
2867
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02002868 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002869
2870 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002871 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002872 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002873 lua_pushinteger(L, 1);
2874 return 1;
2875 }
2876
Willy Tarreau5321da92022-05-06 11:57:34 +02002877 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002878 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002879 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002880 }
2881 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002882 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002883 return 0;
2884}
2885
2886/* This function fail or initite the connection. */
2887__LJMP static int hlua_socket_connect(struct lua_State *L)
2888{
2889 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002890 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002891 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002892 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002893 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002894 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002895 int low, high;
2896 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002897 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002898 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002899 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002900
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002901 if (lua_gettop(L) < 2)
2902 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002903
2904 /* Get args. */
2905 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002906
2907 /* Check if we run on the same thread than the xreator thread.
2908 * We cannot access to the socket if the thread is different.
2909 */
2910 if (socket->tid != tid)
2911 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2912
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002913 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002914 if (lua_gettop(L) >= 3) {
2915 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002916 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002917
Tim Duesterhus6edab862018-01-06 19:04:45 +01002918 /* Force the ip to end with a colon, to support IPv6 addresses
2919 * that are not enclosed within square brackets.
2920 */
2921 if (port > 0) {
2922 luaL_buffinit(L, &b);
2923 luaL_addstring(&b, ip);
2924 luaL_addchar(&b, ':');
2925 luaL_pushresult(&b);
2926 ip = lua_tolstring(L, lua_gettop(L), NULL);
2927 }
2928 }
2929
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002930 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002931 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002932 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002933 lua_pushnil(L);
2934 return 1;
2935 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002936
2937 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002938 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 +02002939 if (!addr) {
2940 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002941 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002942 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002943
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002944 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002945 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002946 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002947 if (port == -1) {
2948 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002949 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002950 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002951 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2952 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002953 if (port == -1) {
2954 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002955 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002956 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002957 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002958 }
2959 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002960
Willy Tarreau5321da92022-05-06 11:57:34 +02002961 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2962 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002963 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002964 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002965
Willy Tarreau3e7be362022-05-27 10:35:27 +02002966 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002967 xref_unlock(&socket->xref, peer);
2968 WILL_LJMP(luaL_error(L, "connect: internal error"));
2969 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002971 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002972 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002973 if (!hlua)
2974 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002975
2976 /* inform the stream that we want to be notified whenever the
2977 * connection completes.
2978 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02002979 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002980 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002981 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002982
Willy Tarreauf31af932020-01-14 09:59:38 +01002983 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002984
Willy Tarreau5321da92022-05-06 11:57:34 +02002985 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002986 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002987 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002988 }
2989 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002990
2991 task_wakeup(s->task, TASK_WOKEN_INIT);
2992 /* Return yield waiting for connection. */
2993
Willy Tarreau9635e032018-10-16 17:52:55 +02002994 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995
2996 return 0;
2997}
2998
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002999#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003000__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3001{
3002 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003003 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003004 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003005
3006 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3007 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003008
3009 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003010 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003011 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003012 lua_pushnil(L);
3013 return 1;
3014 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003015
Willy Tarreau0698c802022-05-11 14:09:57 +02003016 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003017
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003018 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003019 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003020 return MAY_LJMP(hlua_socket_connect(L));
3021}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003022#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003023
3024__LJMP static int hlua_socket_setoption(struct lua_State *L)
3025{
3026 return 0;
3027}
3028
3029__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3030{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003031 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003032 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003033 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003034 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003035 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003036
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003037 MAY_LJMP(check_args(L, 2, "settimeout"));
3038
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003039 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003040
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003041 /* convert the timeout to millis */
3042 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003043
Thierry Fournier17a921b2018-03-08 09:59:02 +01003044 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003045 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003046 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3047
Mark Lakes56cc1252018-03-27 09:48:06 +02003048 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003049 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003050
3051 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003052 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003053 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003054
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003055 /* Check if we run on the same thread than the xreator thread.
3056 * We cannot access to the socket if the thread is different.
3057 */
3058 if (socket->tid != tid)
3059 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3060
Mark Lakes56cc1252018-03-27 09:48:06 +02003061 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003062 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003063 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003064 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3065 WILL_LJMP(lua_error(L));
3066 return 0;
3067 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003068
Willy Tarreau0698c802022-05-11 14:09:57 +02003069 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003070
Cyril Bonté7bb63452018-08-17 23:51:02 +02003071 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003072 s->scf->ioto = tmout;
3073 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003074
3075 s->task->expire = tick_add_ifset(now_ms, tmout);
3076 task_queue(s->task);
3077
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003078 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003079
Thierry Fourniere9636f12018-03-08 09:54:32 +01003080 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003081 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003082}
3083
3084__LJMP static int hlua_socket_new(lua_State *L)
3085{
3086 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003087 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003088 struct appctx *appctx;
3089
3090 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003091 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003092 hlua_pusherror(L, "socket: full stack");
3093 goto out_fail_conf;
3094 }
3095
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003096 /* Create the object: obj[0] = userdata. */
3097 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003098 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003099 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003100 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003101 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003102
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003103 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003104 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003105 hlua_pusherror(L, "socket: uninitialized pools.");
3106 goto out_fail_conf;
3107 }
3108
Willy Tarreau87b09662015-04-03 00:22:06 +02003109 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003110 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3111 lua_setmetatable(L, -2);
3112
Willy Tarreaud420a972015-04-06 00:39:18 +02003113 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003114 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003115 if (!appctx) {
3116 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003117 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003118 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003119 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3120 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003121 ctx->die = 0;
3122 LIST_INIT(&ctx->wake_on_write);
3123 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003124
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003125 if (appctx_init(appctx) == -1) {
3126 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003127 goto out_fail_appctx;
3128 }
3129
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003130 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003131 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003132 return 1;
3133
Christopher Faulet13a35e52021-12-20 15:34:16 +01003134 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003135 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003136 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003137 WILL_LJMP(lua_error(L));
3138 return 0;
3139}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003140
3141/*
3142 *
3143 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003144 * Class Channel
3145 *
3146 *
3147 */
3148
3149/* Returns the struct hlua_channel join to the class channel in the
3150 * stack entry "ud" or throws an argument error.
3151 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003152__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003153{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003154 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003155}
3156
Willy Tarreau47860ed2015-03-10 14:07:50 +01003157/* Pushes the channel onto the top of the stack. If the stask does not have a
3158 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003159 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003160static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003161{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003162 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003163 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003164 return 0;
3165
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003166 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003167 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003168 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003169
3170 /* Pop a class sesison metatable and affect it to the userdata. */
3171 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3172 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003173 return 1;
3174}
3175
Christopher Faulet9f55a502020-02-25 15:21:02 +01003176/* Helper function returning a filter attached to a channel at the position <ud>
3177 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003178 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003179 * initialized.
3180 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003181static 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 +01003182{
3183 struct filter *filter = NULL;
3184
3185 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3186 struct hlua_flt_ctx *flt_ctx;
3187
3188 filter = lua_touserdata (L, -1);
3189 flt_ctx = filter->ctx;
3190 if (hlua_filter_from_payload(filter)) {
3191 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3192 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3193 }
3194 }
3195
3196 lua_pop(L, 1);
3197 return filter;
3198}
3199
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003200/* Copies <len> bytes of data present in the channel's buffer, starting at the
3201* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003202* responsibility to ensure <len> and <offset> are valid. It always return the
3203* length of the built string. <len> may be 0, in this case, an empty string is
3204* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003205*/
3206static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003207{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003208 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003209 luaL_Buffer b;
3210
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003211 block1 = len;
3212 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3213 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3214 block2 = len - block1;
3215
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003216 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003217 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3218 if (block2)
3219 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003220 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003221 return len;
3222}
3223
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003224/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3225 * function returns -1 if data cannot be copied. Otherwise, it returns the
3226 * number of bytes copied.
3227 */
3228static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3229{
3230 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003231
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003232 /* Nothing to do, just return */
3233 if (unlikely(istlen(str) == 0))
3234 goto end;
3235
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003236 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003237 ret = -1;
3238 goto end;
3239 }
3240 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3241
3242 end:
3243 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003244}
3245
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003246/* Removes <len> bytes of data at the absolute position <offset>.
3247 */
3248static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3249{
3250 size_t end = offset + len;
3251
3252 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3253 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3254 b_data(&chn->buf) - end, -len);
3255 b_sub(&chn->buf, len);
3256}
3257
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003258/* Copies input data in the channel's buffer. It is possible to set a specific
3259 * offset (0 by default) and a length (all remaining input data starting for the
3260 * offset by default). If there is not enough input data and more data can be
3261 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003262 *
3263 * From an action, All input data are considered. For a filter, the offset and
3264 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003265 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003266__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003267{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003268 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003269 struct filter *filter;
3270 size_t input, output;
3271 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003272
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003273 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003275 output = co_data(chn);
3276 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003277
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003278 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3279 if (filter && !hlua_filter_from_payload(filter))
3280 WILL_LJMP(lua_error(L));
3281
3282 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003283 if (lua_gettop(L) > 1) {
3284 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3285 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003286 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003287 offset += output;
3288 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003289 lua_pushfstring(L, "offset out of range.");
3290 WILL_LJMP(lua_error(L));
3291 }
3292 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003293 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003294 if (lua_gettop(L) == 3) {
3295 len = MAY_LJMP(luaL_checkinteger(L, 3));
3296 if (!len)
3297 goto dup;
3298 if (len == -1)
3299 len = global.tune.bufsize;
3300 if (len < 0) {
3301 lua_pushfstring(L, "length out of range.");
3302 WILL_LJMP(lua_error(L));
3303 }
3304 }
3305
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003306 /* Wait for more data if possible if no length was specified and there
3307 * is no data or not enough data was received.
3308 */
3309 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003310 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3311 /* Yield waiting for more data, as requested */
3312 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3313 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003314
3315 /* Return 'nil' if there is no data and the channel can't receive more data */
3316 if (!len) {
3317 lua_pushnil(L);
3318 return -1;
3319 }
3320
3321 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003322 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003323 }
3324
3325 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003326 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003327 return 1;
3328}
3329
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003330/* Copies the first line (including the trailing LF) of input data in the
3331 * channel's buffer. It is possible to set a specific offset (0 by default) and
3332 * a length (all remaining input data starting for the offset by default). If
3333 * there is not enough input data and more data can be received, the function
3334 * yields. If a length is explicitly specified, no more data are
3335 * copied. Otherwise, if no LF is found and more data can be received, this
3336 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003337 *
3338 * From an action, All input data are considered. For a filter, the offset and
3339 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003340 */
3341__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003342{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003343 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003344 struct filter *filter;
3345 size_t l, input, output;
3346 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003347
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003348 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003349 output = co_data(chn);
3350 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003351
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003352 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3353 if (filter && !hlua_filter_from_payload(filter))
3354 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003355
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003356 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003357 if (lua_gettop(L) > 1) {
3358 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3359 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003360 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003361 offset += output;
3362 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003363 lua_pushfstring(L, "offset out of range.");
3364 WILL_LJMP(lua_error(L));
3365 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003366 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003367
3368 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003369 if (lua_gettop(L) == 3) {
3370 len = MAY_LJMP(luaL_checkinteger(L, 3));
3371 if (!len)
3372 goto dup;
3373 if (len == -1)
3374 len = global.tune.bufsize;
3375 if (len < 0) {
3376 lua_pushfstring(L, "length out of range.");
3377 WILL_LJMP(lua_error(L));
3378 }
3379 }
3380
3381 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003382 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003383 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003384 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003385 len = l+1;
3386 goto dup;
3387 }
3388 }
3389
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003390 /* Wait for more data if possible if no line is found and no length was
3391 * specified or not enough data was received.
3392 */
3393 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003394 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3395 /* Yield waiting for more data */
3396 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3397 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003398
3399 /* Return 'nil' if there is no data and the channel can't receive more data */
3400 if (!len) {
3401 lua_pushnil(L);
3402 return -1;
3403 }
3404
3405 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003406 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003407 }
3408
3409 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003410 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003411 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003412}
3413
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003414/* [ DEPRECATED ]
3415 *
3416 * Duplicate all input data foud in the channel's buffer. The data are not
3417 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003418 *
3419 * From an action, All input data are considered. For a filter, the offset and
3420 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003421 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003422__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003423{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003424 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003425 struct filter *filter;
3426 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003427
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003428 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003429 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003430 if (IS_HTX_STRM(chn_strm(chn))) {
3431 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3432 WILL_LJMP(lua_error(L));
3433 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003434
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003435 offset = co_data(chn);
3436 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003437
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003438 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3439 if (filter && !hlua_filter_from_payload(filter))
3440 WILL_LJMP(lua_error(L));
3441
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003442 if (!ci_data(chn) && channel_input_closed(chn)) {
3443 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003444 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003445 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003446
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003447 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003448 return 1;
3449}
3450
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003451/* [ DEPRECATED ]
3452 *
3453 * Get all input data foud in the channel's buffer. The data are removed from
3454 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3455 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003456 *
3457 * From an action, All input data are considered. For a filter, the offset and
3458 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003459 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003460__LJMP static int hlua_channel_get(lua_State *L)
3461{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003462 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003463 struct filter *filter;
3464 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003465 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003466
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003467 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003468 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3469 if (IS_HTX_STRM(chn_strm(chn))) {
3470 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3471 WILL_LJMP(lua_error(L));
3472 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003473
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003474 offset = co_data(chn);
3475 len = ci_data(chn);
3476
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003477 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3478 if (filter && !hlua_filter_from_payload(filter))
3479 WILL_LJMP(lua_error(L));
3480
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003481 if (!ci_data(chn) && channel_input_closed(chn)) {
3482 lua_pushnil(L);
3483 return 1;
3484 }
3485
3486 ret = _hlua_channel_dup(chn, L, offset, len);
3487 _hlua_channel_delete(chn, offset, ret);
3488 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003489}
3490
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003491/* This functions consumes and returns one line. If the channel is closed,
3492 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003493 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003494 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003495 *
3496 * From an action, All input data are considered. For a filter, the offset and
3497 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003498 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003499__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003500{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003501 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003502 struct filter *filter;
3503 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003504 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003505
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003506 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003507
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003508 offset = co_data(chn);
3509 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003510
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003511 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3512 if (filter && !hlua_filter_from_payload(filter))
3513 WILL_LJMP(lua_error(L));
3514
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003515 if (!ci_data(chn) && channel_input_closed(chn)) {
3516 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003517 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003518 }
3519
3520 for (l = 0; l < len; l++) {
3521 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3522 len = l+1;
3523 goto dup;
3524 }
3525 }
3526
3527 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3528 /* Yield waiting for more data */
3529 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3530 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003531
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003532 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003533 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003534 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003535 return 1;
3536}
3537
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003538/* [ DEPRECATED ]
3539 *
3540 * Check arguments for the function "hlua_channel_getline_yield".
3541 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003542__LJMP static int hlua_channel_getline(lua_State *L)
3543{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003544 struct channel *chn;
3545
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003546 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003547 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3548 if (IS_HTX_STRM(chn_strm(chn))) {
3549 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3550 WILL_LJMP(lua_error(L));
3551 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003552 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3553}
3554
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003555/* Retrieves a given amount of input data at the given offset. By default all
3556 * available input data are returned. The offset may be negactive to start from
3557 * the end of input data. The length may be -1 to set it to the maximum buffer
3558 * size.
3559 */
3560__LJMP static int hlua_channel_get_data(lua_State *L)
3561{
3562 struct channel *chn;
3563
3564 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3565 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3566 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3567 if (IS_HTX_STRM(chn_strm(chn))) {
3568 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3569 WILL_LJMP(lua_error(L));
3570 }
3571 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3572}
3573
3574/* Retrieves a given amount of input data at the given offset. By default all
3575 * available input data are returned. The offset may be negactive to start from
3576 * the end of input data. The length may be -1 to set it to the maximum buffer
3577 * size.
3578 */
3579__LJMP static int hlua_channel_get_line(lua_State *L)
3580{
3581 struct channel *chn;
3582
3583 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3584 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3585 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3586 if (IS_HTX_STRM(chn_strm(chn))) {
3587 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3588 WILL_LJMP(lua_error(L));
3589 }
3590 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3591}
3592
3593/* Appends a string into the input side of channel. It returns the length of the
3594 * written string, or -1 if the channel is closed or if the buffer size is too
3595 * little for the data. 0 may be returned if nothing is copied. This function
3596 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 *
3598 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003599 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003600__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003601{
Christopher Faulet23976d92021-08-06 09:59:49 +02003602 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003604 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003606 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003607
3608 MAY_LJMP(check_args(L, 2, "append"));
3609 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003610 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003611 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003612 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003613 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003614 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003615
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003616 offset = co_data(chn);
3617 len = ci_data(chn);
3618
3619 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3620 if (filter && !hlua_filter_from_payload(filter))
3621 WILL_LJMP(lua_error(L));
3622
3623 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3624 if (ret > 0 && filter) {
3625 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3626
3627 flt_update_offsets(filter, chn, ret);
3628 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3629 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003630 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003631 return 1;
3632}
3633
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003634/* Prepends a string into the input side of channel. It returns the length of the
3635 * written string, or -1 if the channel is closed or if the buffer size is too
3636 * little for the data. 0 may be returned if nothing is copied. This function
3637 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638 *
3639 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003640 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003641__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003642{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003643 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003644 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003645 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003646 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003647 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003648
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003649 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003650 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3652 if (IS_HTX_STRM(chn_strm(chn))) {
3653 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3654 WILL_LJMP(lua_error(L));
3655 }
3656
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657 offset = co_data(chn);
3658 len = ci_data(chn);
3659
3660 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3661 if (filter && !hlua_filter_from_payload(filter))
3662 WILL_LJMP(lua_error(L));
3663
3664 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3665 if (ret > 0 && filter) {
3666 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3667
3668 flt_update_offsets(filter, chn, ret);
3669 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3670 }
3671
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003672 lua_pushinteger(L, ret);
3673 return 1;
3674}
3675
3676/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003677 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003678 * returns the length of the written string, or -1 if the channel is closed or
3679 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003680 *
3681 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003682 */
3683__LJMP static int hlua_channel_insert_data(lua_State *L)
3684{
3685 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003686 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003687 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003688 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003689 int ret, offset;
3690
3691 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3692 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3693 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3694 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003695
3696 output = co_data(chn);
3697 input = ci_data(chn);
3698
3699 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3700 if (filter && !hlua_filter_from_payload(filter))
3701 WILL_LJMP(lua_error(L));
3702
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003703 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003705 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003706 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003707 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003708 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003709 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003710 lua_pushfstring(L, "offset out of range.");
3711 WILL_LJMP(lua_error(L));
3712 }
3713 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003714 if (IS_HTX_STRM(chn_strm(chn))) {
3715 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3716 WILL_LJMP(lua_error(L));
3717 }
3718
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003719 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3720 if (ret > 0 && filter) {
3721 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003722
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003723 flt_update_offsets(filter, chn, ret);
3724 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003725 }
3726
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003727 lua_pushinteger(L, ret);
3728 return 1;
3729}
3730/* Replaces a given amount of input data at the given offset by a string
3731 * content. By default all remaining data are removed (offset = 0 and len =
3732 * -1). It returns the length of the written string, or -1 if the channel is
3733 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003734 *
3735 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003736 */
3737__LJMP static int hlua_channel_set_data(lua_State *L)
3738{
3739 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003740 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003741 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003742 size_t sz, input, output;
3743 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003744
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003745 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3746 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3747 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3748 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003750 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003751 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003752 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003753 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003754
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003755 output = co_data(chn);
3756 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003757
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3759 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003760 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003761
3762 offset = output;
3763 if (lua_gettop(L) > 2) {
3764 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3765 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003766 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003767 offset += output;
3768 if (offset < output || offset > input + output) {
3769 lua_pushfstring(L, "offset out of range.");
3770 WILL_LJMP(lua_error(L));
3771 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003772 }
3773
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003774 len = output + input - offset;
3775 if (lua_gettop(L) == 4) {
3776 len = MAY_LJMP(luaL_checkinteger(L, 4));
3777 if (!len)
3778 goto set;
3779 if (len == -1)
3780 len = output + input - offset;
3781 if (len < 0 || offset + len > output + input) {
3782 lua_pushfstring(L, "length out of range.");
3783 WILL_LJMP(lua_error(L));
3784 }
3785 }
3786
3787 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003788 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003789 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003790 lua_pushinteger(L, -1);
3791 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003792 _hlua_channel_delete(chn, offset, len);
3793 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3794 if (filter) {
3795 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3796
3797 len -= (ret > 0 ? ret : 0);
3798 flt_update_offsets(filter, chn, -len);
3799 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3800 }
3801
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003803 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003804 return 1;
3805}
3806
3807/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003808 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003809 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003810 *
3811 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003812 */
3813__LJMP static int hlua_channel_del_data(lua_State *L)
3814{
3815 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003816 struct filter *filter;
3817 size_t input, output;
3818 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003819
3820 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3821 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3822 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003823
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003824 if (IS_HTX_STRM(chn_strm(chn))) {
3825 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3826 WILL_LJMP(lua_error(L));
3827 }
3828
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003829 output = co_data(chn);
3830 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003831
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003832 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3833 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003834 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003835
3836 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003837 if (lua_gettop(L) > 1) {
3838 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003839 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003840 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003841 offset += output;
3842 if (offset < output || offset > input + output) {
3843 lua_pushfstring(L, "offset out of range.");
3844 WILL_LJMP(lua_error(L));
3845 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003846 }
3847
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003848 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003849 if (lua_gettop(L) == 3) {
3850 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003851 if (!len)
3852 goto end;
3853 if (len == -1)
3854 len = output + input - offset;
3855 if (len < 0 || offset + len > output + input) {
3856 lua_pushfstring(L, "length out of range.");
3857 WILL_LJMP(lua_error(L));
3858 }
3859 }
3860
3861 _hlua_channel_delete(chn, offset, len);
3862 if (filter) {
3863 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3864
3865 flt_update_offsets(filter, chn, -len);
3866 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3867 }
3868
3869 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003870 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003871 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003872}
3873
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003874/* Append data in the output side of the buffer. This data is immediately
3875 * sent. The function returns the amount of data written. If the buffer
3876 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003877 * if the channel is closed.
3878 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003879__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003880{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003881 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003882 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003883 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003884 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003885 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003886 struct hlua *hlua;
3887
3888 /* Get hlua struct, or NULL if we execute from main lua state */
3889 hlua = hlua_gethlua(L);
3890 if (!hlua) {
3891 lua_pushnil(L);
3892 return 1;
3893 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003894
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003895 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3896 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3897 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003898
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003899 offset = co_data(chn);
3900 len = ci_data(chn);
3901
3902 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3903 if (filter && !hlua_filter_from_payload(filter))
3904 WILL_LJMP(lua_error(L));
3905
3906
Willy Tarreau47860ed2015-03-10 14:07:50 +01003907 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003908 lua_pushinteger(L, -1);
3909 return 1;
3910 }
3911
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003912 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003913 if (len > sz -l) {
3914 if (filter) {
3915 lua_pushinteger(L, -1);
3916 return 1;
3917 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003918 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003919 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003920
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003921 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003922 if (ret == -1) {
3923 lua_pop(L, 1);
3924 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003925 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003926 }
3927 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003928 if (filter) {
3929 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3930
3931
3932 flt_update_offsets(filter, chn, ret);
3933 FLT_OFF(filter, chn) += ret;
3934 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3935 }
3936 else
3937 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003938
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003939 l += ret;
3940 lua_pop(L, 1);
3941 lua_pushinteger(L, l);
3942 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003943
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003944 if (l < sz) {
3945 /* Yield only if the channel's output is not empty.
3946 * Otherwise it means we cannot add more data. */
3947 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003948 return 1;
3949
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003950 /* If we are waiting for space in the response buffer, we
3951 * must set the flag WAKERESWR. This flag required the task
3952 * wake up if any activity is detected on the response buffer.
3953 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003954 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003955 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003956 else
3957 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003958 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003959 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003960
3961 return 1;
3962}
3963
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003964/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003965 * yield the LUA process, and resume it without checking the
3966 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003967 *
3968 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003969 */
3970__LJMP static int hlua_channel_send(lua_State *L)
3971{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003972 struct channel *chn;
3973
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003974 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003975 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3976 if (IS_HTX_STRM(chn_strm(chn))) {
3977 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3978 WILL_LJMP(lua_error(L));
3979 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003980 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003981 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003982}
3983
3984/* This function forward and amount of butes. The data pass from
3985 * the input side of the buffer to the output side, and can be
3986 * forwarded. This function never fails.
3987 *
3988 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003989 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003990 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003991__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003992{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003993 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003994 struct filter *filter;
3995 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003996 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003997 struct hlua *hlua;
3998
3999 /* Get hlua struct, or NULL if we execute from main lua state */
4000 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004001 if (!hlua) {
4002 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004003 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004004 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004005
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004006 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004007 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004008 l = MAY_LJMP(luaL_checkinteger(L, -1));
4009
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004010 offset = co_data(chn);
4011 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004012
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004013 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4014 if (filter && !hlua_filter_from_payload(filter))
4015 WILL_LJMP(lua_error(L));
4016
4017 max = fwd - l;
4018 if (max > len)
4019 max = len;
4020
4021 if (filter) {
4022 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4023
4024 FLT_OFF(filter, chn) += max;
4025 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4026 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4027 }
4028 else
4029 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004030
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004031 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004032 lua_pop(L, 1);
4033 lua_pushinteger(L, l);
4034
4035 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004036 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004037 /* The the input channel or the output channel are closed, we
4038 * must return the amount of data forwarded.
4039 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004040 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004041 return 1;
4042
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004043 /* If we are waiting for space data in the response buffer, we
4044 * must set the flag WAKERESWR. This flag required the task
4045 * wake up if any activity is detected on the response buffer.
4046 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004047 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004048 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004049 else
4050 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004051
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004052 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004053 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004054 }
4055
4056 return 1;
4057}
4058
4059/* Just check the input and prepare the stack for the previous
4060 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004061 *
4062 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004063 */
4064__LJMP static int hlua_channel_forward(lua_State *L)
4065{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004066 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004067
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004068 MAY_LJMP(check_args(L, 2, "forward"));
4069 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4070 if (IS_HTX_STRM(chn_strm(chn))) {
4071 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4072 WILL_LJMP(lua_error(L));
4073 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004074 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004075 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004076}
4077
4078/* Just returns the number of bytes available in the input
4079 * side of the buffer. This function never fails.
4080 */
4081__LJMP static int hlua_channel_get_in_len(lua_State *L)
4082{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004083 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004084 struct filter *filter;
4085 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004086
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004087 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004088 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004089
4090 output = co_data(chn);
4091 input = ci_data(chn);
4092 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4093 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4094 lua_pushinteger(L, input);
4095 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004096 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004097
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004098 lua_pushinteger(L, htx->data - co_data(chn));
4099 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004100 return 1;
4101}
4102
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004103/* Returns true if the channel is full. */
4104__LJMP static int hlua_channel_is_full(lua_State *L)
4105{
4106 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004107
4108 MAY_LJMP(check_args(L, 1, "is_full"));
4109 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004110 /* ignore the reserve, we are not on a producer side (ie in an
4111 * applet).
4112 */
4113 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004114 return 1;
4115}
4116
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004117/* Returns true if the channel may still receive data. */
4118__LJMP static int hlua_channel_may_recv(lua_State *L)
4119{
4120 struct channel *chn;
4121
4122 MAY_LJMP(check_args(L, 1, "may_recv"));
4123 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4124 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4125 return 1;
4126}
4127
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004128/* Returns true if the channel is the response channel. */
4129__LJMP static int hlua_channel_is_resp(lua_State *L)
4130{
4131 struct channel *chn;
4132
4133 MAY_LJMP(check_args(L, 1, "is_resp"));
4134 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4135
4136 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4137 return 1;
4138}
4139
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004140/* Just returns the number of bytes available in the output
4141 * side of the buffer. This function never fails.
4142 */
4143__LJMP static int hlua_channel_get_out_len(lua_State *L)
4144{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004145 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004146 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004147
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004148 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004149 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004150
4151 output = co_data(chn);
4152 input = ci_data(chn);
4153 hlua_channel_filter(L, 1, chn, &output, &input);
4154
4155 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004156 return 1;
4157}
4158
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004159/*
4160 *
4161 *
4162 * Class Fetches
4163 *
4164 *
4165 */
4166
4167/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004168 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004169 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004170__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004171{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004172 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004173}
4174
4175/* This function creates and push in the stack a fetch object according
4176 * with a current TXN.
4177 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004178static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004179{
Willy Tarreau7073c472015-04-06 11:15:40 +02004180 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004181
4182 /* Check stack size. */
4183 if (!lua_checkstack(L, 3))
4184 return 0;
4185
4186 /* Create the object: obj[0] = userdata.
4187 * Note that the base of the Fetches object is the
4188 * transaction object.
4189 */
4190 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004191 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004192 lua_rawseti(L, -2, 0);
4193
Willy Tarreau7073c472015-04-06 11:15:40 +02004194 hsmp->s = txn->s;
4195 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004196 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004197 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004198
4199 /* Pop a class sesison metatable and affect it to the userdata. */
4200 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4201 lua_setmetatable(L, -2);
4202
4203 return 1;
4204}
4205
4206/* This function is an LUA binding. It is called with each sample-fetch.
4207 * It uses closure argument to store the associated sample-fetch. It
4208 * returns only one argument or throws an error. An error is thrown
4209 * only if an error is encountered during the argument parsing. If
4210 * the "sample-fetch" function fails, nil is returned.
4211 */
4212__LJMP static int hlua_run_sample_fetch(lua_State *L)
4213{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004214 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004215 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004216 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004217 int i;
4218 struct sample smp;
4219
4220 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004221 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004222
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004223 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004224 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004225
Thierry FOURNIERca988662015-12-20 18:43:03 +01004226 /* Check execution authorization. */
4227 if (f->use & SMP_USE_HTTP_ANY &&
4228 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4229 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4230 "is not available in Lua services", f->kw);
4231 WILL_LJMP(lua_error(L));
4232 }
4233
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004234 /* Get extra arguments. */
4235 for (i = 0; i < lua_gettop(L) - 1; i++) {
4236 if (i >= ARGM_NBARGS)
4237 break;
4238 hlua_lua2arg(L, i + 2, &args[i]);
4239 }
4240 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004241 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004242
4243 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004244 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004245
4246 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004247 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004248 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004249 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004250 }
4251
4252 /* Initialise the sample. */
4253 memset(&smp, 0, sizeof(smp));
4254
4255 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004256 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004257 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004258 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004259 lua_pushstring(L, "");
4260 else
4261 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004262 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004263 }
4264
4265 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004266 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004267 hlua_smp2lua_str(L, &smp);
4268 else
4269 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004270
4271 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004272 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004273 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004274
4275 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004276 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004277 WILL_LJMP(lua_error(L));
4278 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004279}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004280
4281/*
4282 *
4283 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004284 * Class Converters
4285 *
4286 *
4287 */
4288
4289/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004290 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004291 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004292__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004293{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004294 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004295}
4296
4297/* This function creates and push in the stack a Converters object
4298 * according with a current TXN.
4299 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004300static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004301{
Willy Tarreau7073c472015-04-06 11:15:40 +02004302 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004303
4304 /* Check stack size. */
4305 if (!lua_checkstack(L, 3))
4306 return 0;
4307
4308 /* Create the object: obj[0] = userdata.
4309 * Note that the base of the Converters object is the
4310 * same than the TXN object.
4311 */
4312 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004313 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004314 lua_rawseti(L, -2, 0);
4315
Willy Tarreau7073c472015-04-06 11:15:40 +02004316 hsmp->s = txn->s;
4317 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004318 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004319 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004320
Willy Tarreau87b09662015-04-03 00:22:06 +02004321 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004322 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4323 lua_setmetatable(L, -2);
4324
4325 return 1;
4326}
4327
4328/* This function is an LUA binding. It is called with each converter.
4329 * It uses closure argument to store the associated converter. It
4330 * returns only one argument or throws an error. An error is thrown
4331 * only if an error is encountered during the argument parsing. If
4332 * the converter function function fails, nil is returned.
4333 */
4334__LJMP static int hlua_run_sample_conv(lua_State *L)
4335{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004336 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004337 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004338 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004339 int i;
4340 struct sample smp;
4341
4342 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004343 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004344
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004345 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004346 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004347
4348 /* Get extra arguments. */
4349 for (i = 0; i < lua_gettop(L) - 2; i++) {
4350 if (i >= ARGM_NBARGS)
4351 break;
4352 hlua_lua2arg(L, i + 3, &args[i]);
4353 }
4354 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004355 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004356
4357 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004358 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004359
4360 /* Run the special args checker. */
4361 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4362 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004363 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004364 }
4365
4366 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004367 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004368 if (!hlua_lua2smp(L, 2, &smp)) {
4369 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004370 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004371 }
4372
Willy Tarreau1777ea62016-03-10 16:15:46 +01004373 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4374
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004375 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004376 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004377 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004378 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004379 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004380 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004381 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4382 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004383 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004384 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004385 }
4386
4387 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004388 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004389 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004390 lua_pushstring(L, "");
4391 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004392 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004393 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004394 }
4395
4396 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004397 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004398 hlua_smp2lua_str(L, &smp);
4399 else
4400 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004401 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004402 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004403 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004404
4405 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004406 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004407 WILL_LJMP(lua_error(L));
4408 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004409}
4410
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004411/*
4412 *
4413 *
4414 * Class AppletTCP
4415 *
4416 *
4417 */
4418
4419/* Returns a struct hlua_txn if the stack entry "ud" is
4420 * a class stream, otherwise it throws an error.
4421 */
4422__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4423{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004424 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004425}
4426
4427/* This function creates and push in the stack an Applet object
4428 * according with a current TXN.
4429 */
4430static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4431{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004432 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004433 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004434 struct proxy *p;
4435
4436 ALREADY_CHECKED(s);
4437 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004438
4439 /* Check stack size. */
4440 if (!lua_checkstack(L, 3))
4441 return 0;
4442
4443 /* Create the object: obj[0] = userdata.
4444 * Note that the base of the Converters object is the
4445 * same than the TXN object.
4446 */
4447 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004448 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004449 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004450 luactx->appctx = ctx;
4451 luactx->htxn.s = s;
4452 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004453
4454 /* Create the "f" field that contains a list of fetches. */
4455 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004456 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004457 return 0;
4458 lua_settable(L, -3);
4459
4460 /* Create the "sf" field that contains a list of stringsafe fetches. */
4461 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004462 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004463 return 0;
4464 lua_settable(L, -3);
4465
4466 /* Create the "c" field that contains a list of converters. */
4467 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004468 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004469 return 0;
4470 lua_settable(L, -3);
4471
4472 /* Create the "sc" field that contains a list of stringsafe converters. */
4473 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004474 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004475 return 0;
4476 lua_settable(L, -3);
4477
4478 /* Pop a class stream metatable and affect it to the table. */
4479 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4480 lua_setmetatable(L, -2);
4481
4482 return 1;
4483}
4484
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004485__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4486{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004487 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004488 struct stream *s;
4489 const char *name;
4490 size_t len;
4491 struct sample smp;
4492
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004493 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4494 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004495
4496 /* It is useles to retrieve the stream, but this function
4497 * runs only in a stream context.
4498 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004499 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004500 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004501 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004502
4503 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004504 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004505 hlua_lua2smp(L, 3, &smp);
4506
4507 /* Store the sample in a variable. */
4508 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004509
4510 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4511 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4512 else
4513 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4514
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004515 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004516}
4517
4518__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4519{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004520 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004521 struct stream *s;
4522 const char *name;
4523 size_t len;
4524 struct sample smp;
4525
4526 MAY_LJMP(check_args(L, 2, "unset_var"));
4527
4528 /* It is useles to retrieve the stream, but this function
4529 * runs only in a stream context.
4530 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004531 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004532 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004533 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004534
4535 /* Unset the variable. */
4536 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004537 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4538 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004539}
4540
4541__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4542{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004543 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004544 struct stream *s;
4545 const char *name;
4546 size_t len;
4547 struct sample smp;
4548
4549 MAY_LJMP(check_args(L, 2, "get_var"));
4550
4551 /* It is useles to retrieve the stream, but this function
4552 * runs only in a stream context.
4553 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004554 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004555 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004556 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004557
4558 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004559 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004560 lua_pushnil(L);
4561 return 1;
4562 }
4563
4564 return hlua_smp2lua(L, &smp);
4565}
4566
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004567__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4568{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004569 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4570 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004571 struct hlua *hlua;
4572
4573 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004574 if (!s->hlua)
4575 return 0;
4576 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004577
4578 MAY_LJMP(check_args(L, 2, "set_priv"));
4579
4580 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004581 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004582
4583 /* Get and store new value. */
4584 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4585 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4586
4587 return 0;
4588}
4589
4590__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4591{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004592 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4593 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004594 struct hlua *hlua;
4595
4596 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004597 if (!s->hlua) {
4598 lua_pushnil(L);
4599 return 1;
4600 }
4601 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004602
4603 /* Push configuration index in the stack. */
4604 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4605
4606 return 1;
4607}
4608
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004609/* If expected data not yet available, it returns a yield. This function
4610 * consumes the data in the buffer. It returns a string containing the
4611 * data. This string can be empty.
4612 */
4613__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4614{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004615 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004616 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004617 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004618 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004619 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004620 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004621 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004622
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004623 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004624 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004625
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004626 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004627 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004628 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004629 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004630 }
4631
4632 /* End of data: commit the total strings and return. */
4633 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004634 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004635 return 1;
4636 }
4637
4638 /* Ensure that the block 2 length is usable. */
4639 if (ret == 1)
4640 len2 = 0;
4641
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004642 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004643 luaL_addlstring(&luactx->b, blk1, len1);
4644 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004645
4646 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004647 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004648 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004649 return 1;
4650}
4651
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004652/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004653__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4654{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004655 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004656
4657 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004658 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004659
4660 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4661}
4662
4663/* If expected data not yet available, it returns a yield. This function
4664 * consumes the data in the buffer. It returns a string containing the
4665 * data. This string can be empty.
4666 */
4667__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4668{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004669 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004670 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004671 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004672 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004673 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004674 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004675 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004676 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004677
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004678 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004679 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004680
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004681 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004682 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004683 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004684 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004685 }
4686
4687 /* End of data: commit the total strings and return. */
4688 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004689 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004690 return 1;
4691 }
4692
4693 /* Ensure that the block 2 length is usable. */
4694 if (ret == 1)
4695 len2 = 0;
4696
4697 if (len == -1) {
4698
4699 /* If len == -1, catenate all the data avalaile and
4700 * yield because we want to get all the data until
4701 * the end of data stream.
4702 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004703 luaL_addlstring(&luactx->b, blk1, len1);
4704 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004705 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004706 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004707 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004708
4709 } else {
4710
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004711 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004712 if (len1 > len)
4713 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004714 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004715 len -= len1;
4716
4717 /* Copy the second block. */
4718 if (len2 > len)
4719 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004720 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004721 len -= len2;
4722
4723 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004724 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004725
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004726 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004727 if (len > 0) {
4728 lua_pushinteger(L, len);
4729 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004730 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004731 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004732 }
4733
4734 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004735 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004736 return 1;
4737 }
4738
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004739 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004740 hlua_pusherror(L, "Lua: internal error");
4741 WILL_LJMP(lua_error(L));
4742 return 0;
4743}
4744
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004745/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004746__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4747{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004748 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004749 int len = -1;
4750
4751 if (lua_gettop(L) > 2)
4752 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4753 if (lua_gettop(L) >= 2) {
4754 len = MAY_LJMP(luaL_checkinteger(L, 2));
4755 lua_pop(L, 1);
4756 }
4757
4758 /* Confirm or set the required length */
4759 lua_pushinteger(L, len);
4760
4761 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004762 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004763
4764 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4765}
4766
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004767/* Append data in the output side of the buffer. This data is immediately
4768 * sent. The function returns the amount of data written. If the buffer
4769 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004770 * if the channel is closed.
4771 */
4772__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4773{
4774 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004775 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004776 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4777 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004778 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004779 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004780 int max;
4781
4782 /* Get the max amount of data which can write as input in the channel. */
4783 max = channel_recv_max(chn);
4784 if (max > (len - l))
4785 max = len - l;
4786
4787 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004788 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004789
4790 /* update counters. */
4791 l += max;
4792 lua_pop(L, 1);
4793 lua_pushinteger(L, l);
4794
4795 /* If some data is not send, declares the situation to the
4796 * applet, and returns a yield.
4797 */
4798 if (l < len) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02004799 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02004800 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004801 }
4802
4803 return 1;
4804}
4805
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004806/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004807 * yield the LUA process, and resume it without checking the
4808 * input arguments.
4809 */
4810__LJMP static int hlua_applet_tcp_send(lua_State *L)
4811{
4812 MAY_LJMP(check_args(L, 2, "send"));
4813 lua_pushinteger(L, 0);
4814
4815 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4816}
4817
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004818/*
4819 *
4820 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004821 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004822 *
4823 *
4824 */
4825
4826/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004827 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004828 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004829__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004830{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004831 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004832}
4833
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004834/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004835 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004836 * It relies on the caller to have already reserved the room in ctx->svcctx
4837 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004838 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004839static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004840{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004841 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004842 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004843 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004844 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004845 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004846 struct htx *htx;
4847 struct htx_blk *blk;
4848 struct htx_sl *sl;
4849 struct ist path;
4850 unsigned long long len = 0;
4851 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004852 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004853
4854 /* Check stack size. */
4855 if (!lua_checkstack(L, 3))
4856 return 0;
4857
4858 /* Create the object: obj[0] = userdata.
4859 * Note that the base of the Converters object is the
4860 * same than the TXN object.
4861 */
4862 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004863 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004864 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004865 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004866 http_ctx->status = 200; /* Default status code returned. */
4867 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004868 luactx->htxn.s = s;
4869 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004870
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004871 /* Create the "f" field that contains a list of fetches. */
4872 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004873 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004874 return 0;
4875 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004876
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004877 /* Create the "sf" field that contains a list of stringsafe fetches. */
4878 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004879 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004880 return 0;
4881 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004882
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004883 /* Create the "c" field that contains a list of converters. */
4884 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004885 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004886 return 0;
4887 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004888
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004889 /* Create the "sc" field that contains a list of stringsafe converters. */
4890 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004891 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004892 return 0;
4893 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004894
Christopher Fauleta2097962019-07-15 16:25:33 +02004895 htx = htxbuf(&s->req.buf);
4896 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004897 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004898 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004899
Christopher Fauleta2097962019-07-15 16:25:33 +02004900 /* Stores the request method. */
4901 lua_pushstring(L, "method");
4902 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4903 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004904
Christopher Fauleta2097962019-07-15 16:25:33 +02004905 /* Stores the http version. */
4906 lua_pushstring(L, "version");
4907 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4908 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004909
Christopher Fauleta2097962019-07-15 16:25:33 +02004910 /* creates an array of headers. hlua_http_get_headers() crates and push
4911 * the array on the top of the stack.
4912 */
4913 lua_pushstring(L, "headers");
4914 htxn.s = s;
4915 htxn.p = px;
4916 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004917 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004918 return 0;
4919 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004920
Amaury Denoyellec453f952021-07-06 11:40:12 +02004921 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4922 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004923 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004924 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004925
Christopher Fauleta2097962019-07-15 16:25:33 +02004926 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004927 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004928 q = p;
4929 while (q < end && *q != '?')
4930 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004931
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004932 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004933 lua_pushstring(L, "path");
4934 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004935 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004936
Christopher Fauleta2097962019-07-15 16:25:33 +02004937 /* Stores the query string. */
4938 lua_pushstring(L, "qs");
4939 if (*q == '?')
4940 q++;
4941 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004942 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004943 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004944
Christopher Fauleta2097962019-07-15 16:25:33 +02004945 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4946 struct htx_blk *blk = htx_get_blk(htx, pos);
4947 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004948
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004949 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004950 break;
4951 if (type == HTX_BLK_DATA)
4952 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004953 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01004954 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02004955 len += htx->extra;
4956
4957 /* Stores the request path. */
4958 lua_pushstring(L, "length");
4959 lua_pushinteger(L, len);
4960 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004961
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004962 /* Create an empty array of HTTP request headers. */
4963 lua_pushstring(L, "response");
4964 lua_newtable(L);
4965 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004966
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004967 /* Pop a class stream metatable and affect it to the table. */
4968 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4969 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004970
4971 return 1;
4972}
4973
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004974__LJMP static int hlua_applet_http_set_var(lua_State *L)
4975{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004976 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004977 struct stream *s;
4978 const char *name;
4979 size_t len;
4980 struct sample smp;
4981
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004982 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4983 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004984
4985 /* It is useles to retrieve the stream, but this function
4986 * runs only in a stream context.
4987 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004988 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004989 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004990 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004991
4992 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004993 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004994 hlua_lua2smp(L, 3, &smp);
4995
4996 /* Store the sample in a variable. */
4997 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004998
4999 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5000 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5001 else
5002 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5003
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005004 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005005}
5006
5007__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5008{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005009 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005010 struct stream *s;
5011 const char *name;
5012 size_t len;
5013 struct sample smp;
5014
5015 MAY_LJMP(check_args(L, 2, "unset_var"));
5016
5017 /* It is useles to retrieve the stream, but this function
5018 * runs only in a stream context.
5019 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005020 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005021 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005022 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005023
5024 /* Unset the variable. */
5025 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005026 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5027 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005028}
5029
5030__LJMP static int hlua_applet_http_get_var(lua_State *L)
5031{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005032 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005033 struct stream *s;
5034 const char *name;
5035 size_t len;
5036 struct sample smp;
5037
5038 MAY_LJMP(check_args(L, 2, "get_var"));
5039
5040 /* It is useles to retrieve the stream, but this function
5041 * runs only in a stream context.
5042 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005043 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005044 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005045 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005046
5047 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005048 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005049 lua_pushnil(L);
5050 return 1;
5051 }
5052
5053 return hlua_smp2lua(L, &smp);
5054}
5055
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005056__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5057{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005058 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5059 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005060 struct hlua *hlua;
5061
5062 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005063 if (!s->hlua)
5064 return 0;
5065 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005066
5067 MAY_LJMP(check_args(L, 2, "set_priv"));
5068
5069 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005070 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005071
5072 /* Get and store new value. */
5073 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5074 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5075
5076 return 0;
5077}
5078
5079__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5080{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005081 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5082 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005083 struct hlua *hlua;
5084
5085 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005086 if (!s->hlua) {
5087 lua_pushnil(L);
5088 return 1;
5089 }
5090 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005091
5092 /* Push configuration index in the stack. */
5093 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5094
5095 return 1;
5096}
5097
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005098/* If expected data not yet available, it returns a yield. This function
5099 * consumes the data in the buffer. It returns a string containing the
5100 * data. This string can be empty.
5101 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005102__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005103{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005104 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005105 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005106 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005107 struct htx *htx;
5108 struct htx_blk *blk;
5109 size_t count;
5110 int stop = 0;
5111
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005112 htx = htx_from_buf(&req->buf);
5113 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005114 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005115
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005116 while (count && !stop && blk) {
5117 enum htx_blk_type type = htx_get_blk_type(blk);
5118 uint32_t sz = htx_get_blksz(blk);
5119 struct ist v;
5120 uint32_t vlen;
5121 char *nl;
5122
5123 vlen = sz;
5124 if (vlen > count) {
5125 if (type != HTX_BLK_DATA)
5126 break;
5127 vlen = count;
5128 }
5129
5130 switch (type) {
5131 case HTX_BLK_UNUSED:
5132 break;
5133
5134 case HTX_BLK_DATA:
5135 v = htx_get_blk_value(htx, blk);
5136 v.len = vlen;
5137 nl = istchr(v, '\n');
5138 if (nl != NULL) {
5139 stop = 1;
5140 vlen = nl - v.ptr + 1;
5141 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005142 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005143 break;
5144
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005145 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005146 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005147 stop = 1;
5148 break;
5149
5150 default:
5151 break;
5152 }
5153
Willy Tarreau84240042022-02-28 16:51:23 +01005154 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005155 count -= vlen;
5156 if (sz == vlen)
5157 blk = htx_remove_blk(htx, blk);
5158 else {
5159 htx_cut_data_blk(htx, blk, vlen);
5160 break;
5161 }
5162 }
5163
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005164 /* The message was fully consumed and no more data are expected
5165 * (EOM flag set).
5166 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005167 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005168 stop = 1;
5169
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005170 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005171 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005172 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005173 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005174 }
5175
5176 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005177 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005178 return 1;
5179}
5180
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005181
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005182/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005183__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005184{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005185 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005186
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005187 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005188 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005189
Christopher Fauleta2097962019-07-15 16:25:33 +02005190 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005191}
5192
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005193/* If expected data not yet available, it returns a yield. This function
5194 * consumes the data in the buffer. It returns a string containing the
5195 * data. This string can be empty.
5196 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005197__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005198{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005199 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005200 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005201 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005202 struct htx *htx;
5203 struct htx_blk *blk;
5204 size_t count;
5205 int len;
5206
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005207 htx = htx_from_buf(&req->buf);
5208 len = MAY_LJMP(luaL_checkinteger(L, 2));
5209 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005210 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005211 while (count && len && blk) {
5212 enum htx_blk_type type = htx_get_blk_type(blk);
5213 uint32_t sz = htx_get_blksz(blk);
5214 struct ist v;
5215 uint32_t vlen;
5216
5217 vlen = sz;
5218 if (len > 0 && vlen > len)
5219 vlen = len;
5220 if (vlen > count) {
5221 if (type != HTX_BLK_DATA)
5222 break;
5223 vlen = count;
5224 }
5225
5226 switch (type) {
5227 case HTX_BLK_UNUSED:
5228 break;
5229
5230 case HTX_BLK_DATA:
5231 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005232 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005233 break;
5234
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005235 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005236 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005237 len = 0;
5238 break;
5239
5240 default:
5241 break;
5242 }
5243
Willy Tarreau84240042022-02-28 16:51:23 +01005244 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005245 count -= vlen;
5246 if (len > 0)
5247 len -= vlen;
5248 if (sz == vlen)
5249 blk = htx_remove_blk(htx, blk);
5250 else {
5251 htx_cut_data_blk(htx, blk, vlen);
5252 break;
5253 }
5254 }
5255
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005256 /* The message was fully consumed and no more data are expected
5257 * (EOM flag set).
5258 */
Christopher Faulet904763f2023-03-22 14:53:11 +01005259 if (htx_is_empty(htx) && (sc->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005260 len = 0;
5261
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005262 htx_to_buf(htx, &req->buf);
5263
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005264 /* If we are no other data available, yield waiting for new data. */
5265 if (len) {
5266 if (len > 0) {
5267 lua_pushinteger(L, len);
5268 lua_replace(L, 2);
5269 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005270 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005271 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005272 }
5273
5274 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005275 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005276 return 1;
5277}
5278
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005279/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005280__LJMP static int hlua_applet_http_recv(lua_State *L)
5281{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005282 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005283 int len = -1;
5284
5285 /* Check arguments. */
5286 if (lua_gettop(L) > 2)
5287 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5288 if (lua_gettop(L) >= 2) {
5289 len = MAY_LJMP(luaL_checkinteger(L, 2));
5290 lua_pop(L, 1);
5291 }
5292
Christopher Fauleta2097962019-07-15 16:25:33 +02005293 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005294
Christopher Fauleta2097962019-07-15 16:25:33 +02005295 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005296 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005297
Christopher Fauleta2097962019-07-15 16:25:33 +02005298 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005299}
5300
5301/* Append data in the output side of the buffer. This data is immediately
5302 * sent. The function returns the amount of data written. If the buffer
5303 * cannot contain the data, the function yields. The function returns -1
5304 * if the channel is closed.
5305 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005306__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005307{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005308 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005309 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005310 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005311 struct htx *htx = htx_from_buf(&res->buf);
5312 const char *data;
5313 size_t len;
5314 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5315 int max;
5316
Christopher Faulet9060fc02019-07-03 11:39:30 +02005317 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005318 if (!max)
5319 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005320
5321 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5322
5323 /* Get the max amount of data which can write as input in the channel. */
5324 if (max > (len - l))
5325 max = len - l;
5326
5327 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005328 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005329 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005330
5331 /* update counters. */
5332 l += max;
5333 lua_pop(L, 1);
5334 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005335
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005336 /* If some data is not send, declares the situation to the
5337 * applet, and returns a yield.
5338 */
5339 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005340 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005341 htx_to_buf(htx, &res->buf);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005342 sc_need_room(sc);
Willy Tarreau9635e032018-10-16 17:52:55 +02005343 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005344 }
5345
Christopher Fauleta2097962019-07-15 16:25:33 +02005346 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005347 return 1;
5348}
5349
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005350/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005351 * yield the LUA process, and resume it without checking the
5352 * input arguments.
5353 */
5354__LJMP static int hlua_applet_http_send(lua_State *L)
5355{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005356 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005357 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005358
5359 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005360 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005361 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5362 WILL_LJMP(lua_error(L));
5363 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005364
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005365 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005366 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005367
Christopher Fauleta2097962019-07-15 16:25:33 +02005368 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005369}
5370
5371__LJMP static int hlua_applet_http_addheader(lua_State *L)
5372{
5373 const char *name;
5374 int ret;
5375
5376 MAY_LJMP(hlua_checkapplet_http(L, 1));
5377 name = MAY_LJMP(luaL_checkstring(L, 2));
5378 MAY_LJMP(luaL_checkstring(L, 3));
5379
5380 /* Push in the stack the "response" entry. */
5381 ret = lua_getfield(L, 1, "response");
5382 if (ret != LUA_TTABLE) {
5383 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5384 "is expected as an array. %s found", lua_typename(L, ret));
5385 WILL_LJMP(lua_error(L));
5386 }
5387
5388 /* check if the header is already registered if it is not
5389 * the case, register it.
5390 */
5391 ret = lua_getfield(L, -1, name);
5392 if (ret == LUA_TNIL) {
5393
5394 /* Entry not found. */
5395 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5396
5397 /* Insert the new header name in the array in the top of the stack.
5398 * It left the new array in the top of the stack.
5399 */
5400 lua_newtable(L);
5401 lua_pushvalue(L, 2);
5402 lua_pushvalue(L, -2);
5403 lua_settable(L, -4);
5404
5405 } else if (ret != LUA_TTABLE) {
5406
5407 /* corruption error. */
5408 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5409 "is expected as an array. %s found", name, lua_typename(L, ret));
5410 WILL_LJMP(lua_error(L));
5411 }
5412
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005413 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005414 * the header value as new entry.
5415 */
5416 lua_pushvalue(L, 3);
5417 ret = lua_rawlen(L, -2);
5418 lua_rawseti(L, -2, ret + 1);
5419 lua_pushboolean(L, 1);
5420 return 1;
5421}
5422
5423__LJMP static int hlua_applet_http_status(lua_State *L)
5424{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005425 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005426 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005427 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005428 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005429
5430 if (status < 100 || status > 599) {
5431 lua_pushboolean(L, 0);
5432 return 1;
5433 }
5434
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005435 http_ctx->status = status;
5436 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005437 lua_pushboolean(L, 1);
5438 return 1;
5439}
5440
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005441
Christopher Fauleta2097962019-07-15 16:25:33 +02005442__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005443{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005444 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005445 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005446 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005447 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005448 struct htx *htx;
5449 struct htx_sl *sl;
5450 struct h1m h1m;
5451 const char *status, *reason;
5452 const char *name, *value;
5453 size_t nlen, vlen;
5454 unsigned int flags;
5455
5456 /* Send the message at once. */
5457 htx = htx_from_buf(&res->buf);
5458 h1m_init_res(&h1m);
5459
5460 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005461 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5462 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005463 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005464 reason = http_get_reason(http_ctx->status);
5465 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005466 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5467 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5468 }
5469 else {
5470 flags = HTX_SL_F_IS_RESP;
5471 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5472 }
5473 if (!sl) {
5474 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005475 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005476 WILL_LJMP(lua_error(L));
5477 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005478 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005479
5480 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005481 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5482 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005483 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005484 WILL_LJMP(lua_error(L));
5485 }
5486
5487 /* Browse the list of headers. */
5488 lua_pushnil(L);
5489 while(lua_next(L, -2) != 0) {
5490 /* We expect a string as -2. */
5491 if (lua_type(L, -2) != LUA_TSTRING) {
5492 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005493 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005494 lua_typename(L, lua_type(L, -2)));
5495 WILL_LJMP(lua_error(L));
5496 }
5497 name = lua_tolstring(L, -2, &nlen);
5498
5499 /* We expect an array as -1. */
5500 if (lua_type(L, -1) != LUA_TTABLE) {
5501 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 +02005502 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005503 name,
5504 lua_typename(L, lua_type(L, -1)));
5505 WILL_LJMP(lua_error(L));
5506 }
5507
5508 /* Browse the table who is on the top of the stack. */
5509 lua_pushnil(L);
5510 while(lua_next(L, -2) != 0) {
5511 int id;
5512
5513 /* We expect a number as -2. */
5514 if (lua_type(L, -2) != LUA_TNUMBER) {
5515 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 +02005516 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005517 name,
5518 lua_typename(L, lua_type(L, -2)));
5519 WILL_LJMP(lua_error(L));
5520 }
5521 id = lua_tointeger(L, -2);
5522
5523 /* We expect a string as -2. */
5524 if (lua_type(L, -1) != LUA_TSTRING) {
5525 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 +02005526 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005527 name, id,
5528 lua_typename(L, lua_type(L, -1)));
5529 WILL_LJMP(lua_error(L));
5530 }
5531 value = lua_tolstring(L, -1, &vlen);
5532
5533 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005534 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5535 int ret;
5536
5537 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5538 if (ret < 0) {
5539 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5540 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5541 name);
5542 WILL_LJMP(lua_error(L));
5543 }
5544 else if (ret == 0)
5545 goto next; /* Skip it */
5546 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005547 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5548 struct ist v = ist2(value, vlen);
5549 int ret;
5550
5551 ret = h1_parse_cont_len_header(&h1m, &v);
5552 if (ret < 0) {
5553 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005554 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005555 name);
5556 WILL_LJMP(lua_error(L));
5557 }
5558 else if (ret == 0)
5559 goto next; /* Skip it */
5560 }
5561
5562 /* Add a new header */
5563 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5564 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005565 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005566 name);
5567 WILL_LJMP(lua_error(L));
5568 }
5569 next:
5570 /* Remove the array from the stack, and get next element with a remaining string. */
5571 lua_pop(L, 1);
5572 }
5573
5574 /* Remove the array from the stack, and get next element with a remaining string. */
5575 lua_pop(L, 1);
5576 }
5577
5578 if (h1m.flags & H1_MF_CHNK)
5579 h1m.flags &= ~H1_MF_CLEN;
5580 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5581 h1m.flags |= H1_MF_XFER_LEN;
5582
5583 /* Uset HTX start-line flags */
5584 if (h1m.flags & H1_MF_XFER_ENC)
5585 flags |= HTX_SL_F_XFER_ENC;
5586 if (h1m.flags & H1_MF_XFER_LEN) {
5587 flags |= HTX_SL_F_XFER_LEN;
5588 if (h1m.flags & H1_MF_CHNK)
5589 flags |= HTX_SL_F_CHNK;
5590 else if (h1m.flags & H1_MF_CLEN)
5591 flags |= HTX_SL_F_CLEN;
5592 if (h1m.body_len == 0)
5593 flags |= HTX_SL_F_BODYLESS;
5594 }
5595 sl->flags |= flags;
5596
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005597 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005598 * and the status code implies the presence of a message body, we must
5599 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005600 * for the keepalive compliance. If the applet announces a transfer-encoding
5601 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005602 */
5603 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005604 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005605 /* Add a new header */
5606 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5607 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5608 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005609 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005610 WILL_LJMP(lua_error(L));
5611 }
5612 }
5613
5614 /* Finalize headers. */
5615 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5616 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005617 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005618 WILL_LJMP(lua_error(L));
5619 }
5620
5621 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5622 b_reset(&res->buf);
5623 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5624 WILL_LJMP(lua_error(L));
5625 }
5626
5627 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005628 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005629
5630 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005631 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005632 return 0;
5633
5634}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005635/* We will build the status line and the headers of the HTTP response.
5636 * We will try send at once if its not possible, we give back the hand
5637 * waiting for more room.
5638 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005639__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005640{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005641 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005642 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005643 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005644
5645 if (co_data(res)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02005646 sc_need_room(sc);
Christopher Fauleta2097962019-07-15 16:25:33 +02005647 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005648 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005649 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005650}
5651
5652
Christopher Fauleta2097962019-07-15 16:25:33 +02005653__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005654{
Christopher Fauleta2097962019-07-15 16:25:33 +02005655 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005656}
5657
Christopher Fauleta2097962019-07-15 16:25:33 +02005658/*
5659 *
5660 *
5661 * Class HTTP
5662 *
5663 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005664 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005665
5666/* Returns a struct hlua_txn if the stack entry "ud" is
5667 * a class stream, otherwise it throws an error.
5668 */
5669__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005670{
Christopher Fauleta2097962019-07-15 16:25:33 +02005671 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5672}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005673
Christopher Fauleta2097962019-07-15 16:25:33 +02005674/* This function creates and push in the stack a HTTP object
5675 * according with a current TXN.
5676 */
5677static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5678{
5679 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005680
Christopher Fauleta2097962019-07-15 16:25:33 +02005681 /* Check stack size. */
5682 if (!lua_checkstack(L, 3))
5683 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005684
Christopher Fauleta2097962019-07-15 16:25:33 +02005685 /* Create the object: obj[0] = userdata.
5686 * Note that the base of the Converters object is the
5687 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005688 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005689 lua_newtable(L);
5690 htxn = lua_newuserdata(L, sizeof(*htxn));
5691 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005692
5693 htxn->s = txn->s;
5694 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005695 htxn->dir = txn->dir;
5696 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005697
5698 /* Pop a class stream metatable and affect it to the table. */
5699 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5700 lua_setmetatable(L, -2);
5701
5702 return 1;
5703}
5704
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005705/* This function creates and returns an array containing the status-line
5706 * elements. This function does not fails.
5707 */
5708__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5709{
5710 /* Create the table. */
5711 lua_newtable(L);
5712
5713 if (sl->flags & HTX_SL_F_IS_RESP) {
5714 lua_pushstring(L, "version");
5715 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5716 lua_settable(L, -3);
5717 lua_pushstring(L, "code");
5718 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5719 lua_settable(L, -3);
5720 lua_pushstring(L, "reason");
5721 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5722 lua_settable(L, -3);
5723 }
5724 else {
5725 lua_pushstring(L, "method");
5726 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5727 lua_settable(L, -3);
5728 lua_pushstring(L, "uri");
5729 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5730 lua_settable(L, -3);
5731 lua_pushstring(L, "version");
5732 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5733 lua_settable(L, -3);
5734 }
5735 return 1;
5736}
5737
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005738/* This function creates ans returns an array of HTTP headers.
5739 * This function does not fails. It is used as wrapper with the
5740 * 2 following functions.
5741 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005742__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005743{
Christopher Fauleta2097962019-07-15 16:25:33 +02005744 struct htx *htx;
5745 int32_t pos;
5746
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005747 /* Create the table. */
5748 lua_newtable(L);
5749
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005750
Christopher Fauleta2097962019-07-15 16:25:33 +02005751 htx = htxbuf(&msg->chn->buf);
5752 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5753 struct htx_blk *blk = htx_get_blk(htx, pos);
5754 enum htx_blk_type type = htx_get_blk_type(blk);
5755 struct ist n, v;
5756 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005757
Christopher Fauleta2097962019-07-15 16:25:33 +02005758 if (type == HTX_BLK_HDR) {
5759 n = htx_get_blk_name(htx,blk);
5760 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005761 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005762 else if (type == HTX_BLK_EOH)
5763 break;
5764 else
5765 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005766
Christopher Fauleta2097962019-07-15 16:25:33 +02005767 /* Check for existing entry:
5768 * assume that the table is on the top of the stack, and
5769 * push the key in the stack, the function lua_gettable()
5770 * perform the lookup.
5771 */
5772 lua_pushlstring(L, n.ptr, n.len);
5773 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005774
Christopher Fauleta2097962019-07-15 16:25:33 +02005775 switch (lua_type(L, -1)) {
5776 case LUA_TNIL:
5777 /* Table not found, create it. */
5778 lua_pop(L, 1); /* remove the nil value. */
5779 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5780 lua_newtable(L); /* create and push empty table. */
5781 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5782 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5783 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005784 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005785
Christopher Fauleta2097962019-07-15 16:25:33 +02005786 case LUA_TTABLE:
5787 /* Entry found: push the value in the table. */
5788 len = lua_rawlen(L, -1);
5789 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5790 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5791 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5792 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005793
Christopher Fauleta2097962019-07-15 16:25:33 +02005794 default:
5795 /* Other cases are errors. */
5796 hlua_pusherror(L, "internal error during the parsing of headers.");
5797 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005798 }
5799 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005800 return 1;
5801}
5802
5803__LJMP static int hlua_http_req_get_headers(lua_State *L)
5804{
5805 struct hlua_txn *htxn;
5806
5807 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5808 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5809
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005810 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005811 WILL_LJMP(lua_error(L));
5812
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005813 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005814}
5815
5816__LJMP static int hlua_http_res_get_headers(lua_State *L)
5817{
5818 struct hlua_txn *htxn;
5819
5820 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5821 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5822
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005823 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005824 WILL_LJMP(lua_error(L));
5825
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005826 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005827}
5828
5829/* This function replace full header, or just a value in
5830 * the request or in the response. It is a wrapper fir the
5831 * 4 following functions.
5832 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005833__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005834{
5835 size_t name_len;
5836 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5837 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5838 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005839 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005840 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005841
Dragan Dosen26743032019-04-30 15:54:36 +02005842 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005843 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5844
Christopher Fauleta2097962019-07-15 16:25:33 +02005845 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005846 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005847 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005848 return 0;
5849}
5850
5851__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5852{
5853 struct hlua_txn *htxn;
5854
5855 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5856 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5857
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005858 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005859 WILL_LJMP(lua_error(L));
5860
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005861 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005862}
5863
5864__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5865{
5866 struct hlua_txn *htxn;
5867
5868 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5869 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5870
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005871 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005872 WILL_LJMP(lua_error(L));
5873
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005874 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005875}
5876
5877__LJMP static int hlua_http_req_rep_val(lua_State *L)
5878{
5879 struct hlua_txn *htxn;
5880
5881 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5882 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5883
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005884 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005885 WILL_LJMP(lua_error(L));
5886
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005887 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005888}
5889
5890__LJMP static int hlua_http_res_rep_val(lua_State *L)
5891{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005892 struct hlua_txn *htxn;
5893
5894 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5895 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5896
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005897 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005898 WILL_LJMP(lua_error(L));
5899
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005900 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005901}
5902
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005903/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005904 * It is a wrapper for the 2 following functions.
5905 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005906__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005907{
5908 size_t len;
5909 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005910 struct htx *htx = htxbuf(&msg->chn->buf);
5911 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005912
Christopher Fauleta2097962019-07-15 16:25:33 +02005913 ctx.blk = NULL;
5914 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5915 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005916 return 0;
5917}
5918
5919__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5920{
5921 struct hlua_txn *htxn;
5922
5923 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5924 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5925
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005926 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005927 WILL_LJMP(lua_error(L));
5928
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005929 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005930}
5931
5932__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5933{
5934 struct hlua_txn *htxn;
5935
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005936 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005937 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5938
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005939 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005940 WILL_LJMP(lua_error(L));
5941
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005942 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005943}
5944
5945/* This function adds an header. It is a wrapper used by
5946 * the 2 following functions.
5947 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005948__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005949{
5950 size_t name_len;
5951 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5952 size_t value_len;
5953 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005954 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005955
Christopher Fauleta2097962019-07-15 16:25:33 +02005956 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5957 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005958 return 0;
5959}
5960
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005961__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5962{
5963 struct hlua_txn *htxn;
5964
5965 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5966 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5967
5968 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5969 WILL_LJMP(lua_error(L));
5970
5971 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5972}
5973
5974__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5975{
5976 struct hlua_txn *htxn;
5977
5978 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5979 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5980
5981 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5982 WILL_LJMP(lua_error(L));
5983
5984 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5985}
5986
5987static int hlua_http_req_set_hdr(lua_State *L)
5988{
5989 struct hlua_txn *htxn;
5990
5991 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5992 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5993
5994 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5995 WILL_LJMP(lua_error(L));
5996
5997 hlua_http_del_hdr(L, &htxn->s->txn->req);
5998 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5999}
6000
6001static int hlua_http_res_set_hdr(lua_State *L)
6002{
6003 struct hlua_txn *htxn;
6004
6005 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6006 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6007
6008 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6009 WILL_LJMP(lua_error(L));
6010
6011 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6012 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6013}
6014
6015/* This function set the method. */
6016static int hlua_http_req_set_meth(lua_State *L)
6017{
6018 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6019 size_t name_len;
6020 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6021
6022 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6023 WILL_LJMP(lua_error(L));
6024
6025 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6026 return 1;
6027}
6028
6029/* This function set the method. */
6030static int hlua_http_req_set_path(lua_State *L)
6031{
6032 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6033 size_t name_len;
6034 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6035
6036 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6037 WILL_LJMP(lua_error(L));
6038
6039 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6040 return 1;
6041}
6042
6043/* This function set the query-string. */
6044static int hlua_http_req_set_query(lua_State *L)
6045{
6046 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6047 size_t name_len;
6048 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6049
6050 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6051 WILL_LJMP(lua_error(L));
6052
6053 /* Check length. */
6054 if (name_len > trash.size - 1) {
6055 lua_pushboolean(L, 0);
6056 return 1;
6057 }
6058
6059 /* Add the mark question as prefix. */
6060 chunk_reset(&trash);
6061 trash.area[trash.data++] = '?';
6062 memcpy(trash.area + trash.data, name, name_len);
6063 trash.data += name_len;
6064
6065 lua_pushboolean(L,
6066 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6067 return 1;
6068}
6069
6070/* This function set the uri. */
6071static int hlua_http_req_set_uri(lua_State *L)
6072{
6073 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6074 size_t name_len;
6075 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6076
6077 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6078 WILL_LJMP(lua_error(L));
6079
6080 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6081 return 1;
6082}
6083
6084/* This function set the response code & optionally reason. */
6085static int hlua_http_res_set_status(lua_State *L)
6086{
6087 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6088 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6089 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6090 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6091
6092 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6093 WILL_LJMP(lua_error(L));
6094
6095 http_res_set_status(code, reason, htxn->s);
6096 return 0;
6097}
6098
6099/*
6100 *
6101 *
6102 * Class HTTPMessage
6103 *
6104 *
6105 */
6106
6107/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6108 * otherwise it throws an error.
6109 */
6110__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6111{
6112 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6113}
6114
6115/* Creates and pushes on the stack a HTTP object according with a current TXN.
6116 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006117static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006118{
6119 /* Check stack size. */
6120 if (!lua_checkstack(L, 3))
6121 return 0;
6122
6123 lua_newtable(L);
6124 lua_pushlightuserdata(L, msg);
6125 lua_rawseti(L, -2, 0);
6126
6127 /* Create the "channel" field that contains the request channel object. */
6128 lua_pushstring(L, "channel");
6129 if (!hlua_channel_new(L, msg->chn))
6130 return 0;
6131 lua_rawset(L, -3);
6132
6133 /* Pop a class stream metatable and affect it to the table. */
6134 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6135 lua_setmetatable(L, -2);
6136
6137 return 1;
6138}
6139
6140/* Helper function returning a filter attached to the HTTP message at the
6141 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006142 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006143 * filled with output and input length respectively.
6144 */
6145static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6146{
6147 struct channel *chn = msg->chn;
6148 struct htx *htx = htxbuf(&chn->buf);
6149 struct filter *filter = NULL;
6150
6151 *offset = co_data(msg->chn);
6152 *len = htx->data - co_data(msg->chn);
6153
6154 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6155 filter = lua_touserdata (L, -1);
6156 if (msg->msg_state >= HTTP_MSG_DATA) {
6157 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6158
6159 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6160 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6161 }
6162 }
6163
6164 lua_pop(L, 1);
6165 return filter;
6166}
6167
6168/* Returns true if the channel attached to the HTTP message is the response
6169 * channel.
6170 */
6171__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6172{
6173 struct http_msg *msg;
6174
6175 MAY_LJMP(check_args(L, 1, "is_resp"));
6176 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6177
6178 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6179 return 1;
6180}
6181
6182/* Returns an array containing the elements status-line of the HTTP message. It relies
6183 * on hlua_http_get_stline().
6184 */
6185__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6186{
6187 struct http_msg *msg;
6188 struct htx *htx;
6189 struct htx_sl *sl;
6190
6191 MAY_LJMP(check_args(L, 1, "get_stline"));
6192 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6193
6194 if (msg->msg_state > HTTP_MSG_BODY)
6195 WILL_LJMP(lua_error(L));
6196
6197 htx = htxbuf(&msg->chn->buf);
6198 sl = http_get_stline(htx);
6199 if (!sl)
6200 return 0;
6201 return hlua_http_get_stline(L, sl);
6202}
6203
6204/* Returns an array containing all headers of the HTTP message. it relies on
6205 * hlua_http_get_headers().
6206 */
6207__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6208{
6209 struct http_msg *msg;
6210
6211 MAY_LJMP(check_args(L, 1, "get_headers"));
6212 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6213
6214 if (msg->msg_state > HTTP_MSG_BODY)
6215 WILL_LJMP(lua_error(L));
6216
6217 return hlua_http_get_headers(L, msg);
6218}
6219
6220/* Deletes all occurrences of an header in the HTTP message matching on its
6221 * name. It relies on hlua_http_del_hdr().
6222 */
6223__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6224{
6225 struct http_msg *msg;
6226
6227 MAY_LJMP(check_args(L, 2, "del_header"));
6228 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6229
6230 if (msg->msg_state > HTTP_MSG_BODY)
6231 WILL_LJMP(lua_error(L));
6232
6233 return hlua_http_del_hdr(L, msg);
6234}
6235
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006236/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006237 * message given its name against a regex and replaces it if it matches. It
6238 * relies on hlua_http_rep_hdr().
6239 */
6240__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6241{
6242 struct http_msg *msg;
6243
6244 MAY_LJMP(check_args(L, 4, "rep_header"));
6245 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6246
6247 if (msg->msg_state > HTTP_MSG_BODY)
6248 WILL_LJMP(lua_error(L));
6249
6250 return hlua_http_rep_hdr(L, msg, 1);
6251}
6252
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006253/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006254 * message given its name against a regex and replaces it if it matches. It
6255 * relies on hlua_http_rep_hdr().
6256 */
6257__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6258{
6259 struct http_msg *msg;
6260
6261 MAY_LJMP(check_args(L, 4, "rep_value"));
6262 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6263
6264 if (msg->msg_state > HTTP_MSG_BODY)
6265 WILL_LJMP(lua_error(L));
6266
6267 return hlua_http_rep_hdr(L, msg, 0);
6268}
6269
6270/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6271__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6272{
6273 struct http_msg *msg;
6274
6275 MAY_LJMP(check_args(L, 3, "add_header"));
6276 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6277
6278 if (msg->msg_state > HTTP_MSG_BODY)
6279 WILL_LJMP(lua_error(L));
6280
6281 return hlua_http_add_hdr(L, msg);
6282}
6283
6284/* Add an header in the HTTP message removing existing headers with the same
6285 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6286 */
6287__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6288{
6289 struct http_msg *msg;
6290
6291 MAY_LJMP(check_args(L, 3, "set_header"));
6292 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6293
6294 if (msg->msg_state > HTTP_MSG_BODY)
6295 WILL_LJMP(lua_error(L));
6296
6297 hlua_http_del_hdr(L, msg);
6298 return hlua_http_add_hdr(L, msg);
6299}
6300
6301/* Rewrites the request method. It relies on http_req_replace_stline(). */
6302__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6303{
6304 struct stream *s;
6305 struct http_msg *msg;
6306 const char *name;
6307 size_t name_len;
6308
6309 MAY_LJMP(check_args(L, 2, "set_method"));
6310 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6311 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6312
6313 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6314 WILL_LJMP(lua_error(L));
6315
6316 s = chn_strm(msg->chn);
6317 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6318 return 1;
6319}
6320
6321/* Rewrites the request path. It relies on http_req_replace_stline(). */
6322__LJMP static int hlua_http_msg_set_path(lua_State *L)
6323{
6324 struct stream *s;
6325 struct http_msg *msg;
6326 const char *name;
6327 size_t name_len;
6328
6329 MAY_LJMP(check_args(L, 2, "set_path"));
6330 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6331 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6332
6333 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6334 WILL_LJMP(lua_error(L));
6335
6336 s = chn_strm(msg->chn);
6337 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6338 return 1;
6339}
6340
6341/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6342__LJMP static int hlua_http_msg_set_query(lua_State *L)
6343{
6344 struct stream *s;
6345 struct http_msg *msg;
6346 const char *name;
6347 size_t name_len;
6348
6349 MAY_LJMP(check_args(L, 2, "set_query"));
6350 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6351 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6352
6353 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6354 WILL_LJMP(lua_error(L));
6355
6356 /* Check length. */
6357 if (name_len > trash.size - 1) {
6358 lua_pushboolean(L, 0);
6359 return 1;
6360 }
6361
6362 /* Add the mark question as prefix. */
6363 chunk_reset(&trash);
6364 trash.area[trash.data++] = '?';
6365 memcpy(trash.area + trash.data, name, name_len);
6366 trash.data += name_len;
6367
6368 s = chn_strm(msg->chn);
6369 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6370 return 1;
6371}
6372
6373/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6374__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6375{
6376 struct stream *s;
6377 struct http_msg *msg;
6378 const char *name;
6379 size_t name_len;
6380
6381 MAY_LJMP(check_args(L, 2, "set_uri"));
6382 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6383 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6384
6385 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6386 WILL_LJMP(lua_error(L));
6387
6388 s = chn_strm(msg->chn);
6389 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6390 return 1;
6391}
6392
6393/* Rewrites the response status code. It relies on http_res_set_status(). */
6394__LJMP static int hlua_http_msg_set_status(lua_State *L)
6395{
6396 struct http_msg *msg;
6397 unsigned int code;
6398 const char *reason;
6399 size_t reason_len;
6400
6401 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6402 code = MAY_LJMP(luaL_checkinteger(L, 2));
6403 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6404
6405 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6406 WILL_LJMP(lua_error(L));
6407
6408 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6409 return 1;
6410}
6411
6412/* Returns true if the HTTP message is full. */
6413__LJMP static int hlua_http_msg_is_full(lua_State *L)
6414{
6415 struct http_msg *msg;
6416
6417 MAY_LJMP(check_args(L, 1, "is_full"));
6418 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6419 lua_pushboolean(L, channel_full(msg->chn, 0));
6420 return 1;
6421}
6422
6423/* Returns true if the HTTP message may still receive data. */
6424__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6425{
6426 struct http_msg *msg;
6427 struct htx *htx;
6428
6429 MAY_LJMP(check_args(L, 1, "may_recv"));
6430 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6431 htx = htxbuf(&msg->chn->buf);
6432 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6433 return 1;
6434}
6435
6436/* Returns true if the HTTP message EOM was received */
6437__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6438{
6439 struct http_msg *msg;
6440 struct htx *htx;
6441
6442 MAY_LJMP(check_args(L, 1, "may_recv"));
6443 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6444 htx = htxbuf(&msg->chn->buf);
6445 lua_pushboolean(L, !htx_expect_more(htx));
6446 return 1;
6447}
6448
6449/* Returns the number of bytes available in the input side of the HTTP
6450 * message. This function never fails.
6451 */
6452__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6453{
6454 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006455 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006456
6457 MAY_LJMP(check_args(L, 1, "input"));
6458 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006459 hlua_http_msg_filter(L, 1, msg, &output, &input);
6460 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006461 return 1;
6462}
6463
6464/* Returns the number of bytes available in the output side of the HTTP
6465 * message. This function never fails.
6466 */
6467__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6468{
6469 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006470 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006471
6472 MAY_LJMP(check_args(L, 1, "output"));
6473 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006474 hlua_http_msg_filter(L, 1, msg, &output, &input);
6475 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006476 return 1;
6477}
6478
6479/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6480 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006481 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006482 * block. This function is called during the payload filtering, so the headers
6483 * are already scheduled for output (from the filter point of view).
6484 */
6485static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6486{
6487 struct htx *htx = htxbuf(&msg->chn->buf);
6488 struct htx_blk *blk;
6489 struct htx_ret htxret;
6490 luaL_Buffer b;
6491 int ret = 0;
6492
6493 luaL_buffinit(L, &b);
6494 htxret = htx_find_offset(htx, offset);
6495 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6496 enum htx_blk_type type = htx_get_blk_type(blk);
6497 struct ist v;
6498
6499 switch (type) {
6500 case HTX_BLK_UNUSED:
6501 break;
6502
6503 case HTX_BLK_DATA:
6504 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006505 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006506 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006507
6508 luaL_addlstring(&b, v.ptr, v.len);
6509 ret += v.len;
6510 break;
6511
6512 default:
vishnu0af4bd72021-10-24 06:46:24 +05306513 if (!ret)
6514 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006515 goto end;
6516 }
6517 offset = 0;
6518 }
6519
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006520end:
vishnu0af4bd72021-10-24 06:46:24 +05306521 if (!ret && (htx->flags & HTX_FL_EOM))
6522 goto no_data;
6523 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006524 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306525
6526 no_data:
6527 /* Remove the empty string and push nil on the stack */
6528 lua_pop(L, 1);
6529 lua_pushnil(L);
6530 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006531}
6532
6533/* Copies the string <str> to the HTTP message <msg> at the offset
6534 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006535 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006536 * the filter context.
6537 */
6538static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6539{
6540 struct htx *htx = htx_from_buf(&msg->chn->buf);
6541 struct htx_ret htxret;
6542 int /*max, */ret = 0;
6543
6544 /* Nothing to do, just return */
6545 if (unlikely(istlen(str) == 0))
6546 goto end;
6547
6548 if (istlen(str) > htx_free_data_space(htx)) {
6549 ret = -1;
6550 goto end;
6551 }
6552
6553 htxret = htx_find_offset(htx, offset);
6554 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6555 if (!htx_add_last_data(htx, str))
6556 goto end;
6557 }
6558 else {
6559 struct ist v = htx_get_blk_value(htx, htxret.blk);
6560 v.ptr += htxret.ret;
6561 v.len = 0;
6562 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6563 goto end;
6564 }
6565 ret = str.len;
6566 if (ret) {
6567 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6568 flt_update_offsets(filter, msg->chn, ret);
6569 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6570 }
6571
6572 end:
6573 htx_to_buf(htx, &msg->chn->buf);
6574 return ret;
6575}
6576
6577/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6578 * position <offset>. It stops on the first non-DATA HTX block. This function is
6579 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006580 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006581 * update the filter context.
6582 */
6583static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6584{
6585 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6586 struct htx *htx = htx_from_buf(&msg->chn->buf);
6587 struct htx_blk *blk;
6588 struct htx_ret htxret;
6589 size_t ret = 0;
6590
6591 /* Be sure <len> is always the amount of DATA to remove */
6592 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006593 /* When htx tail type == HTX_BLK_DATA, no need to take care
6594 * of special blocks like HTX_BLK_EOT.
6595 * We simply truncate after offset
6596 * (truncate targeted blk and discard the following ones)
6597 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006598 htx_truncate(htx, offset);
6599 ret = len;
6600 goto end;
6601 }
6602
6603 htxret = htx_find_offset(htx, offset);
6604 blk = htxret.blk;
6605 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006606 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006607 struct ist v;
6608
6609 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6610 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006611
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006612 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006613 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006614
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006615 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006616 /* trimming data in blk: discard everything after the offset
6617 * (replace 'v' with 'IST_NULL')
6618 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006619 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006620 if (blk && v.len < len) {
6621 /* In this case, caller wants to keep removing data,
6622 * but we need to spare current blk
6623 * because it was already trimmed
6624 */
6625 blk = htx_get_next_blk(htx, blk);
6626 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006627 len -= v.len;
6628 ret += v.len;
6629 }
6630
6631
6632 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006633 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006634 enum htx_blk_type type = htx_get_blk_type(blk);
6635 uint32_t sz = htx_get_blksz(blk);
6636
6637 switch (type) {
6638 case HTX_BLK_UNUSED:
6639 break;
6640
6641 case HTX_BLK_DATA:
6642 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006643 /* don't discard whole blk, only part of it
6644 * (from the beginning)
6645 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006646 htx_cut_data_blk(htx, blk, len);
6647 ret += len;
6648 goto end;
6649 }
6650 break;
6651
6652 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006653 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006654 goto end;
6655 }
6656
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006657 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006658 len -= sz;
6659 ret += sz;
6660 blk = htx_remove_blk(htx, blk);
6661 }
6662
6663end:
6664 flt_update_offsets(filter, msg->chn, -ret);
6665 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6666 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6667 * to loose the EOM flag if the message is empty.
6668 */
6669}
6670
6671/* Copies input data found in an HTTP message. Unlike the channel function used
6672 * to duplicate raw data, this one can only be called inside a filter, from
6673 * http_payload callback. So it cannot yield. An exception is returned if it is
6674 * called from another callback. If nothing was copied, a nil value is pushed on
6675 * the stack.
6676 */
6677__LJMP static int hlua_http_msg_get_body(lua_State *L)
6678{
6679 struct http_msg *msg;
6680 struct filter *filter;
6681 size_t output, input;
6682 int offset, len;
6683
6684 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6685 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6686 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6687
6688 if (msg->msg_state < HTTP_MSG_DATA)
6689 WILL_LJMP(lua_error(L));
6690
6691 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6692 if (!filter || !hlua_filter_from_payload(filter))
6693 WILL_LJMP(lua_error(L));
6694
6695 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6696 lua_pushnil(L);
6697 return 1;
6698 }
6699
6700 offset = output;
6701 if (lua_gettop(L) > 1) {
6702 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6703 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006704 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006705 offset += output;
6706 if (offset < output || offset > input + output) {
6707 lua_pushfstring(L, "offset out of range.");
6708 WILL_LJMP(lua_error(L));
6709 }
6710 }
6711 len = output + input - offset;
6712 if (lua_gettop(L) == 3) {
6713 len = MAY_LJMP(luaL_checkinteger(L, 3));
6714 if (!len)
6715 goto dup;
6716 if (len == -1)
6717 len = global.tune.bufsize;
6718 if (len < 0) {
6719 lua_pushfstring(L, "length out of range.");
6720 WILL_LJMP(lua_error(L));
6721 }
6722 }
6723
6724 dup:
6725 _hlua_http_msg_dup(msg, L, offset, len);
6726 return 1;
6727}
6728
6729/* Appends a string to the HTTP message, after all existing DATA blocks but
6730 * before the trailers, if any. It returns the amount of data written or -1 if
6731 * nothing was copied. Unlike the channel function used to append data, this one
6732 * can only be called inside a filter, from http_payload callback. So it cannot
6733 * yield. An exception is returned if it is called from another callback.
6734 */
6735__LJMP static int hlua_http_msg_append(lua_State *L)
6736{
6737 struct http_msg *msg;
6738 struct filter *filter;
6739 const char *str;
6740 size_t offset, len, sz;
6741 int ret;
6742
6743 MAY_LJMP(check_args(L, 2, "append"));
6744 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6745
6746 if (msg->msg_state < HTTP_MSG_DATA)
6747 WILL_LJMP(lua_error(L));
6748
6749 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6750 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6751 if (!filter || !hlua_filter_from_payload(filter))
6752 WILL_LJMP(lua_error(L));
6753
6754 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6755 lua_pushinteger(L, ret);
6756 return 1;
6757}
6758
6759/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6760 * returns the amount of data written or -1 if nothing was copied. Unlike the
6761 * channel function used to prepend data, this one can only be called inside a
6762 * filter, from http_payload callback. So it cannot yield. An exception is
6763 * returned if it is called from another callback.
6764 */
6765__LJMP static int hlua_http_msg_prepend(lua_State *L)
6766{
6767 struct http_msg *msg;
6768 struct filter *filter;
6769 const char *str;
6770 size_t offset, len, sz;
6771 int ret;
6772
6773 MAY_LJMP(check_args(L, 2, "prepend"));
6774 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006775
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006776 if (msg->msg_state < HTTP_MSG_DATA)
6777 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006778
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006779 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6780 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6781 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006782 WILL_LJMP(lua_error(L));
6783
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006784 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6785 lua_pushinteger(L, ret);
6786 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006787}
6788
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006789/* Inserts a string to the HTTP message at a given offset. By default the string
6790 * is appended at the end of DATA blocks. It returns the amount of data written
6791 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6792 * this one can only be called inside a filter, from http_payload callback. So
6793 * it cannot yield. An exception is returned if it is called from another
6794 * callback.
6795 */
6796__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006797{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006798 struct http_msg *msg;
6799 struct filter *filter;
6800 const char *str;
6801 size_t input, output, sz;
6802 int offset;
6803 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006804
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006805 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6806 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006807 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006808
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006810 WILL_LJMP(lua_error(L));
6811
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006812 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006813 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006814 if (!filter || !hlua_filter_from_payload(filter))
6815 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006816
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006817 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006818 if (lua_gettop(L) > 2) {
6819 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6820 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006821 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006822 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02006823 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006824 lua_pushfstring(L, "offset out of range.");
6825 WILL_LJMP(lua_error(L));
6826 }
6827 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006828
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006829 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6830 lua_pushinteger(L, ret);
6831 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006832}
6833
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006834/* Removes a given amount of data from the HTTP message at a given offset. By
6835 * default all DATA blocks are removed. It returns the amount of data
6836 * removed. Unlike the channel function used to remove data, this one can only
6837 * be called inside a filter, from http_payload callback. So it cannot yield. An
6838 * exception is returned if it is called from another callback.
6839 */
6840__LJMP static int hlua_http_msg_del_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 size_t input, output;
6845 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006846
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006847 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006848 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006849 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006850
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006851 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006852 WILL_LJMP(lua_error(L));
6853
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006854 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006855 if (!filter || !hlua_filter_from_payload(filter))
6856 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006857
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006858 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00006859 if (lua_gettop(L) > 1) {
6860 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006861 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006862 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006863 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02006864 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006865 lua_pushfstring(L, "offset out of range.");
6866 WILL_LJMP(lua_error(L));
6867 }
6868 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006869
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006870 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006871 if (lua_gettop(L) == 3) {
6872 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006873 if (!len)
6874 goto end;
6875 if (len == -1)
6876 len = output + input - offset;
6877 if (len < 0 || offset + len > output + input) {
6878 lua_pushfstring(L, "length out of range.");
6879 WILL_LJMP(lua_error(L));
6880 }
6881 }
6882
6883 _hlua_http_msg_delete(msg, filter, offset, len);
6884
6885 end:
6886 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006887 return 1;
6888}
6889
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006890/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006891 * all remaining data are removed, accordingly to the filter context. It returns
6892 * the amount of data written or -1 if nothing was copied. Unlike the channel
6893 * function used to replace data, this one can only be called inside a filter,
6894 * from http_payload callback. So it cannot yield. An exception is returned if
6895 * it is called from another callback.
6896 */
6897__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006898{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006899 struct http_msg *msg;
6900 struct filter *filter;
6901 struct htx *htx;
6902 const char *str;
6903 size_t input, output, sz;
6904 int offset, len;
6905 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006906
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006907 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6908 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6909 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6910
6911 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006912 WILL_LJMP(lua_error(L));
6913
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006914 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6915 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6916 if (!filter || !hlua_filter_from_payload(filter))
6917 WILL_LJMP(lua_error(L));
6918
6919 offset = output;
6920 if (lua_gettop(L) > 2) {
6921 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6922 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006923 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006924 offset += output;
6925 if (offset < output || offset > input + output) {
6926 lua_pushfstring(L, "offset out of range.");
6927 WILL_LJMP(lua_error(L));
6928 }
6929 }
6930
6931 len = output + input - offset;
6932 if (lua_gettop(L) == 4) {
6933 len = MAY_LJMP(luaL_checkinteger(L, 4));
6934 if (!len)
6935 goto set;
6936 if (len == -1)
6937 len = output + input - offset;
6938 if (len < 0 || offset + len > output + input) {
6939 lua_pushfstring(L, "length out of range.");
6940 WILL_LJMP(lua_error(L));
6941 }
6942 }
6943
6944 set:
6945 /* Be sure we can copied the string once input data will be removed. */
6946 htx = htx_from_buf(&msg->chn->buf);
6947 if (sz > htx_free_data_space(htx) + len)
6948 lua_pushinteger(L, -1);
6949 else {
6950 _hlua_http_msg_delete(msg, filter, offset, len);
6951 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6952 lua_pushinteger(L, ret);
6953 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006954 return 1;
6955}
6956
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006957/* Prepends data into an HTTP message and forward it, from the filter point of
6958 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6959 * the channel function used to send data, this one can only be called inside a
6960 * filter, from http_payload callback. So it cannot yield. An exception is
6961 * returned if it is called from another callback.
6962 */
6963__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006964{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006965 struct http_msg *msg;
6966 struct filter *filter;
6967 struct htx *htx;
6968 const char *str;
6969 size_t offset, len, sz;
6970 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006971
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006972 MAY_LJMP(check_args(L, 2, "send"));
6973 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6974
6975 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006976 WILL_LJMP(lua_error(L));
6977
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006978 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6979 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6980 if (!filter || !hlua_filter_from_payload(filter))
6981 WILL_LJMP(lua_error(L));
6982
6983 /* Return an error if the channel's output is closed */
6984 if (unlikely(channel_output_closed(msg->chn))) {
6985 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006986 return 1;
6987 }
6988
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006989 htx = htx_from_buf(&msg->chn->buf);
6990 if (sz > htx_free_data_space(htx)) {
6991 lua_pushinteger(L, -1);
6992 return 1;
6993 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006994
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006995 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6996 if (ret > 0) {
6997 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6998
6999 FLT_OFF(filter, msg->chn) += ret;
7000 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7001 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7002 }
7003
7004 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007005 return 1;
7006}
7007
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007008/* Forwards a given amount of bytes. It return -1 if the channel's output is
7009 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7010 * channel function used to forward data, this one can only be called inside a
7011 * filter, from http_payload callback. So it cannot yield. An exception is
7012 * returned if it is called from another callback. All other functions deal with
7013 * DATA block, this one not.
7014*/
7015__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007016{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007017 struct http_msg *msg;
7018 struct filter *filter;
7019 size_t offset, len;
7020 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007021
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007022 MAY_LJMP(check_args(L, 2, "forward"));
7023 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7024
7025 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007026 WILL_LJMP(lua_error(L));
7027
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007028 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7029 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7030 if (!filter || !hlua_filter_from_payload(filter))
7031 WILL_LJMP(lua_error(L));
7032
7033 /* Nothing to do, just return */
7034 if (!fwd)
7035 goto end;
7036
7037 /* Return an error if the channel's output is closed */
7038 if (unlikely(channel_output_closed(msg->chn))) {
7039 ret = -1;
7040 goto end;
7041 }
7042
7043 ret = fwd;
7044 if (ret > len)
7045 ret = len;
7046
7047 if (ret) {
7048 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7049
7050 FLT_OFF(filter, msg->chn) += ret;
7051 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7052 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7053 }
7054
7055 end:
7056 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007057 return 1;
7058}
7059
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007060/* Set EOM flag on the HTX message.
7061 *
7062 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7063 * really know how to do without this feature.
7064 */
7065__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007066{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007067 struct http_msg *msg;
7068 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007069
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007070 MAY_LJMP(check_args(L, 1, "set_eom"));
7071 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7072 htx = htxbuf(&msg->chn->buf);
7073 htx->flags |= HTX_FL_EOM;
7074 return 0;
7075}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007076
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007077/* Unset EOM flag on the HTX message.
7078 *
7079 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7080 * really know how to do without this feature.
7081 */
7082__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7083{
7084 struct http_msg *msg;
7085 struct htx *htx;
7086
7087 MAY_LJMP(check_args(L, 1, "set_eom"));
7088 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7089 htx = htxbuf(&msg->chn->buf);
7090 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007091 return 0;
7092}
7093
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007094/*
7095 *
7096 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007097 * Class HTTPClient
7098 *
7099 *
7100 */
7101__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7102{
7103 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7104}
7105
William Lallemandf77f1de2021-09-28 19:10:38 +02007106
7107/* stops the httpclient and ask it to kill itself */
7108__LJMP static int hlua_httpclient_gc(lua_State *L)
7109{
7110 struct hlua_httpclient *hlua_hc;
7111
7112 MAY_LJMP(check_args(L, 1, "__gc"));
7113
7114 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7115
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007116 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7117 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007118 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007119 hlua_hc->hc = NULL;
7120 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007121
7122 return 0;
7123}
7124
7125
William Lallemand3956c4e2021-09-21 16:25:15 +02007126__LJMP static int hlua_httpclient_new(lua_State *L)
7127{
7128 struct hlua_httpclient *hlua_hc;
7129 struct hlua *hlua;
7130
7131 /* Get hlua struct, or NULL if we execute from main lua state */
7132 hlua = hlua_gethlua(L);
7133 if (!hlua)
7134 return 0;
7135
7136 /* Check stack size. */
7137 if (!lua_checkstack(L, 3)) {
7138 hlua_pusherror(L, "httpclient: full stack");
7139 goto err;
7140 }
7141 /* Create the object: obj[0] = userdata. */
7142 lua_newtable(L);
7143 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7144 lua_rawseti(L, -2, 0);
7145 memset(hlua_hc, 0, sizeof(*hlua_hc));
7146
7147 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7148 if (!hlua_hc->hc)
7149 goto err;
7150
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007151 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007152
William Lallemand3956c4e2021-09-21 16:25:15 +02007153 /* Pop a class stream metatable and affect it to the userdata. */
7154 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7155 lua_setmetatable(L, -2);
7156
7157 return 1;
7158
7159 err:
7160 WILL_LJMP(lua_error(L));
7161 return 0;
7162}
7163
7164
7165/*
7166 * Callback of the httpclient, this callback wakes the lua task up, once the
7167 * httpclient receives some data
7168 *
7169 */
7170
William Lallemandbd5739e2021-10-28 15:41:38 +02007171static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007172{
7173 struct hlua *hlua = hc->caller;
7174
7175 if (!hlua || !hlua->task)
7176 return;
7177
7178 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7179}
7180
7181/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007182 * Fill the lua stack with headers from the httpclient response
7183 * This works the same way as the hlua_http_get_headers() function
7184 */
7185__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7186{
7187 struct http_hdr *hdr;
7188
7189 lua_newtable(L);
7190
William Lallemandef574b22021-10-05 16:19:31 +02007191 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007192 struct ist n, v;
7193 int len;
7194
7195 n = hdr->n;
7196 v = hdr->v;
7197
7198 /* Check for existing entry:
7199 * assume that the table is on the top of the stack, and
7200 * push the key in the stack, the function lua_gettable()
7201 * perform the lookup.
7202 */
7203
7204 lua_pushlstring(L, n.ptr, n.len);
7205 lua_gettable(L, -2);
7206
7207 switch (lua_type(L, -1)) {
7208 case LUA_TNIL:
7209 /* Table not found, create it. */
7210 lua_pop(L, 1); /* remove the nil value. */
7211 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7212 lua_newtable(L); /* create and push empty table. */
7213 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7214 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7215 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7216 break;
7217
7218 case LUA_TTABLE:
7219 /* Entry found: push the value in the table. */
7220 len = lua_rawlen(L, -1);
7221 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7222 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7223 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7224 break;
7225
7226 default:
7227 /* Other cases are errors. */
7228 hlua_pusherror(L, "internal error during the parsing of headers.");
7229 WILL_LJMP(lua_error(L));
7230 }
7231 }
7232 return 1;
7233}
7234
7235/*
William Lallemand746e6f32021-10-06 10:57:44 +02007236 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7237 *
7238 * Caller must free the result
7239 */
7240struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7241{
7242 struct http_hdr hdrs[global.tune.max_http_hdr];
7243 struct http_hdr *result = NULL;
7244 uint32_t hdr_num = 0;
7245
7246 lua_pushnil(L);
7247 while (lua_next(L, -2) != 0) {
7248 struct ist name, value;
7249 const char *n, *v;
7250 size_t nlen, vlen;
7251
7252 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7253 /* Skip element if the key is not a string or if the value is not a table */
7254 goto next_hdr;
7255 }
7256
7257 n = lua_tolstring(L, -2, &nlen);
7258 name = ist2(n, nlen);
7259
7260 /* Loop on header's values */
7261 lua_pushnil(L);
7262 while (lua_next(L, -2)) {
7263 if (!lua_isstring(L, -1)) {
7264 /* Skip the value if it is not a string */
7265 goto next_value;
7266 }
7267
7268 v = lua_tolstring(L, -1, &vlen);
7269 value = ist2(v, vlen);
7270 name = ist2(n, nlen);
7271
7272 hdrs[hdr_num].n = istdup(name);
7273 hdrs[hdr_num].v = istdup(value);
7274
7275 hdr_num++;
7276
7277 next_value:
7278 lua_pop(L, 1);
7279 }
7280
7281 next_hdr:
7282 lua_pop(L, 1);
7283
7284 }
7285
7286 if (hdr_num) {
7287 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007288 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007289 if (!result)
7290 goto skip_headers;
7291 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7292
7293 result[hdr_num].n = IST_NULL;
7294 result[hdr_num].v = IST_NULL;
7295 }
7296
7297skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007298
7299 return result;
7300}
7301
7302
William Lallemandbd5739e2021-10-28 15:41:38 +02007303/*
7304 * For each yield, checks if there is some data in the httpclient and push them
7305 * in the lua buffer, once the httpclient finished its job, push the result on
7306 * the stack
7307 */
7308__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7309{
7310 struct buffer *tr;
7311 int res;
7312 struct hlua *hlua = hlua_gethlua(L);
7313 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7314
7315
7316 tr = get_trash_chunk();
7317
7318 res = httpclient_res_xfer(hlua_hc->hc, tr);
7319 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7320
7321 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7322
7323 luaL_pushresult(&hlua_hc->b);
7324 lua_settable(L, -3);
7325
7326 lua_pushstring(L, "status");
7327 lua_pushinteger(L, hlua_hc->hc->res.status);
7328 lua_settable(L, -3);
7329
7330
7331 lua_pushstring(L, "reason");
7332 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7333 lua_settable(L, -3);
7334
7335 lua_pushstring(L, "headers");
7336 hlua_httpclient_get_headers(L, hlua_hc);
7337 lua_settable(L, -3);
7338
7339 return 1;
7340 }
7341
7342 if (httpclient_data(hlua_hc->hc))
7343 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7344
7345 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7346
7347 return 0;
7348}
7349
7350/*
7351 * Call this when trying to stream a body during a request
7352 */
7353__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7354{
7355 struct hlua *hlua;
7356 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7357 const char *body_str = NULL;
7358 int ret;
7359 int end = 0;
7360 size_t buf_len;
7361 size_t to_send = 0;
7362
7363 hlua = hlua_gethlua(L);
7364
7365 if (!hlua || !hlua->task)
7366 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7367 "'frontend', 'backend' or 'task'"));
7368
7369 ret = lua_getfield(L, -1, "body");
7370 if (ret != LUA_TSTRING)
7371 goto rcv;
7372
7373 body_str = lua_tolstring(L, -1, &buf_len);
7374 lua_pop(L, 1);
7375
Christopher Fauletfc591292022-01-12 14:46:03 +01007376 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007377
7378 if ((hlua_hc->sent + to_send) >= buf_len)
7379 end = 1;
7380
7381 /* the end flag is always set since we are using the whole remaining size */
7382 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7383
7384 if (buf_len > hlua_hc->sent) {
7385 /* still need to process the buffer */
7386 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7387 } else {
7388 goto rcv;
7389 /* we sent the whole request buffer we can recv */
7390 }
7391 return 0;
7392
7393rcv:
7394
7395 /* we return a "res" object */
7396 lua_newtable(L);
7397
William Lallemandbd5739e2021-10-28 15:41:38 +02007398 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007399 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007400
William Lallemand933fe392021-11-04 09:45:58 +01007401 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007402 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7403
7404 return 1;
7405}
William Lallemand746e6f32021-10-06 10:57:44 +02007406
William Lallemand3956c4e2021-09-21 16:25:15 +02007407/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007408 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007409 */
7410
William Lallemanddc2cc902021-10-26 11:43:26 +02007411__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007412{
7413 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007414 struct http_hdr *hdrs = NULL;
7415 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007416 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007417 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007418 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007419 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007420 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007421
7422 hlua = hlua_gethlua(L);
7423
7424 if (!hlua || !hlua->task)
7425 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7426 "'frontend', 'backend' or 'task'"));
7427
William Lallemand746e6f32021-10-06 10:57:44 +02007428 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7429 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7430
William Lallemand4f4f2b72022-02-17 20:00:23 +01007431 hlua_hc = hlua_checkhttpclient(L, 1);
7432
William Lallemand7177a952022-03-03 15:33:12 +01007433 lua_pushnil(L); /* first key */
7434 while (lua_next(L, 2)) {
7435 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7436 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7437 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007438
William Lallemand7177a952022-03-03 15:33:12 +01007439 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7440 if (lua_type(L, -1) != LUA_TSTRING)
7441 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7442 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007443
William Lallemand7177a952022-03-03 15:33:12 +01007444 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7445 if (lua_type(L, -1) != LUA_TNUMBER)
7446 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7447 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007448
William Lallemand7177a952022-03-03 15:33:12 +01007449 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7450 if (lua_type(L, -1) != LUA_TTABLE)
7451 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7452 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007453
William Lallemand7177a952022-03-03 15:33:12 +01007454 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7455 if (lua_type(L, -1) != LUA_TSTRING)
7456 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7457 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007458
William Lallemand7177a952022-03-03 15:33:12 +01007459 } else {
7460 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7461 }
7462 /* removes 'value'; keeps 'key' for next iteration */
7463 lua_pop(L, 1);
7464 }
William Lallemanddec25c32021-10-25 19:48:37 +02007465
William Lallemand746e6f32021-10-06 10:57:44 +02007466 if (!url_str) {
7467 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7468 return 0;
7469 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007470
William Lallemand10a37362022-03-02 16:18:26 +01007471 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007472
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007473 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007474 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007475 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007476
7477 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007478 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7479 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7480 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007481 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007482
William Lallemandbd5739e2021-10-28 15:41:38 +02007483 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007484 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007485 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7486 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007487
William Lallemandbd5739e2021-10-28 15:41:38 +02007488 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007489
William Lallemand746e6f32021-10-06 10:57:44 +02007490 /* free the temporary headers array */
7491 hdrs_i = hdrs;
7492 while (hdrs_i && isttest(hdrs_i->n)) {
7493 istfree(&hdrs_i->n);
7494 istfree(&hdrs_i->v);
7495 hdrs_i++;
7496 }
7497 ha_free(&hdrs);
7498
7499
William Lallemand6137a9e2021-10-26 15:01:53 +02007500 if (ret != ERR_NONE) {
7501 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7502 return 0;
7503 }
7504
William Lallemandc2d3db42022-04-26 11:46:13 +02007505 if (!httpclient_start(hlua_hc->hc))
7506 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007507
William Lallemandbd5739e2021-10-28 15:41:38 +02007508 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007509
William Lallemand3956c4e2021-09-21 16:25:15 +02007510 return 0;
7511}
7512
7513/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007514 * Sends an HTTP HEAD request and wait for a response
7515 *
7516 * httpclient:head(url, headers, payload)
7517 */
7518__LJMP static int hlua_httpclient_head(lua_State *L)
7519{
7520 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7521}
7522
7523/*
7524 * Send an HTTP GET request and wait for a response
7525 *
7526 * httpclient:get(url, headers, payload)
7527 */
7528__LJMP static int hlua_httpclient_get(lua_State *L)
7529{
7530 return hlua_httpclient_send(L, HTTP_METH_GET);
7531
7532}
7533
7534/*
7535 * Sends an HTTP PUT request and wait for a response
7536 *
7537 * httpclient:put(url, headers, payload)
7538 */
7539__LJMP static int hlua_httpclient_put(lua_State *L)
7540{
7541 return hlua_httpclient_send(L, HTTP_METH_PUT);
7542}
7543
7544/*
7545 * Send an HTTP POST request and wait for a response
7546 *
7547 * httpclient:post(url, headers, payload)
7548 */
7549__LJMP static int hlua_httpclient_post(lua_State *L)
7550{
7551 return hlua_httpclient_send(L, HTTP_METH_POST);
7552}
7553
7554
7555/*
7556 * Sends an HTTP DELETE request and wait for a response
7557 *
7558 * httpclient:delete(url, headers, payload)
7559 */
7560__LJMP static int hlua_httpclient_delete(lua_State *L)
7561{
7562 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7563}
7564
7565/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007566 *
7567 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007568 * Class TXN
7569 *
7570 *
7571 */
7572
7573/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007574 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007575 */
7576__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7577{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007578 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007579}
7580
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007581__LJMP static int hlua_set_var(lua_State *L)
7582{
7583 struct hlua_txn *htxn;
7584 const char *name;
7585 size_t len;
7586 struct sample smp;
7587
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007588 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7589 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007590
7591 /* It is useles to retrieve the stream, but this function
7592 * runs only in a stream context.
7593 */
7594 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7595 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7596
7597 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007598 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007599 hlua_lua2smp(L, 3, &smp);
7600
7601 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007602 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007603
7604 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7605 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7606 else
7607 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7608
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007609 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007610}
7611
Christopher Faulet85d79c92016-11-09 16:54:56 +01007612__LJMP static int hlua_unset_var(lua_State *L)
7613{
7614 struct hlua_txn *htxn;
7615 const char *name;
7616 size_t len;
7617 struct sample smp;
7618
7619 MAY_LJMP(check_args(L, 2, "unset_var"));
7620
7621 /* It is useles to retrieve the stream, but this function
7622 * runs only in a stream context.
7623 */
7624 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7625 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7626
7627 /* Unset the variable. */
7628 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007629 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7630 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007631}
7632
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007633__LJMP static int hlua_get_var(lua_State *L)
7634{
7635 struct hlua_txn *htxn;
7636 const char *name;
7637 size_t len;
7638 struct sample smp;
7639
7640 MAY_LJMP(check_args(L, 2, "get_var"));
7641
7642 /* It is useles to retrieve the stream, but this function
7643 * runs only in a stream context.
7644 */
7645 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7646 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7647
Willy Tarreau7560dd42016-03-10 16:28:58 +01007648 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007649 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007650 lua_pushnil(L);
7651 return 1;
7652 }
7653
7654 return hlua_smp2lua(L, &smp);
7655}
7656
Willy Tarreau59551662015-03-10 14:23:13 +01007657__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007658{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007659 struct hlua *hlua;
7660
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007661 MAY_LJMP(check_args(L, 2, "set_priv"));
7662
Willy Tarreau87b09662015-04-03 00:22:06 +02007663 /* It is useles to retrieve the stream, but this function
7664 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007665 */
7666 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007667
7668 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007669 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007670 if (!hlua)
7671 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007672
7673 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007674 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007675
7676 /* Get and store new value. */
7677 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7678 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7679
7680 return 0;
7681}
7682
Willy Tarreau59551662015-03-10 14:23:13 +01007683__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007684{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007685 struct hlua *hlua;
7686
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007687 MAY_LJMP(check_args(L, 1, "get_priv"));
7688
Willy Tarreau87b09662015-04-03 00:22:06 +02007689 /* It is useles to retrieve the stream, but this function
7690 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007691 */
7692 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007693
7694 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007695 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007696 if (!hlua) {
7697 lua_pushnil(L);
7698 return 1;
7699 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007700
7701 /* Push configuration index in the stack. */
7702 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7703
7704 return 1;
7705}
7706
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007707/* Create stack entry containing a class TXN. This function
7708 * return 0 if the stack does not contains free slots,
7709 * otherwise it returns 1.
7710 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007711static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007712{
Willy Tarreaude491382015-04-06 11:04:28 +02007713 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007714
7715 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007716 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007717 return 0;
7718
7719 /* NOTE: The allocation never fails. The failure
7720 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007721 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007722 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007723 /* Create the object: obj[0] = userdata. */
7724 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007725 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007726 lua_rawseti(L, -2, 0);
7727
Willy Tarreaude491382015-04-06 11:04:28 +02007728 htxn->s = s;
7729 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007730 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007731 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007732
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007733 /* Create the "f" field that contains a list of fetches. */
7734 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007735 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007736 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007737 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007738
7739 /* Create the "sf" field that contains a list of stringsafe fetches. */
7740 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007741 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007742 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007743 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007744
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007745 /* Create the "c" field that contains a list of converters. */
7746 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007747 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007748 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007749 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007750
7751 /* Create the "sc" field that contains a list of stringsafe converters. */
7752 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007753 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007754 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007755 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007756
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007757 /* Create the "req" field that contains the request channel object. */
7758 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007759 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007760 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007761 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007762
7763 /* Create the "res" field that contains the response channel object. */
7764 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007765 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007766 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007767 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007768
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007769 /* Creates the HTTP object is the current proxy allows http. */
7770 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007771 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007772 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007773 return 0;
7774 }
7775 else
7776 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007777 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007778
Christopher Faulet78c35472020-02-26 17:14:08 +01007779 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7780 /* HTTPMessage object are created when a lua TXN is created from
7781 * a filter context only
7782 */
7783
7784 /* Creates the HTTP-Request object is the current proxy allows http. */
7785 lua_pushstring(L, "http_req");
7786 if (p->mode == PR_MODE_HTTP) {
7787 if (!hlua_http_msg_new(L, &s->txn->req))
7788 return 0;
7789 }
7790 else
7791 lua_pushnil(L);
7792 lua_rawset(L, -3);
7793
7794 /* Creates the HTTP-Response object is the current proxy allows http. */
7795 lua_pushstring(L, "http_res");
7796 if (p->mode == PR_MODE_HTTP) {
7797 if (!hlua_http_msg_new(L, &s->txn->rsp))
7798 return 0;
7799 }
7800 else
7801 lua_pushnil(L);
7802 lua_rawset(L, -3);
7803 }
7804
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007805 /* Pop a class sesison metatable and affect it to the userdata. */
7806 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7807 lua_setmetatable(L, -2);
7808
7809 return 1;
7810}
7811
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007812__LJMP static int hlua_txn_deflog(lua_State *L)
7813{
7814 const char *msg;
7815 struct hlua_txn *htxn;
7816
7817 MAY_LJMP(check_args(L, 2, "deflog"));
7818 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7819 msg = MAY_LJMP(luaL_checkstring(L, 2));
7820
7821 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7822 return 0;
7823}
7824
7825__LJMP static int hlua_txn_log(lua_State *L)
7826{
7827 int level;
7828 const char *msg;
7829 struct hlua_txn *htxn;
7830
7831 MAY_LJMP(check_args(L, 3, "log"));
7832 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7833 level = MAY_LJMP(luaL_checkinteger(L, 2));
7834 msg = MAY_LJMP(luaL_checkstring(L, 3));
7835
7836 if (level < 0 || level >= NB_LOG_LEVELS)
7837 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7838
7839 hlua_sendlog(htxn->s->be, level, msg);
7840 return 0;
7841}
7842
7843__LJMP static int hlua_txn_log_debug(lua_State *L)
7844{
7845 const char *msg;
7846 struct hlua_txn *htxn;
7847
7848 MAY_LJMP(check_args(L, 2, "Debug"));
7849 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7850 msg = MAY_LJMP(luaL_checkstring(L, 2));
7851 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7852 return 0;
7853}
7854
7855__LJMP static int hlua_txn_log_info(lua_State *L)
7856{
7857 const char *msg;
7858 struct hlua_txn *htxn;
7859
7860 MAY_LJMP(check_args(L, 2, "Info"));
7861 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7862 msg = MAY_LJMP(luaL_checkstring(L, 2));
7863 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7864 return 0;
7865}
7866
7867__LJMP static int hlua_txn_log_warning(lua_State *L)
7868{
7869 const char *msg;
7870 struct hlua_txn *htxn;
7871
7872 MAY_LJMP(check_args(L, 2, "Warning"));
7873 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7874 msg = MAY_LJMP(luaL_checkstring(L, 2));
7875 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7876 return 0;
7877}
7878
7879__LJMP static int hlua_txn_log_alert(lua_State *L)
7880{
7881 const char *msg;
7882 struct hlua_txn *htxn;
7883
7884 MAY_LJMP(check_args(L, 2, "Alert"));
7885 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7886 msg = MAY_LJMP(luaL_checkstring(L, 2));
7887 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7888 return 0;
7889}
7890
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007891__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7892{
7893 struct hlua_txn *htxn;
7894 int ll;
7895
7896 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7897 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7898 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7899
7900 if (ll < 0 || ll > 7)
7901 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7902
7903 htxn->s->logs.level = ll;
7904 return 0;
7905}
7906
7907__LJMP static int hlua_txn_set_tos(lua_State *L)
7908{
7909 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007910 int tos;
7911
7912 MAY_LJMP(check_args(L, 2, "set_tos"));
7913 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7914 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7915
Willy Tarreau1a18b542018-12-11 16:37:42 +01007916 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007917 return 0;
7918}
7919
7920__LJMP static int hlua_txn_set_mark(lua_State *L)
7921{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007922 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007923 int mark;
7924
7925 MAY_LJMP(check_args(L, 2, "set_mark"));
7926 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7927 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7928
Lukas Tribus579e3e32019-08-11 18:03:45 +02007929 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007930 return 0;
7931}
7932
Patrick Hemmer268a7072018-05-11 12:52:31 -04007933__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7934{
7935 struct hlua_txn *htxn;
7936
7937 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7938 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7939 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7940 return 0;
7941}
7942
7943__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7944{
7945 struct hlua_txn *htxn;
7946
7947 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7948 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7949 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7950 return 0;
7951}
7952
Christopher Faulet700d9e82020-01-31 12:21:52 +01007953/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007954 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007955 * message and terminate the transaction. It returns 1 on success and 0 on
7956 * error. The Reply must be on top of the stack.
7957 */
7958__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7959{
7960 struct htx *htx;
7961 struct htx_sl *sl;
7962 struct h1m h1m;
7963 const char *status, *reason, *body;
7964 size_t status_len, reason_len, body_len;
7965 int ret, code, flags;
7966
7967 code = 200;
7968 status = "200";
7969 status_len = 3;
7970 ret = lua_getfield(L, -1, "status");
7971 if (ret == LUA_TNUMBER) {
7972 code = lua_tointeger(L, -1);
7973 status = lua_tolstring(L, -1, &status_len);
7974 }
7975 lua_pop(L, 1);
7976
7977 reason = http_get_reason(code);
7978 reason_len = strlen(reason);
7979 ret = lua_getfield(L, -1, "reason");
7980 if (ret == LUA_TSTRING)
7981 reason = lua_tolstring(L, -1, &reason_len);
7982 lua_pop(L, 1);
7983
7984 body = NULL;
7985 body_len = 0;
7986 ret = lua_getfield(L, -1, "body");
7987 if (ret == LUA_TSTRING)
7988 body = lua_tolstring(L, -1, &body_len);
7989 lua_pop(L, 1);
7990
7991 /* Prepare the response before inserting the headers */
7992 h1m_init_res(&h1m);
7993 htx = htx_from_buf(&s->res.buf);
7994 channel_htx_truncate(&s->res, htx);
7995 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7996 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7997 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7998 ist2(status, status_len), ist2(reason, reason_len));
7999 }
8000 else {
8001 flags = HTX_SL_F_IS_RESP;
8002 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8003 ist2(status, status_len), ist2(reason, reason_len));
8004 }
8005 if (!sl)
8006 goto fail;
8007 sl->info.res.status = code;
8008
8009 /* Push in the stack the "headers" entry. */
8010 ret = lua_getfield(L, -1, "headers");
8011 if (ret != LUA_TTABLE)
8012 goto skip_headers;
8013
8014 lua_pushnil(L);
8015 while (lua_next(L, -2) != 0) {
8016 struct ist name, value;
8017 const char *n, *v;
8018 size_t nlen, vlen;
8019
8020 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8021 /* Skip element if the key is not a string or if the value is not a table */
8022 goto next_hdr;
8023 }
8024
8025 n = lua_tolstring(L, -2, &nlen);
8026 name = ist2(n, nlen);
8027 if (isteqi(name, ist("content-length"))) {
8028 /* Always skip content-length header. It will be added
8029 * later with the correct len
8030 */
8031 goto next_hdr;
8032 }
8033
8034 /* Loop on header's values */
8035 lua_pushnil(L);
8036 while (lua_next(L, -2)) {
8037 if (!lua_isstring(L, -1)) {
8038 /* Skip the value if it is not a string */
8039 goto next_value;
8040 }
8041
8042 v = lua_tolstring(L, -1, &vlen);
8043 value = ist2(v, vlen);
8044
8045 if (isteqi(name, ist("transfer-encoding")))
8046 h1_parse_xfer_enc_header(&h1m, value);
8047 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8048 goto fail;
8049
8050 next_value:
8051 lua_pop(L, 1);
8052 }
8053
8054 next_hdr:
8055 lua_pop(L, 1);
8056 }
8057 skip_headers:
8058 lua_pop(L, 1);
8059
8060 /* Update h1m flags: CLEN is set if CHNK is not present */
8061 if (!(h1m.flags & H1_MF_CHNK)) {
8062 const char *clen = ultoa(body_len);
8063
8064 h1m.flags |= H1_MF_CLEN;
8065 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8066 goto fail;
8067 }
8068 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8069 h1m.flags |= H1_MF_XFER_LEN;
8070
8071 /* Update HTX start-line flags */
8072 if (h1m.flags & H1_MF_XFER_ENC)
8073 flags |= HTX_SL_F_XFER_ENC;
8074 if (h1m.flags & H1_MF_XFER_LEN) {
8075 flags |= HTX_SL_F_XFER_LEN;
8076 if (h1m.flags & H1_MF_CHNK)
8077 flags |= HTX_SL_F_CHNK;
8078 else if (h1m.flags & H1_MF_CLEN)
8079 flags |= HTX_SL_F_CLEN;
8080 if (h1m.body_len == 0)
8081 flags |= HTX_SL_F_BODYLESS;
8082 }
8083 sl->flags |= flags;
8084
8085
8086 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008087 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008088 goto fail;
8089
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008090 htx->flags |= HTX_FL_EOM;
8091
Christopher Faulet700d9e82020-01-31 12:21:52 +01008092 /* Now, forward the response and terminate the transaction */
8093 s->txn->status = code;
8094 htx_to_buf(htx, &s->res.buf);
8095 if (!http_forward_proxy_resp(s, 1))
8096 goto fail;
8097
8098 return 1;
8099
8100 fail:
8101 channel_htx_truncate(&s->res, htx);
8102 return 0;
8103}
8104
8105/* Terminate a transaction if called from a lua action. For TCP streams,
8106 * processing is just aborted. Nothing is returned to the client and all
8107 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8108 * is forwarded to the client before terminating the transaction. On success,
8109 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8110 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8111 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008112 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008113__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008114{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008115 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008116 struct stream *s;
8117 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008118
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008119 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008120
Christopher Faulet700d9e82020-01-31 12:21:52 +01008121 /* If the flags NOTERM is set, we cannot terminate the session, so we
8122 * just end the execution of the current lua code. */
8123 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008124 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008125
Christopher Faulet700d9e82020-01-31 12:21:52 +01008126 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008127 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008128 struct channel *req = &s->req;
8129 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008130
Christopher Faulet700d9e82020-01-31 12:21:52 +01008131 channel_auto_read(req);
8132 channel_abort(req);
8133 channel_auto_close(req);
8134 channel_erase(req);
8135
Christopher Faulet700d9e82020-01-31 12:21:52 +01008136 channel_auto_read(res);
8137 channel_auto_close(res);
8138 channel_shutr_now(res);
8139
8140 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8141 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008142 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008143
Christopher Faulet700d9e82020-01-31 12:21:52 +01008144 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8145 /* No reply or invalid reply */
8146 s->txn->status = 0;
8147 http_reply_and_close(s, 0, NULL);
8148 }
8149 else {
8150 /* Remove extra args to have the reply on top of the stack */
8151 if (lua_gettop(L) > 2)
8152 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008153
Christopher Faulet700d9e82020-01-31 12:21:52 +01008154 if (!hlua_txn_forward_reply(L, s)) {
8155 if (!(s->flags & SF_ERR_MASK))
8156 s->flags |= SF_ERR_PRXCOND;
8157 lua_pushinteger(L, ACT_RET_ERR);
8158 WILL_LJMP(hlua_done(L));
8159 return 0; /* Never reached */
8160 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008161 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008162
Christopher Faulet700d9e82020-01-31 12:21:52 +01008163 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8164 if (htxn->dir == SMP_OPT_DIR_REQ) {
8165 /* let's log the request time */
8166 s->logs.tv_request = now;
8167 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008168 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008169 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008170
Christopher Faulet700d9e82020-01-31 12:21:52 +01008171 done:
8172 if (!(s->flags & SF_ERR_MASK))
8173 s->flags |= SF_ERR_LOCAL;
8174 if (!(s->flags & SF_FINST_MASK))
8175 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008176
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008177 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8178 lua_pushinteger(L, -1);
8179 else
8180 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008181 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008182 return 0;
8183}
8184
Christopher Faulet700d9e82020-01-31 12:21:52 +01008185/*
8186 *
8187 *
8188 * Class REPLY
8189 *
8190 *
8191 */
8192
8193/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8194 * free slots, the function fails and returns 0;
8195 */
8196static int hlua_txn_reply_new(lua_State *L)
8197{
8198 struct hlua_txn *htxn;
8199 const char *reason, *body = NULL;
8200 int ret, status;
8201
8202 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008203 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008204 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8205 WILL_LJMP(lua_error(L));
8206 }
8207
8208 /* Default value */
8209 status = 200;
8210 reason = http_get_reason(status);
8211
8212 if (lua_istable(L, 2)) {
8213 /* load status and reason from the table argument at index 2 */
8214 ret = lua_getfield(L, 2, "status");
8215 if (ret == LUA_TNIL)
8216 goto reason;
8217 else if (ret != LUA_TNUMBER) {
8218 /* invalid status: ignore the reason */
8219 goto body;
8220 }
8221 status = lua_tointeger(L, -1);
8222
8223 reason:
8224 lua_pop(L, 1); /* restore the stack: remove status */
8225 ret = lua_getfield(L, 2, "reason");
8226 if (ret == LUA_TSTRING)
8227 reason = lua_tostring(L, -1);
8228
8229 body:
8230 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8231 ret = lua_getfield(L, 2, "body");
8232 if (ret == LUA_TSTRING)
8233 body = lua_tostring(L, -1);
8234 lua_pop(L, 1); /* restore the stack: remove body */
8235 }
8236
8237 /* Create the Reply table */
8238 lua_newtable(L);
8239
8240 /* Add status element */
8241 lua_pushstring(L, "status");
8242 lua_pushinteger(L, status);
8243 lua_settable(L, -3);
8244
8245 /* Add reason element */
8246 reason = http_get_reason(status);
8247 lua_pushstring(L, "reason");
8248 lua_pushstring(L, reason);
8249 lua_settable(L, -3);
8250
8251 /* Add body element, nil if undefined */
8252 lua_pushstring(L, "body");
8253 if (body)
8254 lua_pushstring(L, body);
8255 else
8256 lua_pushnil(L);
8257 lua_settable(L, -3);
8258
8259 /* Add headers element */
8260 lua_pushstring(L, "headers");
8261 lua_newtable(L);
8262
8263 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8264 if (lua_istable(L, 2)) {
8265 /* load headers from the table argument at index 2. If it is a table, copy it. */
8266 ret = lua_getfield(L, 2, "headers");
8267 if (ret == LUA_TTABLE) {
8268 /* stack: [ ... <headers:table>, <table> ] */
8269 lua_pushnil(L);
8270 while (lua_next(L, -2) != 0) {
8271 /* stack: [ ... <headers:table>, <table>, k, v] */
8272 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8273 /* invalid value type, skip it */
8274 lua_pop(L, 1);
8275 continue;
8276 }
8277
8278
8279 /* Duplicate the key and swap it with the value. */
8280 lua_pushvalue(L, -2);
8281 lua_insert(L, -2);
8282 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8283
8284 lua_newtable(L);
8285 lua_insert(L, -2);
8286 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8287
8288 if (lua_isstring(L, -1)) {
8289 /* push the value in the inner table */
8290 lua_rawseti(L, -2, 1);
8291 }
8292 else { /* table */
8293 lua_pushnil(L);
8294 while (lua_next(L, -2) != 0) {
8295 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8296 if (!lua_isstring(L, -1)) {
8297 /* invalid value type, skip it*/
8298 lua_pop(L, 1);
8299 continue;
8300 }
8301 /* push the value in the inner table */
8302 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8303 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8304 }
8305 lua_pop(L, 1);
8306 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8307 }
8308
8309 /* push (k,v) on the stack in the headers table:
8310 * stack: [ ... <headers:table>, <table>, k, k, v ]
8311 */
8312 lua_settable(L, -5);
8313 /* stack: [ ... <headers:table>, <table>, k ] */
8314 }
8315 }
8316 lua_pop(L, 1);
8317 }
8318 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8319 lua_settable(L, -3);
8320 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8321
8322 /* Pop a class sesison metatable and affect it to the userdata. */
8323 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8324 lua_setmetatable(L, -2);
8325 return 1;
8326}
8327
8328/* Set the reply status code, and optionally the reason. If no reason is
8329 * provided, the default one corresponding to the status code is used.
8330 */
8331__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8332{
8333 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8334 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8335
8336 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008337 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008338
8339 if (status < 100 || status > 599) {
8340 lua_pushboolean(L, 0);
8341 return 1;
8342 }
8343 if (!reason)
8344 reason = http_get_reason(status);
8345
8346 lua_pushinteger(L, status);
8347 lua_setfield(L, 1, "status");
8348
8349 lua_pushstring(L, reason);
8350 lua_setfield(L, 1, "reason");
8351
8352 lua_pushboolean(L, 1);
8353 return 1;
8354}
8355
8356/* Add a header into the reply object. Each header name is associated to an
8357 * array of values in the "headers" table. If the header name is not found, a
8358 * new entry is created.
8359 */
8360__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8361{
8362 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8363 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8364 int ret;
8365
8366 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008367 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008368
8369 /* Push in the stack the "headers" entry. */
8370 ret = lua_getfield(L, 1, "headers");
8371 if (ret != LUA_TTABLE) {
8372 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8373 WILL_LJMP(lua_error(L));
8374 }
8375
8376 /* check if the header is already registered. If not, register it. */
8377 ret = lua_getfield(L, -1, name);
8378 if (ret == LUA_TNIL) {
8379 /* Entry not found. */
8380 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8381
8382 /* Insert the new header name in the array in the top of the stack.
8383 * It left the new array in the top of the stack.
8384 */
8385 lua_newtable(L);
8386 lua_pushstring(L, name);
8387 lua_pushvalue(L, -2);
8388 lua_settable(L, -4);
8389 }
8390 else if (ret != LUA_TTABLE) {
8391 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8392 WILL_LJMP(lua_error(L));
8393 }
8394
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008395 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008396 * the header value as new entry.
8397 */
8398 lua_pushstring(L, value);
8399 ret = lua_rawlen(L, -2);
8400 lua_rawseti(L, -2, ret + 1);
8401
8402 lua_pushboolean(L, 1);
8403 return 1;
8404}
8405
8406/* Remove all occurrences of a given header name. */
8407__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8408{
8409 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8410 int ret;
8411
8412 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008413 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008414
8415 /* Push in the stack the "headers" entry. */
8416 ret = lua_getfield(L, 1, "headers");
8417 if (ret != LUA_TTABLE) {
8418 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8419 WILL_LJMP(lua_error(L));
8420 }
8421
8422 lua_pushstring(L, name);
8423 lua_pushnil(L);
8424 lua_settable(L, -3);
8425
8426 lua_pushboolean(L, 1);
8427 return 1;
8428}
8429
8430/* Set the reply's body. Overwrite any existing entry. */
8431__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8432{
8433 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8434
8435 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008436 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008437
8438 lua_pushstring(L, payload);
8439 lua_setfield(L, 1, "body");
8440
8441 lua_pushboolean(L, 1);
8442 return 1;
8443}
8444
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008445__LJMP static int hlua_log(lua_State *L)
8446{
8447 int level;
8448 const char *msg;
8449
8450 MAY_LJMP(check_args(L, 2, "log"));
8451 level = MAY_LJMP(luaL_checkinteger(L, 1));
8452 msg = MAY_LJMP(luaL_checkstring(L, 2));
8453
8454 if (level < 0 || level >= NB_LOG_LEVELS)
8455 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8456
8457 hlua_sendlog(NULL, level, msg);
8458 return 0;
8459}
8460
8461__LJMP static int hlua_log_debug(lua_State *L)
8462{
8463 const char *msg;
8464
8465 MAY_LJMP(check_args(L, 1, "debug"));
8466 msg = MAY_LJMP(luaL_checkstring(L, 1));
8467 hlua_sendlog(NULL, LOG_DEBUG, msg);
8468 return 0;
8469}
8470
8471__LJMP static int hlua_log_info(lua_State *L)
8472{
8473 const char *msg;
8474
8475 MAY_LJMP(check_args(L, 1, "info"));
8476 msg = MAY_LJMP(luaL_checkstring(L, 1));
8477 hlua_sendlog(NULL, LOG_INFO, msg);
8478 return 0;
8479}
8480
8481__LJMP static int hlua_log_warning(lua_State *L)
8482{
8483 const char *msg;
8484
8485 MAY_LJMP(check_args(L, 1, "warning"));
8486 msg = MAY_LJMP(luaL_checkstring(L, 1));
8487 hlua_sendlog(NULL, LOG_WARNING, msg);
8488 return 0;
8489}
8490
8491__LJMP static int hlua_log_alert(lua_State *L)
8492{
8493 const char *msg;
8494
8495 MAY_LJMP(check_args(L, 1, "alert"));
8496 msg = MAY_LJMP(luaL_checkstring(L, 1));
8497 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008498 return 0;
8499}
8500
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008501__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008502{
8503 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008504 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008505 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008506 return 0;
8507}
8508
8509__LJMP static int hlua_sleep(lua_State *L)
8510{
8511 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008512 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008513
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008514 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008515
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008516 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008517 wakeup_ms = tick_add(now_ms, delay);
8518 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008519
Willy Tarreau9635e032018-10-16 17:52:55 +02008520 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008521 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008522}
8523
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008524__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008525{
8526 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008527 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008528
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008529 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008530
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008531 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008532 wakeup_ms = tick_add(now_ms, delay);
8533 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008534
Willy Tarreau9635e032018-10-16 17:52:55 +02008535 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008536 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008537}
8538
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008539/* This functionis an LUA binding. it permits to give back
8540 * the hand at the HAProxy scheduler. It is used when the
8541 * LUA processing consumes a lot of time.
8542 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008543__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008544{
8545 return 0;
8546}
8547
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008548__LJMP static int hlua_yield(lua_State *L)
8549{
Willy Tarreau9635e032018-10-16 17:52:55 +02008550 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008551 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008552}
8553
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008554/* This function change the nice of the currently executed
8555 * task. It is used set low or high priority at the current
8556 * task.
8557 */
Willy Tarreau59551662015-03-10 14:23:13 +01008558__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008559{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008560 struct hlua *hlua;
8561 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008562
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008563 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008564 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008565
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008566 /* Get hlua struct, or NULL if we execute from main lua state */
8567 hlua = hlua_gethlua(L);
8568
8569 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008570 if (!hlua || !hlua->task)
8571 return 0;
8572
8573 if (nice < -1024)
8574 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008575 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008576 nice = 1024;
8577
8578 hlua->task->nice = nice;
8579 return 0;
8580}
8581
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008582/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008583 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8584 * return an E_AGAIN signal, the emmiter of this signal must set a
8585 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008586 *
8587 * Task wrapper are longjmp safe because the only one Lua code
8588 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008589 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008590struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008591{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008592 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008593 enum hlua_exec status;
8594
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008595 if (task->tid < 0)
8596 task->tid = tid;
8597
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008598 /* If it is the first call to the task, we must initialize the
8599 * execution timeouts.
8600 */
8601 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008602 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008603
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008604 /* Execute the Lua code. */
8605 status = hlua_ctx_resume(hlua, 1);
8606
8607 switch (status) {
8608 /* finished or yield */
8609 case HLUA_E_OK:
8610 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008611 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008612 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008613 break;
8614
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008615 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008616 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008617 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008618 break;
8619
8620 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008621 case HLUA_E_ETMOUT:
8622 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8623 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008624 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008625 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008626 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008627 case HLUA_E_ERR:
8628 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008629 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008630 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008631 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008632 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008633 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008634 break;
8635 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008636 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008637}
8638
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008639/* This function is an LUA binding that register LUA function to be
8640 * executed after the HAProxy configuration parsing and before the
8641 * HAProxy scheduler starts. This function expect only one LUA
8642 * argument that is a function. This function returns nothing, but
8643 * throws if an error is encountered.
8644 */
8645__LJMP static int hlua_register_init(lua_State *L)
8646{
8647 struct hlua_init_function *init;
8648 int ref;
8649
8650 MAY_LJMP(check_args(L, 1, "register_init"));
8651
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008652 if (hlua_gethlua(L)) {
8653 /* runtime processing */
8654 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8655 }
8656
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008657 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8658
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008659 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008660 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008661 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008662
8663 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008664 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008665 return 0;
8666}
8667
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008668/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008669 * executed in parallel of the main HAroxy activity. The task is
8670 * created and it is set in the HAProxy scheduler. It can be called
8671 * from the "init" section, "post init" or during the runtime.
8672 *
8673 * Lua prototype:
8674 *
8675 * <none> core.register_task(<function>)
8676 */
8677static int hlua_register_task(lua_State *L)
8678{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008679 struct hlua *hlua = NULL;
8680 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008681 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008682 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008683
8684 MAY_LJMP(check_args(L, 1, "register_task"));
8685
8686 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8687
Thierry Fournier75fc0292020-11-28 13:18:56 +01008688 /* Get the reference state. If the reference is NULL, L is the master
8689 * state, otherwise hlua->T is.
8690 */
8691 hlua = hlua_gethlua(L);
8692 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008693 /* we are in runtime processing */
8694 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008695 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008696 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008697 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008698
Willy Tarreaubafbe012017-11-24 17:34:44 +01008699 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008700 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008701 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008702 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008703
Thierry Fournier59f11be2020-11-29 00:37:41 +01008704 /* We are in the common lua state, execute the task anywhere,
8705 * otherwise, inherit the current thread identifier
8706 */
8707 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008708 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008709 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008710 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008711 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008712 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008713
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008714 task->context = hlua;
8715 task->process = hlua_process_task;
8716
Thierry Fournier021d9862020-11-28 23:42:03 +01008717 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008718 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008719
8720 /* Restore the function in the stack. */
8721 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008722 /* function ref not needed anymore since it was pushed to the substack */
8723 hlua_unref(L, ref);
8724
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008725 hlua->nargs = 0;
8726
8727 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008728 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008729
8730 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008731
8732 alloc_error:
8733 task_destroy(task);
8734 hlua_ctx_destroy(hlua);
8735 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8736 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008737}
8738
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008739/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8740 * doesn't allow "yield" functions because the HAProxy engine cannot
8741 * resume converters.
8742 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008743static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008744{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008745 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008746 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008747 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008748
Willy Tarreaube508f12016-03-10 11:47:01 +01008749 if (!stream)
8750 return 0;
8751
Willy Tarreau87b09662015-04-03 00:22:06 +02008752 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008753 * Lua context can be not initialized. This behavior
8754 * permits to save performances because a systematic
8755 * Lua initialization cause 5% performances loss.
8756 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008757 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008758 struct hlua *hlua;
8759
8760 hlua = pool_alloc(pool_head_hlua);
8761 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008762 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8763 return 0;
8764 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008765 HLUA_INIT(hlua);
8766 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008767 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008768 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8769 return 0;
8770 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008771 }
8772
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008773 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008774 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008775
8776 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008777 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008778 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8779 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008780 else
8781 error = "critical error";
8782 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008783 return 0;
8784 }
8785
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008786 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008787 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008788 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008789 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008790 return 0;
8791 }
8792
8793 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008794 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008795
8796 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008797 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008798 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008799 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008800 return 0;
8801 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008802 hlua_smp2lua(stream->hlua->T, smp);
8803 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008804
8805 /* push keywords in the stack. */
8806 if (arg_p) {
8807 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008808 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008809 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008810 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008811 return 0;
8812 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008813 hlua_arg2lua(stream->hlua->T, arg_p);
8814 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008815 }
8816 }
8817
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008818 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008819 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008820
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008821 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008822 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008823 }
8824
8825 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008826 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008827 /* finished. */
8828 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008829 /* If the stack is empty, the function fails. */
8830 if (lua_gettop(stream->hlua->T) <= 0)
8831 return 0;
8832
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008833 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008834 hlua_lua2smp(stream->hlua->T, -1, smp);
8835 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008836 return 1;
8837
8838 /* yield. */
8839 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008840 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008841 return 0;
8842
8843 /* finished with error. */
8844 case HLUA_E_ERRMSG:
8845 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008846 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008847 fcn->name, lua_tostring(stream->hlua->T, -1));
8848 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008849 return 0;
8850
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008851 case HLUA_E_ETMOUT:
8852 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8853 return 0;
8854
8855 case HLUA_E_NOMEM:
8856 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8857 return 0;
8858
8859 case HLUA_E_YIELD:
8860 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8861 return 0;
8862
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008863 case HLUA_E_ERR:
8864 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008865 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008866 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008867
8868 default:
8869 return 0;
8870 }
8871}
8872
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008873/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8874 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008875 * resume sample-fetches. This function will be called by the sample
8876 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008877 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008878static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8879 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008880{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008881 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008882 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008883 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008884 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008885
Willy Tarreaube508f12016-03-10 11:47:01 +01008886 if (!stream)
8887 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008888
Willy Tarreau87b09662015-04-03 00:22:06 +02008889 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008890 * Lua context can be not initialized. This behavior
8891 * permits to save performances because a systematic
8892 * Lua initialization cause 5% performances loss.
8893 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008894 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008895 struct hlua *hlua;
8896
8897 hlua = pool_alloc(pool_head_hlua);
8898 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008899 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8900 return 0;
8901 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008902 hlua->T = NULL;
8903 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008904 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008905 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8906 return 0;
8907 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008908 }
8909
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008910 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008911 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008912
8913 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008914 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008915 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8916 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008917 else
8918 error = "critical error";
8919 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008920 return 0;
8921 }
8922
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008923 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008924 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008925 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008926 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008927 return 0;
8928 }
8929
8930 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008931 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008932
8933 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008934 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008935 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008936 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008937 return 0;
8938 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008939 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008940
8941 /* push keywords in the stack. */
8942 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8943 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008944 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008945 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008946 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008947 return 0;
8948 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008949 hlua_arg2lua(stream->hlua->T, arg_p);
8950 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008951 }
8952
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008953 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008954 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008955
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008956 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008957 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008958 }
8959
8960 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008961 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008962 /* finished. */
8963 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008964 /* If the stack is empty, the function fails. */
8965 if (lua_gettop(stream->hlua->T) <= 0)
8966 return 0;
8967
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008968 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008969 hlua_lua2smp(stream->hlua->T, -1, smp);
8970 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008971
8972 /* Set the end of execution flag. */
8973 smp->flags &= ~SMP_F_MAY_CHANGE;
8974 return 1;
8975
8976 /* yield. */
8977 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008978 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008979 return 0;
8980
8981 /* finished with error. */
8982 case HLUA_E_ERRMSG:
8983 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008984 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008985 fcn->name, lua_tostring(stream->hlua->T, -1));
8986 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008987 return 0;
8988
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008989 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008990 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8991 return 0;
8992
8993 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008994 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8995 return 0;
8996
8997 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008998 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8999 return 0;
9000
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009001 case HLUA_E_ERR:
9002 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009003 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009004 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009005
9006 default:
9007 return 0;
9008 }
9009}
9010
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009011/* This function is an LUA binding used for registering
9012 * "sample-conv" functions. It expects a converter name used
9013 * in the haproxy configuration file, and an LUA function.
9014 */
9015__LJMP static int hlua_register_converters(lua_State *L)
9016{
9017 struct sample_conv_kw_list *sck;
9018 const char *name;
9019 int ref;
9020 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009021 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009022 struct sample_conv *sc;
9023 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009024
9025 MAY_LJMP(check_args(L, 2, "register_converters"));
9026
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009027 if (hlua_gethlua(L)) {
9028 /* runtime processing */
9029 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9030 }
9031
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009032 /* First argument : converter name. */
9033 name = MAY_LJMP(luaL_checkstring(L, 1));
9034
9035 /* Second argument : lua function. */
9036 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9037
Thierry Fournierf67442e2020-11-28 20:41:07 +01009038 /* Check if the converter is already registered */
9039 trash = get_trash_chunk();
9040 chunk_printf(trash, "lua.%s", name);
9041 sc = find_sample_conv(trash->area, trash->data);
9042 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009043 fcn = sc->private;
9044 if (fcn->function_ref[hlua_state_id] != -1) {
9045 ha_warning("Trying to register converter 'lua.%s' more than once. "
9046 "This will become a hard error in version 2.5.\n", name);
9047 }
9048 fcn->function_ref[hlua_state_id] = ref;
9049 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009050 }
9051
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009052 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009053 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009054 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009055 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009056 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009057 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009058 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009059
9060 /* Fill fcn. */
9061 fcn->name = strdup(name);
9062 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009063 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009064 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009065
9066 /* List head */
9067 sck->list.n = sck->list.p = NULL;
9068
9069 /* converter keyword. */
9070 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009071 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009072 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009073 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009074
9075 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9076 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009077 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 +01009078 sck->kw[0].val_args = NULL;
9079 sck->kw[0].in_type = SMP_T_STR;
9080 sck->kw[0].out_type = SMP_T_STR;
9081 sck->kw[0].private = fcn;
9082
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009083 /* Register this new converter */
9084 sample_register_convs(sck);
9085
9086 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009087
9088 alloc_error:
9089 release_hlua_function(fcn);
9090 ha_free(&sck);
9091 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9092 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009093}
9094
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009095/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009096 * "sample-fetch" functions. It expects a converter name used
9097 * in the haproxy configuration file, and an LUA function.
9098 */
9099__LJMP static int hlua_register_fetches(lua_State *L)
9100{
9101 const char *name;
9102 int ref;
9103 int len;
9104 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009105 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009106 struct sample_fetch *sf;
9107 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009108
9109 MAY_LJMP(check_args(L, 2, "register_fetches"));
9110
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009111 if (hlua_gethlua(L)) {
9112 /* runtime processing */
9113 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
9114 }
9115
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009116 /* First argument : sample-fetch name. */
9117 name = MAY_LJMP(luaL_checkstring(L, 1));
9118
9119 /* Second argument : lua function. */
9120 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9121
Thierry Fournierf67442e2020-11-28 20:41:07 +01009122 /* Check if the sample-fetch is already registered */
9123 trash = get_trash_chunk();
9124 chunk_printf(trash, "lua.%s", name);
9125 sf = find_sample_fetch(trash->area, trash->data);
9126 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009127 fcn = sf->private;
9128 if (fcn->function_ref[hlua_state_id] != -1) {
9129 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9130 "This will become a hard error in version 2.5.\n", name);
9131 }
9132 fcn->function_ref[hlua_state_id] = ref;
9133 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009134 }
9135
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009136 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009137 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009138 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009139 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009140 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009141 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009142 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009143
9144 /* Fill fcn. */
9145 fcn->name = strdup(name);
9146 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009147 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009148 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009149
9150 /* List head */
9151 sfk->list.n = sfk->list.p = NULL;
9152
9153 /* sample-fetch keyword. */
9154 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009155 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009156 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009157 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009158
9159 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9160 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009161 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 +01009162 sfk->kw[0].val_args = NULL;
9163 sfk->kw[0].out_type = SMP_T_STR;
9164 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9165 sfk->kw[0].val = 0;
9166 sfk->kw[0].private = fcn;
9167
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009168 /* Register this new fetch. */
9169 sample_register_fetches(sfk);
9170
9171 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009172
9173 alloc_error:
9174 release_hlua_function(fcn);
9175 ha_free(&sfk);
9176 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9177 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009178}
9179
Christopher Faulet501465d2020-02-26 14:54:16 +01009180/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009181 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009182__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009183{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009184 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009185 unsigned int delay;
9186 unsigned int wakeup_ms;
9187
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009188 /* Get hlua struct, or NULL if we execute from main lua state */
9189 hlua = hlua_gethlua(L);
9190 if (!hlua) {
9191 return 0;
9192 }
9193
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009194 MAY_LJMP(check_args(L, 1, "wake_time"));
9195
9196 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9197 wakeup_ms = tick_add(now_ms, delay);
9198 hlua->wake_time = wakeup_ms;
9199 return 0;
9200}
9201
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009202/* This function is a wrapper to execute each LUA function declared as an action
9203 * wrapper during the initialisation period. This function may return any
9204 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9205 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9206 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009207 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009208static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009209 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009210{
9211 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009212 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009213 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009214 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009215
9216 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009217 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9218 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9219 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9220 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009221 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009222 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009223 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009224 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009225
Willy Tarreau87b09662015-04-03 00:22:06 +02009226 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009227 * Lua context can be not initialized. This behavior
9228 * permits to save performances because a systematic
9229 * Lua initialization cause 5% performances loss.
9230 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009231 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009232 struct hlua *hlua;
9233
9234 hlua = pool_alloc(pool_head_hlua);
9235 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009236 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009237 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009238 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009239 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009240 HLUA_INIT(hlua);
9241 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009242 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 +01009243 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009244 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009245 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009246 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009247 }
9248
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009249 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009250 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009251
9252 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009253 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009254 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9255 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009256 else
9257 error = "critical error";
9258 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009259 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009260 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009261 }
9262
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009263 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009264 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009265 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009266 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009267 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009268 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009269 }
9270
9271 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009272 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 +01009273
Willy Tarreau87b09662015-04-03 00:22:06 +02009274 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009275 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009276 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009277 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009278 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009279 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009280 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009281 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009282
9283 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009284 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009285 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009286 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009287 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009288 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009289 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009290 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009291 lua_pushstring(s->hlua->T, *arg);
9292 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009293 }
9294
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009295 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009296 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009297
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009298 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009299 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009300 }
9301
9302 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009303 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009304 /* finished. */
9305 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009306 /* Catch the return value */
9307 if (lua_gettop(s->hlua->T) > 0)
9308 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009309
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009310 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009311 if (act_ret == ACT_RET_YIELD) {
9312 if (flags & ACT_OPT_FINAL)
9313 goto err_yield;
9314
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009315 if (dir == SMP_OPT_DIR_REQ)
9316 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9317 s->hlua->wake_time);
9318 else
9319 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9320 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009321 }
9322 goto end;
9323
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009324 /* yield. */
9325 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009326 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009327 if (dir == SMP_OPT_DIR_REQ)
9328 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9329 s->hlua->wake_time);
9330 else
9331 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9332 s->hlua->wake_time);
9333
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009334 /* Some actions can be wake up when a "write" event
9335 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009336 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009337 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009338 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009339 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009340 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009341 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009342 act_ret = ACT_RET_YIELD;
9343 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009344
9345 /* finished with error. */
9346 case HLUA_E_ERRMSG:
9347 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009348 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009349 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009350 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009351 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009352
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009353 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009354 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009355 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009356
9357 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009358 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009359 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009360
9361 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009362 err_yield:
9363 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009364 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009365 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009366 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009367
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009368 case HLUA_E_ERR:
9369 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009370 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009371 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009372
9373 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009374 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009375 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009376
9377 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009378 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009379 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009380 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009381}
9382
Willy Tarreau144f84a2021-03-02 16:09:26 +01009383struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009384{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009385 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009386
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009388 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009389 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009390}
9391
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009392static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009393{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009394 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009395 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009396 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009397 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009398 struct task *task;
9399 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009400 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009401
Willy Tarreaubafbe012017-11-24 17:34:44 +01009402 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009403 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009404 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009405 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009406 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009407 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009408 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009409 tcp_ctx->hlua = hlua;
9410 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009411
9412 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009413 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009414 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009415 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009416 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009417 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009418 }
9419 task->nice = 0;
9420 task->context = ctx;
9421 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009422 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009423
9424 /* In the execution wrappers linked with a stream, the
9425 * Lua context can be not initialized. This behavior
9426 * permits to save performances because a systematic
9427 * Lua initialization cause 5% performances loss.
9428 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009429 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 +01009430 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009431 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009432 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009433 }
9434
9435 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009436 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009437
9438 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009439 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009440 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9441 error = lua_tostring(hlua->T, -1);
9442 else
9443 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009444 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009445 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009446 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009447 }
9448
9449 /* Check stack available size. */
9450 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009451 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009452 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009453 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009454 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009455 }
9456
9457 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009458 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009459
9460 /* Create and and push object stream in the stack. */
9461 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009462 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009463 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009464 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009465 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009466 }
9467 hlua->nargs = 1;
9468
9469 /* push keywords in the stack. */
9470 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9471 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009472 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009473 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009474 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009475 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009476 }
9477 lua_pushstring(hlua->T, *arg);
9478 hlua->nargs++;
9479 }
9480
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009481 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009482
9483 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009484 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009485 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009486
Christopher Fauletc9929382022-05-12 11:52:27 +02009487 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009488}
9489
Willy Tarreau60409db2019-08-21 14:14:50 +02009490void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009491{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009492 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009493 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009494 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009495 struct act_rule *rule = ctx->rule;
9496 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009497 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009498
Christopher Faulet31572222023-03-31 11:13:48 +02009499 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9500 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009501
Christopher Faulet31572222023-03-31 11:13:48 +02009502 /* The applet execution is already done. */
9503 if (tcp_ctx->flags & APPLET_DONE)
9504 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009505
9506 /* Execute the function. */
9507 switch (hlua_ctx_resume(hlua, 1)) {
9508 /* finished. */
9509 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009510 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009511 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
9512 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009513
9514 /* yield. */
9515 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009516 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009517 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +02009518 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009519
9520 /* finished with error. */
9521 case HLUA_E_ERRMSG:
9522 /* Display log. */
9523 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009524 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009525 lua_pop(hlua->T, 1);
9526 goto error;
9527
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009528 case HLUA_E_ETMOUT:
9529 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009530 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009531 goto error;
9532
9533 case HLUA_E_NOMEM:
9534 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009535 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009536 goto error;
9537
9538 case HLUA_E_YIELD: /* unexpected */
9539 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009540 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009541 goto error;
9542
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009543 case HLUA_E_ERR:
9544 /* Display log. */
9545 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009546 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009547 goto error;
9548
9549 default:
9550 goto error;
9551 }
9552
Christopher Faulet31572222023-03-31 11:13:48 +02009553out:
9554 /* eat the whole request */
9555 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
9556 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009557
Christopher Faulet31572222023-03-31 11:13:48 +02009558error:
9559 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009560 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009561 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009562}
9563
9564static void hlua_applet_tcp_release(struct appctx *ctx)
9565{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009566 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9567
9568 task_destroy(tcp_ctx->task);
9569 tcp_ctx->task = NULL;
9570 hlua_ctx_destroy(tcp_ctx->hlua);
9571 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009572}
9573
Christopher Fauletc9929382022-05-12 11:52:27 +02009574/* The function returns 0 if the initialisation is complete or -1 if
9575 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009576 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009577static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009578{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009579 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009580 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009581 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009582 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009583 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009584 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009585 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009586 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009587
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009588 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009589 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009590 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009591 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009592 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009593 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009594 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009595 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009596 http_ctx->hlua = hlua;
9597 http_ctx->left_bytes = -1;
9598 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009599
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009600 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009601 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009602
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009603 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009604 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009605 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009606 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009607 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009608 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009609 }
9610 task->nice = 0;
9611 task->context = ctx;
9612 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009613 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009614
9615 /* In the execution wrappers linked with a stream, the
9616 * Lua context can be not initialized. This behavior
9617 * permits to save performances because a systematic
9618 * Lua initialization cause 5% performances loss.
9619 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009620 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 +01009621 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009622 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009623 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009624 }
9625
9626 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009627 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009628
9629 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009630 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009631 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9632 error = lua_tostring(hlua->T, -1);
9633 else
9634 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009635 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009636 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009637 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009638 }
9639
9640 /* Check stack available size. */
9641 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009642 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009643 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009644 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009645 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009646 }
9647
9648 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009649 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009650
9651 /* Create and and push object stream in the stack. */
9652 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009653 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009654 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009655 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009656 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009657 }
9658 hlua->nargs = 1;
9659
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009660 /* push keywords in the stack. */
9661 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9662 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009663 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009664 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009665 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009666 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009667 }
9668 lua_pushstring(hlua->T, *arg);
9669 hlua->nargs++;
9670 }
9671
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009672 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009673
9674 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009675 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009676
Christopher Fauletc9929382022-05-12 11:52:27 +02009677 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009678}
9679
Willy Tarreau60409db2019-08-21 14:14:50 +02009680void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009681{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009682 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009683 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009684 struct stream *strm = __sc_strm(sc);
9685 struct channel *req = sc_oc(sc);
9686 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009687 struct act_rule *rule = ctx->rule;
9688 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009689 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009690 struct htx *req_htx, *res_htx;
9691
9692 res_htx = htx_from_buf(&res->buf);
9693
Christopher Faulet31572222023-03-31 11:13:48 +02009694 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9695 goto out;
9696
9697 /* The applet execution is already done. */
9698 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009699 goto out;
9700
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009701 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009702 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009703 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009704 goto out;
9705 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009706
9707 /* Set the currently running flag. */
9708 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009709 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009710 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009711 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009712 goto out;
9713 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009714 }
9715
Christopher Faulet31572222023-03-31 11:13:48 +02009716 /* Execute the function. */
9717 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009718 /* finished. */
9719 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009720 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009721 break;
9722
9723 /* yield. */
9724 case HLUA_E_AGAIN:
9725 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009726 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009727 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009728
9729 /* finished with error. */
9730 case HLUA_E_ERRMSG:
9731 /* Display log. */
9732 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009733 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009734 lua_pop(hlua->T, 1);
9735 goto error;
9736
9737 case HLUA_E_ETMOUT:
9738 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009739 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009740 goto error;
9741
9742 case HLUA_E_NOMEM:
9743 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009744 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009745 goto error;
9746
9747 case HLUA_E_YIELD: /* unexpected */
9748 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009749 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009750 goto error;
9751
9752 case HLUA_E_ERR:
9753 /* Display log. */
9754 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009755 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009756 goto error;
9757
9758 default:
9759 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009760 }
9761
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009762 if (http_ctx->flags & APPLET_DONE) {
9763 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +02009764 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009765
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009766 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009767 goto error;
9768
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009769 /* no more data are expected. If the response buffer is empty
9770 * for a chunked message, be sure to add something (EOT block in
9771 * this case) to have something to send. It is important to be
9772 * sure the EOM flags will be handled by the endpoint.
9773 */
9774 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9775 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009776 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009777 goto out;
9778 }
9779 channel_add_input(res, 1);
9780 }
9781
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009782 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +02009783 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009784 strm->txn->status = http_ctx->status;
9785 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009786 }
9787
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009788 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009789 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +02009790 /* eat the whole request */
9791 if (co_data(req)) {
9792 req_htx = htx_from_buf(&req->buf);
9793 co_htx_skip(req, req_htx, co_data(req));
9794 htx_to_buf(req_htx, &req->buf);
9795 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009796 return;
9797
9798 error:
9799
9800 /* If we are in HTTP mode, and we are not send any
9801 * data, return a 500 server error in best effort:
9802 * if there is no room available in the buffer,
9803 * just close the connection.
9804 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009805 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009806 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009807
9808 channel_erase(res);
9809 res->buf.data = b_data(err);
9810 memcpy(res->buf.area, b_head(err), b_data(err));
9811 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009812 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +02009813 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009814 }
Christopher Faulet31572222023-03-31 11:13:48 +02009815 else
9816 se_fl_set(ctx->sedesc, SE_FL_ERROR);
9817
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009818 if (!(strm->flags & SF_ERR_MASK))
9819 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009820 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009821 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009822}
9823
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009824static void hlua_applet_http_release(struct appctx *ctx)
9825{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009826 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9827
9828 task_destroy(http_ctx->task);
9829 http_ctx->task = NULL;
9830 hlua_ctx_destroy(http_ctx->hlua);
9831 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009832}
9833
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009834/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009835 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009836 *
9837 * This function can fail with an abort() due to an Lua critical error.
9838 * We are in the configuration parsing process of HAProxy, this abort() is
9839 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009840 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009841static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9842 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009843{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009844 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009845 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009846
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009847 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009848 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009849 if (!rule->arg.hlua_rule) {
9850 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009851 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009852 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009853
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009854 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009855 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9856 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009857 if (!rule->arg.hlua_rule->args) {
9858 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009859 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009860 }
9861
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009862 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009863 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009864
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009865 /* Expect some arguments */
9866 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009867 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009868 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009869 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009870 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009871 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009872 if (!rule->arg.hlua_rule->args[i]) {
9873 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009874 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009875 }
9876 (*cur_arg)++;
9877 }
9878 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009879
Thierry FOURNIER42148732015-09-02 17:17:33 +02009880 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009881 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009882 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009883
9884 error:
9885 if (rule->arg.hlua_rule) {
9886 if (rule->arg.hlua_rule->args) {
9887 for (i = 0; i < fcn->nargs; i++)
9888 ha_free(&rule->arg.hlua_rule->args[i]);
9889 ha_free(&rule->arg.hlua_rule->args);
9890 }
9891 ha_free(&rule->arg.hlua_rule);
9892 }
9893 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009894}
9895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009896static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9897 struct act_rule *rule, char **err)
9898{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009899 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009900
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009901 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009902 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009903 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009904 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009905 * the call of this analyzer.
9906 */
9907 if (rule->from != ACT_F_HTTP_REQ) {
9908 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9909 return ACT_RET_PRS_ERR;
9910 }
9911
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009912 /* Memory for the rule. */
9913 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9914 if (!rule->arg.hlua_rule) {
9915 memprintf(err, "out of memory error");
9916 return ACT_RET_PRS_ERR;
9917 }
9918
9919 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009920 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009921
9922 /* TODO: later accept arguments. */
9923 rule->arg.hlua_rule->args = NULL;
9924
9925 /* Add applet pointer in the rule. */
9926 rule->applet.obj_type = OBJ_TYPE_APPLET;
9927 rule->applet.name = fcn->name;
9928 rule->applet.init = hlua_applet_http_init;
9929 rule->applet.fct = hlua_applet_http_fct;
9930 rule->applet.release = hlua_applet_http_release;
9931 rule->applet.timeout = hlua_timeout_applet;
9932
9933 return ACT_RET_PRS_OK;
9934}
9935
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009936/* This function is an LUA binding used for registering
9937 * "sample-conv" functions. It expects a converter name used
9938 * in the haproxy configuration file, and an LUA function.
9939 */
9940__LJMP static int hlua_register_action(lua_State *L)
9941{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009942 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009943 const char *name;
9944 int ref;
9945 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009946 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009947 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009948 struct buffer *trash;
9949 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009950
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009951 /* Initialise the number of expected arguments at 0. */
9952 nargs = 0;
9953
9954 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9955 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009956
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009957 if (hlua_gethlua(L)) {
9958 /* runtime processing */
9959 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
9960 }
9961
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009962 /* First argument : converter name. */
9963 name = MAY_LJMP(luaL_checkstring(L, 1));
9964
9965 /* Second argument : environment. */
9966 if (lua_type(L, 2) != LUA_TTABLE)
9967 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9968
9969 /* Third argument : lua function. */
9970 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9971
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009972 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009973 if (lua_gettop(L) >= 4)
9974 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9975
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009976 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009977 lua_pushnil(L);
9978 while (lua_next(L, 2) != 0) {
9979 if (lua_type(L, -1) != LUA_TSTRING)
9980 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9981
Thierry Fournierf67442e2020-11-28 20:41:07 +01009982 /* Check if action exists */
9983 trash = get_trash_chunk();
9984 chunk_printf(trash, "lua.%s", name);
9985 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9986 akw = tcp_req_cont_action(trash->area);
9987 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9988 akw = tcp_res_cont_action(trash->area);
9989 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9990 akw = action_http_req_custom(trash->area);
9991 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9992 akw = action_http_res_custom(trash->area);
9993 } else {
9994 akw = NULL;
9995 }
9996 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009997 fcn = akw->private;
9998 if (fcn->function_ref[hlua_state_id] != -1) {
9999 ha_warning("Trying to register action 'lua.%s' more than once. "
10000 "This will become a hard error in version 2.5.\n", name);
10001 }
10002 fcn->function_ref[hlua_state_id] = ref;
10003
10004 /* pop the environment string. */
10005 lua_pop(L, 1);
10006 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010007 }
10008
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010009 /* Check required environment. Only accepted "http" or "tcp". */
10010 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010011 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010012 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010013 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010014 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010015 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010016 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010017
10018 /* Fill fcn. */
10019 fcn->name = strdup(name);
10020 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010021 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010022 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010023
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010024 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010025 fcn->nargs = nargs;
10026
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010027 /* List head */
10028 akl->list.n = akl->list.p = NULL;
10029
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010030 /* action keyword. */
10031 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010032 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010033 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010034 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010035
10036 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10037
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010038 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010039 akl->kw[0].private = fcn;
10040 akl->kw[0].parse = action_register_lua;
10041
10042 /* select the action registering point. */
10043 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10044 tcp_req_cont_keywords_register(akl);
10045 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10046 tcp_res_cont_keywords_register(akl);
10047 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10048 http_req_keywords_register(akl);
10049 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10050 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010051 else {
10052 release_hlua_function(fcn);
10053 if (akl)
10054 ha_free((char **)&(akl->kw[0].kw));
10055 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010056 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010057 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10058 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010059 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010060
10061 /* pop the environment string. */
10062 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010063
10064 /* reset for next loop */
10065 akl = NULL;
10066 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010067 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010068 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010069
10070 alloc_error:
10071 release_hlua_function(fcn);
10072 ha_free(&akl);
10073 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10074 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010075}
10076
10077static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10078 struct act_rule *rule, char **err)
10079{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010080 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010081
Christopher Faulet280f85b2019-07-15 15:02:04 +020010082 if (px->mode == PR_MODE_HTTP) {
10083 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010084 return ACT_RET_PRS_ERR;
10085 }
10086
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010087 /* Memory for the rule. */
10088 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10089 if (!rule->arg.hlua_rule) {
10090 memprintf(err, "out of memory error");
10091 return ACT_RET_PRS_ERR;
10092 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010093
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010094 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010095 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010096
10097 /* TODO: later accept arguments. */
10098 rule->arg.hlua_rule->args = NULL;
10099
10100 /* Add applet pointer in the rule. */
10101 rule->applet.obj_type = OBJ_TYPE_APPLET;
10102 rule->applet.name = fcn->name;
10103 rule->applet.init = hlua_applet_tcp_init;
10104 rule->applet.fct = hlua_applet_tcp_fct;
10105 rule->applet.release = hlua_applet_tcp_release;
10106 rule->applet.timeout = hlua_timeout_applet;
10107
10108 return 0;
10109}
10110
10111/* This function is an LUA binding used for registering
10112 * "sample-conv" functions. It expects a converter name used
10113 * in the haproxy configuration file, and an LUA function.
10114 */
10115__LJMP static int hlua_register_service(lua_State *L)
10116{
10117 struct action_kw_list *akl;
10118 const char *name;
10119 const char *env;
10120 int ref;
10121 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010122 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010123 struct buffer *trash;
10124 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010125
10126 MAY_LJMP(check_args(L, 3, "register_service"));
10127
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010128 if (hlua_gethlua(L)) {
10129 /* runtime processing */
10130 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
10131 }
10132
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010133 /* First argument : converter name. */
10134 name = MAY_LJMP(luaL_checkstring(L, 1));
10135
10136 /* Second argument : environment. */
10137 env = MAY_LJMP(luaL_checkstring(L, 2));
10138
10139 /* Third argument : lua function. */
10140 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10141
Thierry Fournierf67442e2020-11-28 20:41:07 +010010142 /* Check for service already registered */
10143 trash = get_trash_chunk();
10144 chunk_printf(trash, "lua.%s", name);
10145 akw = service_find(trash->area);
10146 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010147 fcn = akw->private;
10148 if (fcn->function_ref[hlua_state_id] != -1) {
10149 ha_warning("Trying to register service 'lua.%s' more than once. "
10150 "This will become a hard error in version 2.5.\n", name);
10151 }
10152 fcn->function_ref[hlua_state_id] = ref;
10153 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010154 }
10155
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010156 /* Allocate and fill the sample fetch keyword struct. */
10157 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10158 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010159 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010160 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010161 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010162 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010163
10164 /* Fill fcn. */
10165 len = strlen("<lua.>") + strlen(name) + 1;
10166 fcn->name = calloc(1, len);
10167 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010168 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010169 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010170 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010171
10172 /* List head */
10173 akl->list.n = akl->list.p = NULL;
10174
10175 /* converter keyword. */
10176 len = strlen("lua.") + strlen(name) + 1;
10177 akl->kw[0].kw = calloc(1, len);
10178 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010179 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010180
10181 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10182
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010183 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010184 if (strcmp(env, "tcp") == 0)
10185 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010186 else if (strcmp(env, "http") == 0)
10187 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010188 else {
10189 release_hlua_function(fcn);
10190 if (akl)
10191 ha_free((char **)&(akl->kw[0].kw));
10192 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010193 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010194 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010195 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010196
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010197 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010198 akl->kw[0].private = fcn;
10199
10200 /* End of array. */
10201 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10202
10203 /* Register this new converter */
10204 service_keywords_register(akl);
10205
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010206 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010207
10208 alloc_error:
10209 release_hlua_function(fcn);
10210 ha_free(&akl);
10211 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10212 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010213}
10214
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010215/* This function initialises Lua cli handler. It copies the
10216 * arguments in the Lua stack and create channel IO objects.
10217 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010218static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010219{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010220 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010221 struct hlua *hlua;
10222 struct hlua_function *fcn;
10223 int i;
10224 const char *error;
10225
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010226 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010227 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010228
Willy Tarreaubafbe012017-11-24 17:34:44 +010010229 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010230 if (!hlua) {
10231 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010232 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010233 }
10234 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010235 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010236
10237 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010238 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010239 * applet_http. It is absolutely compatible.
10240 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010241 ctx->task = task_new_here();
10242 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010243 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010244 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010245 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010246 ctx->task->nice = 0;
10247 ctx->task->context = appctx;
10248 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010249
10250 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010251 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010252 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010253 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010254 }
10255
10256 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010257 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010258 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10259 error = lua_tostring(hlua->T, -1);
10260 else
10261 error = "critical error";
10262 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10263 goto error;
10264 }
10265
10266 /* Check stack available size. */
10267 if (!lua_checkstack(hlua->T, 2)) {
10268 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10269 goto error;
10270 }
10271
10272 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010273 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010274
10275 /* Once the arguments parsed, the CLI is like an AppletTCP,
10276 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010277 */
10278 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10279 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10280 goto error;
10281 }
10282 hlua->nargs = 1;
10283
10284 /* push keywords in the stack. */
10285 for (i = 0; *args[i]; i++) {
10286 /* Check stack available size. */
10287 if (!lua_checkstack(hlua->T, 1)) {
10288 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10289 goto error;
10290 }
10291 lua_pushstring(hlua->T, args[i]);
10292 hlua->nargs++;
10293 }
10294
10295 /* We must initialize the execution timeouts. */
10296 hlua->max_time = hlua_timeout_session;
10297
10298 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010299 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010300
10301 /* It's ok */
10302 return 0;
10303
10304 /* It's not ok. */
10305error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010306 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010307 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010308 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010309 return 1;
10310}
10311
10312static int hlua_cli_io_handler_fct(struct appctx *appctx)
10313{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010314 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010315 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010316 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010317 struct hlua_function *fcn;
10318
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010319 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010320 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010321 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010322
10323 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010324 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010325 return 1;
10326
10327 /* Execute the function. */
10328 switch (hlua_ctx_resume(hlua, 1)) {
10329
10330 /* finished. */
10331 case HLUA_E_OK:
10332 return 1;
10333
10334 /* yield. */
10335 case HLUA_E_AGAIN:
10336 /* We want write. */
10337 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010338 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010339 /* Set the timeout. */
10340 if (hlua->wake_time != TICK_ETERNITY)
10341 task_schedule(hlua->task, hlua->wake_time);
10342 return 0;
10343
10344 /* finished with error. */
10345 case HLUA_E_ERRMSG:
10346 /* Display log. */
10347 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10348 fcn->name, lua_tostring(hlua->T, -1));
10349 lua_pop(hlua->T, 1);
10350 return 1;
10351
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010352 case HLUA_E_ETMOUT:
10353 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10354 fcn->name);
10355 return 1;
10356
10357 case HLUA_E_NOMEM:
10358 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10359 fcn->name);
10360 return 1;
10361
10362 case HLUA_E_YIELD: /* unexpected */
10363 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10364 fcn->name);
10365 return 1;
10366
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010367 case HLUA_E_ERR:
10368 /* Display log. */
10369 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10370 fcn->name);
10371 return 1;
10372
10373 default:
10374 return 1;
10375 }
10376
10377 return 1;
10378}
10379
10380static void hlua_cli_io_release_fct(struct appctx *appctx)
10381{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010382 struct hlua_cli_ctx *ctx = appctx->svcctx;
10383
10384 hlua_ctx_destroy(ctx->hlua);
10385 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010386}
10387
10388/* This function is an LUA binding used for registering
10389 * new keywords in the cli. It expects a list of keywords
10390 * which are the "path". It is limited to 5 keywords. A
10391 * description of the command, a function to be executed
10392 * for the parsing and a function for io handlers.
10393 */
10394__LJMP static int hlua_register_cli(lua_State *L)
10395{
10396 struct cli_kw_list *cli_kws;
10397 const char *message;
10398 int ref_io;
10399 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010400 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010401 int index;
10402 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010403 struct buffer *trash;
10404 const char *kw[5];
10405 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010406 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010407
10408 MAY_LJMP(check_args(L, 3, "register_cli"));
10409
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010410 if (hlua_gethlua(L)) {
10411 /* runtime processing */
10412 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
10413 }
10414
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010415 /* First argument : an array of maximum 5 keywords. */
10416 if (!lua_istable(L, 1))
10417 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10418
10419 /* Second argument : string with contextual message. */
10420 message = MAY_LJMP(luaL_checkstring(L, 2));
10421
10422 /* Third and fourth argument : lua function. */
10423 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10424
Thierry Fournierf67442e2020-11-28 20:41:07 +010010425 /* Check for CLI service already registered */
10426 trash = get_trash_chunk();
10427 index = 0;
10428 lua_pushnil(L);
10429 memset(kw, 0, sizeof(kw));
10430 while (lua_next(L, 1) != 0) {
10431 if (index >= CLI_PREFIX_KW_NB)
10432 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10433 if (lua_type(L, -1) != LUA_TSTRING)
10434 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10435 kw[index] = lua_tostring(L, -1);
10436 if (index == 0)
10437 chunk_printf(trash, "%s", kw[index]);
10438 else
10439 chunk_appendf(trash, " %s", kw[index]);
10440 index++;
10441 lua_pop(L, 1);
10442 }
10443 cli_kw = cli_find_kw_exact((char **)kw);
10444 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010445 fcn = cli_kw->private;
10446 if (fcn->function_ref[hlua_state_id] != -1) {
10447 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10448 "This will become a hard error in version 2.5.\n", trash->area);
10449 }
10450 fcn->function_ref[hlua_state_id] = ref_io;
10451 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010452 }
10453
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010454 /* Allocate and fill the sample fetch keyword struct. */
10455 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010456 if (!cli_kws) {
10457 errmsg = "Lua out of memory error.";
10458 goto error;
10459 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010460 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010461 if (!fcn) {
10462 errmsg = "Lua out of memory error.";
10463 goto error;
10464 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010465
10466 /* Fill path. */
10467 index = 0;
10468 lua_pushnil(L);
10469 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010470 if (index >= 5) {
10471 errmsg = "1st argument must be a table with a maximum of 5 entries";
10472 goto error;
10473 }
10474 if (lua_type(L, -1) != LUA_TSTRING) {
10475 errmsg = "1st argument must be a table filled with strings";
10476 goto error;
10477 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010478 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010479 if (!cli_kws->kw[0].str_kw[index]) {
10480 errmsg = "Lua out of memory error.";
10481 goto error;
10482 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010483 index++;
10484 lua_pop(L, 1);
10485 }
10486
10487 /* Copy help message. */
10488 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010489 if (!cli_kws->kw[0].usage) {
10490 errmsg = "Lua out of memory error.";
10491 goto error;
10492 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010493
10494 /* Fill fcn io handler. */
10495 len = strlen("<lua.cli>") + 1;
10496 for (i = 0; i < index; i++)
10497 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10498 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010499 if (!fcn->name) {
10500 errmsg = "Lua out of memory error.";
10501 goto error;
10502 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010503 strncat((char *)fcn->name, "<lua.cli", len);
10504 for (i = 0; i < index; i++) {
10505 strncat((char *)fcn->name, ".", len);
10506 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10507 }
10508 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010509 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010510
10511 /* Fill last entries. */
10512 cli_kws->kw[0].private = fcn;
10513 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10514 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10515 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10516
10517 /* Register this new converter */
10518 cli_register_kw(cli_kws);
10519
10520 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010521
10522 error:
10523 release_hlua_function(fcn);
10524 if (cli_kws) {
10525 for (i = 0; i < index; i++)
10526 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10527 ha_free((char **)&(cli_kws->kw[0].usage));
10528 }
10529 ha_free(&cli_kws);
10530 WILL_LJMP(luaL_error(L, errmsg));
10531 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010532}
10533
Christopher Faulet69c581a2021-05-31 08:54:04 +020010534static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10535{
10536 struct hlua_flt_config *conf = fconf->conf;
10537 lua_State *L;
10538 int error, pos, state_id, flt_ref;
10539
10540 state_id = reg_flt_to_stack_id(conf->reg);
10541 L = hlua_states[state_id];
10542 pos = lua_gettop(L);
10543
10544 /* The filter parsing function */
10545 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10546
10547 /* Push the filter class on the stack and resolve all callbacks */
10548 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10549
10550 /* Duplicate the filter class so each filter will have its own copy */
10551 lua_newtable(L);
10552 lua_pushnil(L);
10553
10554 while (lua_next(L, pos+2)) {
10555 lua_pushvalue(L, -2);
10556 lua_insert(L, -2);
10557 lua_settable(L, -4);
10558 }
10559 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10560
10561 /* Remove the original lua filter class from the stack */
10562 lua_pop(L, 1);
10563
10564 /* Push the copy on the stack */
10565 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10566
10567 /* extra args are pushed in a table */
10568 lua_newtable(L);
10569 for (pos = 0; conf->args[pos]; pos++) {
10570 /* Check stack available size. */
10571 if (!lua_checkstack(L, 1)) {
10572 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10573 goto error;
10574 }
10575 lua_pushstring(L, conf->args[pos]);
10576 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10577 }
10578
10579 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10580 switch (error) {
10581 case LUA_OK:
10582 /* replace the filter ref */
10583 conf->ref[state_id] = flt_ref;
10584 break;
10585 case LUA_ERRRUN:
10586 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10587 goto error;
10588 case LUA_ERRMEM:
10589 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10590 goto error;
10591 case LUA_ERRERR:
10592 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10593 goto error;
10594#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10595 case LUA_ERRGCMM:
10596 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10597 goto error;
10598#endif
10599 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010600 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010601 goto error;
10602 }
10603
10604 lua_settop(L, 0);
10605 return 0;
10606
10607 error:
10608 lua_settop(L, 0);
10609 return -1;
10610}
10611
10612static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10613{
10614 struct hlua_flt_config *conf = fconf->conf;
10615 lua_State *L;
10616 int state_id;
10617
10618 if (!conf)
10619 return;
10620
10621 state_id = reg_flt_to_stack_id(conf->reg);
10622 L = hlua_states[state_id];
10623 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10624}
10625
10626static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10627{
10628 struct hlua_flt_config *conf = fconf->conf;
10629 int state_id = reg_flt_to_stack_id(conf->reg);
10630
10631 /* Rely on per-thread init for global scripts */
10632 if (!state_id)
10633 return hlua_filter_init_per_thread(px, fconf);
10634 return 0;
10635}
10636
10637static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10638{
10639
10640 if (fconf->conf) {
10641 struct hlua_flt_config *conf = fconf->conf;
10642 int state_id = reg_flt_to_stack_id(conf->reg);
10643 int pos;
10644
10645 /* Rely on per-thread deinit for global scripts */
10646 if (!state_id)
10647 hlua_filter_deinit_per_thread(px, fconf);
10648
10649 for (pos = 0; conf->args[pos]; pos++)
10650 free(conf->args[pos]);
10651 free(conf->args);
10652 }
10653 ha_free(&fconf->conf);
10654 ha_free((char **)&fconf->id);
10655 ha_free(&fconf->ops);
10656}
10657
10658static int hlua_filter_new(struct stream *s, struct filter *filter)
10659{
10660 struct hlua_flt_config *conf = FLT_CONF(filter);
10661 struct hlua_flt_ctx *flt_ctx = NULL;
10662 int ret = 1;
10663
10664 /* In the execution wrappers linked with a stream, the
10665 * Lua context can be not initialized. This behavior
10666 * permits to save performances because a systematic
10667 * Lua initialization cause 5% performances loss.
10668 */
10669 if (!s->hlua) {
10670 struct hlua *hlua;
10671
10672 hlua = pool_alloc(pool_head_hlua);
10673 if (!hlua) {
10674 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10675 conf->reg->name);
10676 ret = 0;
10677 goto end;
10678 }
10679 HLUA_INIT(hlua);
10680 s->hlua = hlua;
10681 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10682 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10683 conf->reg->name);
10684 ret = 0;
10685 goto end;
10686 }
10687 }
10688
10689 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10690 if (!flt_ctx) {
10691 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10692 conf->reg->name);
10693 ret = 0;
10694 goto end;
10695 }
10696 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10697 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10698 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10699 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10700 conf->reg->name);
10701 ret = 0;
10702 goto end;
10703 }
10704 HLUA_INIT(flt_ctx->hlua[0]);
10705 HLUA_INIT(flt_ctx->hlua[1]);
10706 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10707 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10708 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10709 conf->reg->name);
10710 ret = 0;
10711 goto end;
10712 }
10713
10714 if (!HLUA_IS_RUNNING(s->hlua)) {
10715 /* The following Lua calls can fail. */
10716 if (!SET_SAFE_LJMP(s->hlua)) {
10717 const char *error;
10718
10719 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10720 error = lua_tostring(s->hlua->T, -1);
10721 else
10722 error = "critical error";
10723 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10724 ret = 0;
10725 goto end;
10726 }
10727
10728 /* Check stack size. */
10729 if (!lua_checkstack(s->hlua->T, 1)) {
10730 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010731 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010732 ret = 0;
10733 goto end;
10734 }
10735
10736 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10737 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10738 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10739 conf->reg->name);
10740 RESET_SAFE_LJMP(s->hlua);
10741 ret = 0;
10742 goto end;
10743 }
10744 lua_insert(s->hlua->T, -2);
10745
10746 /* Push the copy on the stack */
10747 s->hlua->nargs = 1;
10748
10749 /* We must initialize the execution timeouts. */
10750 s->hlua->max_time = hlua_timeout_session;
10751
10752 /* At this point the execution is safe. */
10753 RESET_SAFE_LJMP(s->hlua);
10754 }
10755
10756 switch (hlua_ctx_resume(s->hlua, 0)) {
10757 case HLUA_E_OK:
10758 /* Nothing returned or not a table, ignore the filter for current stream */
10759 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10760 ret = 0;
10761 goto end;
10762 }
10763
10764 /* Attached the filter pointer to the ctx */
10765 lua_pushstring(s->hlua->T, "__filter");
10766 lua_pushlightuserdata(s->hlua->T, filter);
10767 lua_settable(s->hlua->T, -3);
10768
10769 /* Save a ref on the filter ctx */
10770 lua_pushvalue(s->hlua->T, 1);
10771 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10772 filter->ctx = flt_ctx;
10773 break;
10774 case HLUA_E_ERRMSG:
10775 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10776 ret = -1;
10777 goto end;
10778 case HLUA_E_ETMOUT:
10779 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10780 ret = 0;
10781 goto end;
10782 case HLUA_E_NOMEM:
10783 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10784 ret = 0;
10785 goto end;
10786 case HLUA_E_AGAIN:
10787 case HLUA_E_YIELD:
10788 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10789 " are not allowed from 'new' function.\n", conf->reg->name);
10790 ret = 0;
10791 goto end;
10792 case HLUA_E_ERR:
10793 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10794 ret = 0;
10795 goto end;
10796 default:
10797 ret = 0;
10798 goto end;
10799 }
10800
10801 end:
10802 if (s->hlua)
10803 lua_settop(s->hlua->T, 0);
10804 if (ret <= 0) {
10805 if (flt_ctx) {
10806 hlua_ctx_destroy(flt_ctx->hlua[0]);
10807 hlua_ctx_destroy(flt_ctx->hlua[1]);
10808 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10809 }
10810 }
10811 return ret;
10812}
10813
10814static void hlua_filter_delete(struct stream *s, struct filter *filter)
10815{
10816 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10817
10818 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10819 hlua_ctx_destroy(flt_ctx->hlua[0]);
10820 hlua_ctx_destroy(flt_ctx->hlua[1]);
10821 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10822 filter->ctx = NULL;
10823}
10824
Christopher Faulet9f55a502020-02-25 15:21:02 +010010825static int hlua_filter_from_payload(struct filter *filter)
10826{
10827 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10828
10829 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10830}
10831
Christopher Fauletc404f112020-02-26 15:03:09 +010010832static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10833 int dir, unsigned int flags)
10834{
10835 struct hlua *flt_hlua;
10836 struct hlua_flt_config *conf = FLT_CONF(filter);
10837 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10838 unsigned int hflags = HLUA_TXN_FLT_CTX;
10839 int ret = 1;
10840
10841 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10842 if (!flt_hlua)
10843 goto end;
10844
10845 if (!HLUA_IS_RUNNING(flt_hlua)) {
10846 int extra_idx = lua_gettop(flt_hlua->T);
10847
10848 /* The following Lua calls can fail. */
10849 if (!SET_SAFE_LJMP(flt_hlua)) {
10850 const char *error;
10851
10852 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10853 error = lua_tostring(flt_hlua->T, -1);
10854 else
10855 error = "critical error";
10856 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10857 goto end;
10858 }
10859
10860 /* Check stack size. */
10861 if (!lua_checkstack(flt_hlua->T, 3)) {
10862 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10863 RESET_SAFE_LJMP(flt_hlua);
10864 goto end;
10865 }
10866
10867 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10868 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10869 RESET_SAFE_LJMP(flt_hlua);
10870 goto end;
10871 }
10872 lua_insert(flt_hlua->T, -2);
10873
10874 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10875 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10876 RESET_SAFE_LJMP(flt_hlua);
10877 goto end;
10878 }
10879 flt_hlua->nargs = 2;
10880
10881 if (flags & HLUA_FLT_CB_ARG_CHN) {
10882 if (dir == SMP_OPT_DIR_REQ)
10883 lua_getfield(flt_hlua->T, -1, "req");
10884 else
10885 lua_getfield(flt_hlua->T, -1, "res");
10886 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10887 lua_pushstring(flt_hlua->T, "__filter");
10888 lua_pushlightuserdata(flt_hlua->T, filter);
10889 lua_settable(flt_hlua->T, -3);
10890 }
10891 flt_hlua->nargs++;
10892 }
10893 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010894 if (dir == SMP_OPT_DIR_REQ)
10895 lua_getfield(flt_hlua->T, -1, "http_req");
10896 else
10897 lua_getfield(flt_hlua->T, -1, "http_res");
10898 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10899 lua_pushstring(flt_hlua->T, "__filter");
10900 lua_pushlightuserdata(flt_hlua->T, filter);
10901 lua_settable(flt_hlua->T, -3);
10902 }
10903 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010904 }
10905
10906 /* Check stack size. */
10907 if (!lua_checkstack(flt_hlua->T, 1)) {
10908 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10909 RESET_SAFE_LJMP(flt_hlua);
10910 goto end;
10911 }
10912
10913 while (extra_idx--) {
10914 lua_pushvalue(flt_hlua->T, 1);
10915 lua_remove(flt_hlua->T, 1);
10916 flt_hlua->nargs++;
10917 }
10918
10919 /* We must initialize the execution timeouts. */
10920 flt_hlua->max_time = hlua_timeout_session;
10921
10922 /* At this point the execution is safe. */
10923 RESET_SAFE_LJMP(flt_hlua);
10924 }
10925
10926 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10927 case HLUA_E_OK:
10928 /* Catch the return value if it required */
10929 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10930 ret = lua_tointeger(flt_hlua->T, -1);
10931 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10932 }
10933
10934 /* Set timeout in the required channel. */
10935 if (flt_hlua->wake_time != TICK_ETERNITY) {
10936 if (dir == SMP_OPT_DIR_REQ)
10937 s->req.analyse_exp = flt_hlua->wake_time;
10938 else
10939 s->res.analyse_exp = flt_hlua->wake_time;
10940 }
10941 break;
10942 case HLUA_E_AGAIN:
10943 /* Set timeout in the required channel. */
10944 if (flt_hlua->wake_time != TICK_ETERNITY) {
10945 if (dir == SMP_OPT_DIR_REQ)
10946 s->req.analyse_exp = flt_hlua->wake_time;
10947 else
10948 s->res.analyse_exp = flt_hlua->wake_time;
10949 }
10950 /* Some actions can be wake up when a "write" event
10951 * is detected on a response channel. This is useful
10952 * only for actions targeted on the requests.
10953 */
10954 if (HLUA_IS_WAKERESWR(flt_hlua))
10955 s->res.flags |= CF_WAKE_WRITE;
10956 if (HLUA_IS_WAKEREQWR(flt_hlua))
10957 s->req.flags |= CF_WAKE_WRITE;
10958 ret = 0;
10959 goto end;
10960 case HLUA_E_ERRMSG:
10961 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10962 ret = -1;
10963 goto end;
10964 case HLUA_E_ETMOUT:
10965 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10966 goto end;
10967 case HLUA_E_NOMEM:
10968 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10969 goto end;
10970 case HLUA_E_YIELD:
10971 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10972 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10973 goto end;
10974 case HLUA_E_ERR:
10975 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10976 goto end;
10977 default:
10978 goto end;
10979 }
10980
10981
10982 end:
10983 return ret;
10984}
10985
10986static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10987{
10988 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10989
10990 flt_ctx->flags = 0;
10991 return hlua_filter_callback(s, filter, "start_analyze",
10992 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10993 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10994}
10995
10996static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10997{
10998 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10999
11000 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11001 return hlua_filter_callback(s, filter, "end_analyze",
11002 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11003 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11004}
11005
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011006static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11007{
11008 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11009
11010 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11011 return hlua_filter_callback(s, filter, "http_headers",
11012 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11013 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11014}
11015
11016static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11017 unsigned int offset, unsigned int len)
11018{
11019 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11020 struct hlua *flt_hlua;
11021 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11022 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11023 int ret;
11024
11025 flt_hlua = flt_ctx->hlua[idx];
11026 flt_ctx->cur_off[idx] = offset;
11027 flt_ctx->cur_len[idx] = len;
11028 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11029 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11030 if (ret != -1) {
11031 ret = flt_ctx->cur_len[idx];
11032 if (lua_gettop(flt_hlua->T) > 0) {
11033 ret = lua_tointeger(flt_hlua->T, -1);
11034 if (ret > flt_ctx->cur_len[idx])
11035 ret = flt_ctx->cur_len[idx];
11036 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11037 }
11038 }
11039 return ret;
11040}
11041
11042static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11043{
11044 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11045
11046 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11047 return hlua_filter_callback(s, filter, "http_end",
11048 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11049 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11050}
11051
Christopher Fauletc404f112020-02-26 15:03:09 +010011052static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11053 unsigned int offset, unsigned int len)
11054{
11055 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11056 struct hlua *flt_hlua;
11057 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11058 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11059 int ret;
11060
11061 flt_hlua = flt_ctx->hlua[idx];
11062 flt_ctx->cur_off[idx] = offset;
11063 flt_ctx->cur_len[idx] = len;
11064 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11065 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11066 if (ret != -1) {
11067 ret = flt_ctx->cur_len[idx];
11068 if (lua_gettop(flt_hlua->T) > 0) {
11069 ret = lua_tointeger(flt_hlua->T, -1);
11070 if (ret > flt_ctx->cur_len[idx])
11071 ret = flt_ctx->cur_len[idx];
11072 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11073 }
11074 }
11075 return ret;
11076}
11077
Christopher Faulet69c581a2021-05-31 08:54:04 +020011078static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11079 struct flt_conf *fconf, char **err, void *private)
11080{
11081 struct hlua_reg_filter *reg_flt = private;
11082 lua_State *L;
11083 struct hlua_flt_config *conf = NULL;
11084 const char *flt_id = NULL;
11085 int state_id, pos, flt_flags = 0;
11086 struct flt_ops *hlua_flt_ops = NULL;
11087
11088 state_id = reg_flt_to_stack_id(reg_flt);
11089 L = hlua_states[state_id];
11090
11091 /* Initialize the filter ops with default callbacks */
11092 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011093 if (!hlua_flt_ops)
11094 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011095 hlua_flt_ops->init = hlua_filter_init;
11096 hlua_flt_ops->deinit = hlua_filter_deinit;
11097 if (state_id) {
11098 /* Set per-thread callback if script is loaded per-thread */
11099 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11100 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11101 }
11102 hlua_flt_ops->attach = hlua_filter_new;
11103 hlua_flt_ops->detach = hlua_filter_delete;
11104
11105 /* Push the filter class on the stack and resolve all callbacks */
11106 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11107
Christopher Fauletc404f112020-02-26 15:03:09 +010011108 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11109 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11110 lua_pop(L, 1);
11111 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11112 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11113 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011114 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11115 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11116 lua_pop(L, 1);
11117 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11118 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11119 lua_pop(L, 1);
11120 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11121 hlua_flt_ops->http_end = hlua_filter_http_end;
11122 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011123 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11124 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11125 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011126
11127 /* Get id and flags of the filter class */
11128 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11129 flt_id = lua_tostring(L, -1);
11130 lua_pop(L, 1);
11131 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11132 flt_flags = lua_tointeger(L, -1);
11133 lua_pop(L, 1);
11134
11135 /* Create the filter config */
11136 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011137 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011138 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011139 conf->reg = reg_flt;
11140
11141 /* duplicate args */
11142 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11143 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011144 if (!conf->args)
11145 goto error;
11146 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011147 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011148 if (!conf->args[pos])
11149 goto error;
11150 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011151 conf->args[pos] = NULL;
11152 *cur_arg += pos + 1;
11153
Christopher Fauletc86bb872021-08-13 08:33:57 +020011154 if (flt_id) {
11155 fconf->id = strdup(flt_id);
11156 if (!fconf->id)
11157 goto error;
11158 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011159 fconf->flags = flt_flags;
11160 fconf->conf = conf;
11161 fconf->ops = hlua_flt_ops;
11162
11163 lua_settop(L, 0);
11164 return 0;
11165
11166 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011167 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011168 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011169 if (conf && conf->args) {
11170 for (pos = 0; conf->args[pos]; pos++)
11171 free(conf->args[pos]);
11172 free(conf->args);
11173 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011174 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011175 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011176 lua_settop(L, 0);
11177 return -1;
11178}
11179
Christopher Fauletc404f112020-02-26 15:03:09 +010011180__LJMP static int hlua_register_data_filter(lua_State *L)
11181{
11182 struct filter *filter;
11183 struct channel *chn;
11184
11185 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11186 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11187 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11188
11189 lua_getfield(L, 1, "__filter");
11190 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11191 filter = lua_touserdata (L, -1);
11192 lua_pop(L, 1);
11193
11194 register_data_filter(chn_strm(chn), chn, filter);
11195 return 1;
11196}
11197
11198__LJMP static int hlua_unregister_data_filter(lua_State *L)
11199{
11200 struct filter *filter;
11201 struct channel *chn;
11202
11203 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11204 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11205 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11206
11207 lua_getfield(L, 1, "__filter");
11208 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11209 filter = lua_touserdata (L, -1);
11210 lua_pop(L, 1);
11211
11212 unregister_data_filter(chn_strm(chn), chn, filter);
11213 return 1;
11214}
11215
Christopher Faulet69c581a2021-05-31 08:54:04 +020011216/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011217 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011218 * parse configuration arguments.
11219 */
11220__LJMP static int hlua_register_filter(lua_State *L)
11221{
11222 struct buffer *trash;
11223 struct flt_kw_list *fkl;
11224 struct flt_kw *fkw;
11225 const char *name;
11226 struct hlua_reg_filter *reg_flt= NULL;
11227 int flt_ref, fun_ref;
11228 int len;
11229
11230 MAY_LJMP(check_args(L, 3, "register_filter"));
11231
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011232 if (hlua_gethlua(L)) {
11233 /* runtime processing */
11234 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
11235 }
11236
Christopher Faulet69c581a2021-05-31 08:54:04 +020011237 /* First argument : filter name. */
11238 name = MAY_LJMP(luaL_checkstring(L, 1));
11239
11240 /* Second argument : The filter class */
11241 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11242
11243 /* Third argument : lua function. */
11244 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11245
11246 trash = get_trash_chunk();
11247 chunk_printf(trash, "lua.%s", name);
11248 fkw = flt_find_kw(trash->area);
11249 if (fkw != NULL) {
11250 reg_flt = fkw->private;
11251 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11252 ha_warning("Trying to register filter 'lua.%s' more than once. "
11253 "This will become a hard error in version 2.5.\n", name);
11254 }
11255 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11256 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11257 return 0;
11258 }
11259
11260 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11261 if (!fkl)
11262 goto alloc_error;
11263 fkl->scope = "HLUA";
11264
11265 reg_flt = new_hlua_reg_filter(name);
11266 if (!reg_flt)
11267 goto alloc_error;
11268
11269 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11270 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11271
11272 /* The filter keyword */
11273 len = strlen("lua.") + strlen(name) + 1;
11274 fkl->kw[0].kw = calloc(1, len);
11275 if (!fkl->kw[0].kw)
11276 goto alloc_error;
11277
11278 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11279
11280 fkl->kw[0].parse = hlua_filter_parse_fct;
11281 fkl->kw[0].private = reg_flt;
11282 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11283
11284 /* Register this new filter */
11285 flt_register_keywords(fkl);
11286
11287 return 0;
11288
11289 alloc_error:
11290 release_hlua_reg_filter(reg_flt);
11291 ha_free(&fkl);
11292 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11293 return 0; /* Never reached */
11294}
11295
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011296static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011297 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011298 char **err, unsigned int *timeout)
11299{
11300 const char *error;
11301
11302 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011303 if (error == PARSE_TIME_OVER) {
11304 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11305 args[1], args[0]);
11306 return -1;
11307 }
11308 else if (error == PARSE_TIME_UNDER) {
11309 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11310 args[1], args[0]);
11311 return -1;
11312 }
11313 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011314 memprintf(err, "%s: invalid timeout", args[0]);
11315 return -1;
11316 }
11317 return 0;
11318}
11319
11320static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011321 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011322 char **err)
11323{
11324 return hlua_read_timeout(args, section_type, curpx, defpx,
11325 file, line, err, &hlua_timeout_session);
11326}
11327
11328static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011329 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011330 char **err)
11331{
11332 return hlua_read_timeout(args, section_type, curpx, defpx,
11333 file, line, err, &hlua_timeout_task);
11334}
11335
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011336static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011337 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011338 char **err)
11339{
11340 return hlua_read_timeout(args, section_type, curpx, defpx,
11341 file, line, err, &hlua_timeout_applet);
11342}
11343
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011344static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011345 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011346 char **err)
11347{
11348 char *error;
11349
11350 hlua_nb_instruction = strtoll(args[1], &error, 10);
11351 if (*error != '\0') {
11352 memprintf(err, "%s: invalid number", args[0]);
11353 return -1;
11354 }
11355 return 0;
11356}
11357
Willy Tarreau32f61e22015-03-18 17:54:59 +010011358static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011359 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011360 char **err)
11361{
11362 char *error;
11363
11364 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011365 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011366 return -1;
11367 }
11368 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11369 if (*error != '\0') {
11370 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11371 return -1;
11372 }
11373 return 0;
11374}
11375
11376
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011377/* This function is called by the main configuration key "lua-load". It loads and
11378 * execute an lua file during the parsing of the HAProxy configuration file. It is
11379 * the main lua entry point.
11380 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011381 * This function runs with the HAProxy keywords API. It returns -1 if an error
11382 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011383 *
11384 * In some error case, LUA set an error message in top of the stack. This function
11385 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011386 *
11387 * This function can fail with an abort() due to an Lua critical error.
11388 * We are in the configuration parsing process of HAProxy, this abort() is
11389 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011390 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011391static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011392{
11393 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011394 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011395
11396 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011397 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011398 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011399 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011400 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011401 return -1;
11402 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011403
11404 /* Push args in the Lua stack, except the first one which is the filename */
11405 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011406 /* Check stack size. */
11407 if (!lua_checkstack(L, 1)) {
11408 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11409 return -1;
11410 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011411 lua_pushstring(L, args[nargs]);
11412 }
11413 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011414
11415 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011416 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011417 switch (error) {
11418 case LUA_OK:
11419 break;
11420 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011421 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011422 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011423 return -1;
11424 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011425 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011426 return -1;
11427 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011428 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011429 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011430 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011431#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011432 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011433 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011434 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011435 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011436#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011437 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011438 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011439 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011440 return -1;
11441 }
11442
11443 return 0;
11444}
11445
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011446static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011447 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011448 char **err)
11449{
11450 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011451 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011452 return -1;
11453 }
11454
Thierry Fournier59f11be2020-11-29 00:37:41 +010011455 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011456 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011457 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011458 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011459}
11460
Thierry Fournier59f11be2020-11-29 00:37:41 +010011461static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011462 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011463 char **err)
11464{
11465 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011466 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011467
11468 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011469 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011470 return -1;
11471 }
11472
11473 if (per_thread_load == NULL) {
11474 /* allocate the first entry large enough to store the final NULL */
11475 per_thread_load = calloc(1, sizeof(*per_thread_load));
11476 if (per_thread_load == NULL) {
11477 memprintf(err, "out of memory error");
11478 return -1;
11479 }
11480 }
11481
11482 /* count used entries */
11483 for (len = 0; per_thread_load[len] != NULL; len++)
11484 ;
11485
11486 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11487 if (per_thread_load == NULL) {
11488 memprintf(err, "out of memory error");
11489 return -1;
11490 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011491 per_thread_load[len + 1] = NULL;
11492
Thierry Fournierae6b5682022-09-19 09:04:16 +020011493 /* count args excepting the first, allocate array and copy args */
11494 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011495 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011496 if (per_thread_load[len] == NULL) {
11497 memprintf(err, "out of memory error");
11498 return -1;
11499 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011500 for (i = 1; *(args[i]) != 0; i++) {
11501 per_thread_load[len][i - 1] = strdup(args[i]);
11502 if (per_thread_load[len][i - 1] == NULL) {
11503 memprintf(err, "out of memory error");
11504 return -1;
11505 }
11506 }
11507 per_thread_load[len][i - 1] = strdup("");
11508 if (per_thread_load[len][i - 1] == NULL) {
11509 memprintf(err, "out of memory error");
11510 return -1;
11511 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011512
11513 /* loading for thread 1 only */
11514 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011515 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011516 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011517}
11518
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011519/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11520 * in the given <ctx>.
11521 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011522static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011523{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011524 lua_getglobal(L, "package"); /* push package variable */
11525 lua_pushstring(L, path); /* push given path */
11526 lua_pushstring(L, ";"); /* push semicolon */
11527 lua_getfield(L, -3, type); /* push old path */
11528 lua_concat(L, 3); /* concatenate to new path */
11529 lua_setfield(L, -2, type); /* store new path */
11530 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011531
11532 return 0;
11533}
11534
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011535static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011536 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011537 char **err)
11538{
11539 char *path;
11540 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011541 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011542 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011543
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011544 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011545 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011546 }
11547
11548 if (!(*args[1])) {
11549 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011550 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011551 }
11552 path = args[1];
11553
11554 if (*args[2]) {
11555 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11556 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011557 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011558 }
11559 type = args[2];
11560 }
11561
Thierry Fournier59f11be2020-11-29 00:37:41 +010011562 p = calloc(1, sizeof(*p));
11563 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011564 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011565 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011566 }
11567 p->path = strdup(path);
11568 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011569 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011570 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011571 }
11572 p->type = strdup(type);
11573 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011574 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011575 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011576 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011577 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011578
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011579 /* Handle the global state and the per-thread state for the first
11580 * thread. The remaining threads will be initialized based on
11581 * prepend_path_list.
11582 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011583 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011584 lua_State *L = hlua_states[i];
11585 const char *error;
11586
11587 if (setjmp(safe_ljmp_env) != 0) {
11588 lua_atpanic(L, hlua_panic_safe);
11589 if (lua_type(L, -1) == LUA_TSTRING)
11590 error = lua_tostring(L, -1);
11591 else
11592 error = "critical error";
11593 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11594 exit(1);
11595 } else {
11596 lua_atpanic(L, hlua_panic_ljmp);
11597 }
11598
11599 hlua_prepend_path(L, type, path);
11600
11601 lua_atpanic(L, hlua_panic_safe);
11602 }
11603
Thierry Fournier59f11be2020-11-29 00:37:41 +010011604 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011605
11606err2:
11607 free(p->type);
11608 free(p->path);
11609err:
11610 free(p);
11611 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011612}
11613
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011614/* configuration keywords declaration */
11615static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011616 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011617 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011618 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011619 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11620 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011621 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011622 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011623 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011624 { 0, NULL, NULL },
11625}};
11626
Willy Tarreau0108d902018-11-25 19:14:37 +010011627INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11628
William Lallemand52139182022-03-30 15:05:42 +020011629#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011630
William Lallemand30fcca12022-03-30 12:03:12 +020011631/*
11632 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11633 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11634 * difference is that the yield in lua and for the CLI is not handled the same
11635 * way.
11636 */
11637__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11638{
11639 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11640 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11641 struct ckch_inst *ckchi = *lua_ckchi;
11642 struct ckch_store *old_ckchs = lua_ckchs[0];
11643 struct ckch_store *new_ckchs = lua_ckchs[1];
11644 struct hlua *hlua;
11645 char *err = NULL;
11646 int y = 1;
11647
11648 hlua = hlua_gethlua(L);
11649
11650 /* get the first ckchi to copy */
11651 if (ckchi == NULL)
11652 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11653
11654 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11655 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11656 struct ckch_inst *new_inst;
11657
11658 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11659 if (y % 10 == 0) {
11660
11661 *lua_ckchi = ckchi;
11662
11663 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11664 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11665 }
11666
11667 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11668 goto error;
11669
11670 /* link the new ckch_inst to the duplicate */
11671 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11672 y++;
11673 }
11674
11675 /* The generation is finished, we can insert everything */
11676 ckch_store_replace(old_ckchs, new_ckchs);
11677
11678 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11679
11680 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11681
11682 return 0;
11683
11684error:
11685 ckch_store_free(new_ckchs);
11686 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11687 WILL_LJMP(luaL_error(L, "%s", err));
11688 free(err);
11689
11690 return 0;
11691}
11692
11693/*
11694 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11695 * from the table in parameter.
11696 *
11697 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11698 * means it does not need to have a transaction since everything is done in the
11699 * same function.
11700 *
11701 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11702 *
11703 */
11704__LJMP static int hlua_ckch_set(lua_State *L)
11705{
11706 struct hlua *hlua;
11707 struct ckch_inst **lua_ckchi;
11708 struct ckch_store **lua_ckchs;
11709 struct ckch_store *old_ckchs = NULL;
11710 struct ckch_store *new_ckchs = NULL;
11711 int errcode = 0;
11712 char *err = NULL;
11713 struct cert_exts *cert_ext = NULL;
11714 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010011715 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020011716 int ret;
11717
11718 if (lua_type(L, -1) != LUA_TTABLE)
11719 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11720
11721 hlua = hlua_gethlua(L);
11722
11723 /* FIXME: this should not return an error but should come back later */
11724 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11725 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11726
11727 ret = lua_getfield(L, -1, "filename");
11728 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011729 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011730 errcode |= ERR_ALERT | ERR_FATAL;
11731 goto end;
11732 }
11733 filename = (char *)lua_tostring(L, -1);
11734
11735
11736 /* look for the filename in the tree */
11737 old_ckchs = ckchs_lookup(filename);
11738 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011739 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011740 errcode |= ERR_ALERT | ERR_FATAL;
11741 goto end;
11742 }
11743 /* TODO: handle extra_files_noext */
11744
11745 new_ckchs = ckchs_dup(old_ckchs);
11746 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011747 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011748 errcode |= ERR_ALERT | ERR_FATAL;
11749 goto end;
11750 }
11751
William Lallemand52ddd992022-11-22 11:51:53 +010011752 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020011753
11754 /* loop on the field in the table, which have the same name as the
11755 * possible extensions of files */
11756 lua_pushnil(L);
11757 while (lua_next(L, 1)) {
11758 int i;
11759 const char *field = lua_tostring(L, -2);
11760 char *payload = (char *)lua_tostring(L, -1);
11761
11762 if (!field || strcmp(field, "filename") == 0) {
11763 lua_pop(L, 1);
11764 continue;
11765 }
11766
11767 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11768 if (strcmp(field, cert_exts[i].ext) == 0) {
11769 cert_ext = &cert_exts[i];
11770 break;
11771 }
11772 }
11773
11774 /* this is the default type, the field is not supported */
11775 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011776 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011777 errcode |= ERR_ALERT | ERR_FATAL;
11778 goto end;
11779 }
11780
11781 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010011782 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011783 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011784 errcode |= ERR_ALERT | ERR_FATAL;
11785 goto end;
11786 }
11787 lua_pop(L, 1);
11788 }
11789
11790 /* store the pointers on the lua stack */
11791 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11792 lua_ckchs[0] = old_ckchs;
11793 lua_ckchs[1] = new_ckchs;
11794 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11795 *lua_ckchi = NULL;
11796
11797 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11798 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11799
11800end:
11801 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11802
11803 if (errcode & ERR_CODE) {
11804 ckch_store_free(new_ckchs);
11805 WILL_LJMP(luaL_error(L, "%s", err));
11806 }
11807 free(err);
11808
11809 return 0;
11810}
11811
William Lallemand52139182022-03-30 15:05:42 +020011812#else
11813
11814__LJMP static int hlua_ckch_set(lua_State *L)
11815{
11816 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11817
11818 return 0;
11819}
11820#endif /* ! USE_OPENSSL */
11821
11822
11823
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011824/* This function can fail with an abort() due to an Lua critical error.
11825 * We are in the initialisation process of HAProxy, this abort() is
11826 * tolerated.
11827 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011828int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011829{
11830 struct hlua_init_function *init;
11831 const char *msg;
11832 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011833 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011834 const char *kind;
11835 const char *trace;
11836 int return_status = 1;
11837#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11838 int nres;
11839#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011840
Willy Tarreaucdb53462020-12-02 12:12:00 +010011841 /* disable memory limit checks if limit is not set */
11842 if (!hlua_global_allocator.limit)
11843 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11844
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011845 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011846 if (setjmp(safe_ljmp_env) != 0) {
11847 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011848 if (lua_type(L, -1) == LUA_TSTRING)
11849 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011850 else
11851 error = "critical error";
11852 fprintf(stderr, "Lua post-init: %s.\n", error);
11853 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011854 } else {
11855 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011856 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011857
Thierry Fournierc7492592020-11-28 23:57:24 +010011858 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011859 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010011860 /* function ref should be released right away since it was pushed
11861 * on the stack and will not be used anymore
11862 */
11863 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011864
11865#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011866 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011867#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011868 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011869#endif
11870 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011871 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011872
11873 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011874 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011875 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011876
11877 case LUA_ERRERR:
11878 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011879 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011880 case LUA_ERRRUN:
11881 if (!kind)
11882 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011883 msg = lua_tostring(L, -1);
11884 lua_settop(L, 0); /* Empty the stack. */
11885 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011886 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011887 if (msg)
11888 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11889 else
11890 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11891 return_status = 0;
11892 break;
11893
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011894 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011895 /* Unknown error */
11896 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011897 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011898 case LUA_YIELD:
11899 /* yield is not configured at this step, this state doesn't happen */
11900 if (!kind)
11901 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010011902 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011903 case LUA_ERRMEM:
11904 if (!kind)
11905 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011906 lua_settop(L, 0);
11907 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011908 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011909 ha_alert("Lua init: %s: %s\n", kind, trace);
11910 return_status = 0;
11911 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011912 }
Thierry Fournier670db242020-11-28 10:49:59 +010011913 if (!return_status)
11914 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011915 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011916
11917 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011918 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011919}
11920
Thierry Fournierb8cef172020-11-28 15:37:17 +010011921int hlua_post_init()
11922{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011923 int ret;
11924 int i;
11925 int errors;
11926 char *err = NULL;
11927 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011928 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011929
Willy Tarreaub1310492021-08-30 09:35:18 +020011930#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011931 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011932 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011933 int saved_used_backed = global.ssl_used_backend;
11934 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011935 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011936 global.ssl_used_backend = saved_used_backed;
11937 }
11938#endif
11939
Thierry Fournierc7492592020-11-28 23:57:24 +010011940 /* Perform post init of common thread */
11941 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011942 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011943 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11944 if (ret == 0)
11945 return 0;
11946
11947 /* init remaining lua states and load files */
11948 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11949
11950 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011951 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011952
11953 /* Init lua state */
11954 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11955
11956 /* Load lua files */
11957 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11958 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11959 if (ret != 0) {
11960 ha_alert("Lua init: %s\n", err);
11961 return 0;
11962 }
11963 }
11964 }
11965
11966 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011967 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011968
11969 /* Execute post init for all states */
11970 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11971
11972 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011973 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011974
11975 /* run post init */
11976 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11977 if (ret == 0)
11978 return 0;
11979 }
11980
11981 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011982 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011983
11984 /* control functions registering. Each function must have:
11985 * - only the function_ref[0] set positive and all other to -1
11986 * - only the function_ref[0] set to -1 and all other positive
11987 * This ensure a same reference is not used both in shared
11988 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011989 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011990 * complicated to found for the end user.
11991 */
11992 errors = 0;
11993 list_for_each_entry(fcn, &referenced_functions, l) {
11994 ret = 0;
11995 for (i = 1; i < global.nbthread + 1; i++) {
11996 if (fcn->function_ref[i] == -1)
11997 ret--;
11998 else
11999 ret++;
12000 }
12001 if (abs(ret) != global.nbthread) {
12002 ha_alert("Lua function '%s' is not referenced in all thread. "
12003 "Expect function in all thread or in none thread.\n", fcn->name);
12004 errors++;
12005 continue;
12006 }
12007
12008 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012009 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12010 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012011 "exclusive.\n", fcn->name);
12012 errors++;
12013 }
12014 }
12015
Christopher Faulet69c581a2021-05-31 08:54:04 +020012016 /* Do the same with registered filters */
12017 list_for_each_entry(reg_flt, &referenced_filters, l) {
12018 ret = 0;
12019 for (i = 1; i < global.nbthread + 1; i++) {
12020 if (reg_flt->flt_ref[i] == -1)
12021 ret--;
12022 else
12023 ret++;
12024 }
12025 if (abs(ret) != global.nbthread) {
12026 ha_alert("Lua filter '%s' is not referenced in all thread. "
12027 "Expect function in all thread or in none thread.\n", reg_flt->name);
12028 errors++;
12029 continue;
12030 }
12031
12032 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12033 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12034 "and per-thread Lua context (through lua-load-per-thread). these two context "
12035 "exclusive.\n", fcn->name);
12036 errors++;
12037 }
12038 }
12039
12040
Thierry Fournier59f11be2020-11-29 00:37:41 +010012041 if (errors > 0)
12042 return 0;
12043
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012044 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012045 * -1 in order to have probably a segfault if someone use it
12046 */
12047 hlua_state_id = -1;
12048
12049 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012050}
12051
Willy Tarreau32f61e22015-03-18 17:54:59 +010012052/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12053 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12054 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012055 * allocation. <nsize> is the requested new size. A new allocation is
12056 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010012057 * zero. This one verifies that the limits are respected but is optimized
12058 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012059 *
12060 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
12061 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
12062 * that and will simply allocate zero as if it were the result of malloc(0),
12063 * so mapping this onto realloc() will lead to memory leaks on non-glibc
12064 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010012065 */
12066static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
12067{
12068 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010012069 size_t limit, old, new;
12070
12071 /* a limit of ~0 means unlimited and boot complete, so there's no need
12072 * for accounting anymore.
12073 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012074 if (likely(~zone->limit == 0)) {
12075 if (!nsize)
12076 ha_free(&ptr);
12077 else
12078 ptr = realloc(ptr, nsize);
12079 return ptr;
12080 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010012081
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012082 if (!ptr)
12083 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012084
Willy Tarreaucdb53462020-12-02 12:12:00 +010012085 /* enforce strict limits across all threads */
12086 limit = zone->limit;
12087 old = _HA_ATOMIC_LOAD(&zone->allocated);
12088 do {
12089 new = old + nsize - osize;
12090 if (unlikely(nsize && limit && new > limit))
12091 return NULL;
12092 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012093
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012094 if (!nsize)
12095 ha_free(&ptr);
12096 else
12097 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012098
12099 if (unlikely(!ptr && nsize)) // failed
12100 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12101
12102 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012103 return ptr;
12104}
12105
Thierry Fournierecb83c22020-11-28 15:49:44 +010012106/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012107 * We are in the initialisation process of HAProxy, this abort() is
12108 * tolerated.
12109 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012110lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012111{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012112 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012113 int idx;
12114 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012115 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012116 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012117 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012118 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012119 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012120 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012121
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012122 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012123 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012124
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012125 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012126 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012127 *context = NULL;
12128
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012129 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012130 * the Lua function can fail with an abort. We are in the initialisation
12131 * process of HAProxy, this abort() is tolerated.
12132 */
12133
Thierry Fournier3c539322020-11-28 16:05:05 +010012134 /* Call post initialisation function in safe environment. */
12135 if (setjmp(safe_ljmp_env) != 0) {
12136 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012137 if (lua_type(L, -1) == LUA_TSTRING)
12138 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012139 else
12140 error_msg = "critical error";
12141 fprintf(stderr, "Lua init: %s.\n", error_msg);
12142 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012143 } else {
12144 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012145 }
12146
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012147 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012148 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012149#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12150#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12151#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012152 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012153#endif
12154#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012155 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012156#endif
12157#undef HLUA_PREPEND_PATH_TOSTRING
12158#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012159
Thierry Fournier59f11be2020-11-29 00:37:41 +010012160 /* Apply configured prepend path */
12161 list_for_each_entry(pp, &prepend_path_list, l)
12162 hlua_prepend_path(L, pp->type, pp->path);
12163
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012164 /*
12165 *
12166 * Create "core" object.
12167 *
12168 */
12169
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012170 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012172
Thierry Fournierecb83c22020-11-28 15:49:44 +010012173 /* set the thread id */
12174 hlua_class_const_int(L, "thread", thread_num);
12175
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012176 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012177 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012178 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012179
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012180 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012181 hlua_class_function(L, "register_init", hlua_register_init);
12182 hlua_class_function(L, "register_task", hlua_register_task);
12183 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12184 hlua_class_function(L, "register_converters", hlua_register_converters);
12185 hlua_class_function(L, "register_action", hlua_register_action);
12186 hlua_class_function(L, "register_service", hlua_register_service);
12187 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012188 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012189 hlua_class_function(L, "yield", hlua_yield);
12190 hlua_class_function(L, "set_nice", hlua_set_nice);
12191 hlua_class_function(L, "sleep", hlua_sleep);
12192 hlua_class_function(L, "msleep", hlua_msleep);
12193 hlua_class_function(L, "add_acl", hlua_add_acl);
12194 hlua_class_function(L, "del_acl", hlua_del_acl);
12195 hlua_class_function(L, "set_map", hlua_set_map);
12196 hlua_class_function(L, "del_map", hlua_del_map);
12197 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012198 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012199 hlua_class_function(L, "log", hlua_log);
12200 hlua_class_function(L, "Debug", hlua_log_debug);
12201 hlua_class_function(L, "Info", hlua_log_info);
12202 hlua_class_function(L, "Warning", hlua_log_warning);
12203 hlua_class_function(L, "Alert", hlua_log_alert);
12204 hlua_class_function(L, "done", hlua_done);
12205 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012206
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012207 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012208
12209 /*
12210 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012211 * Create "act" object.
12212 *
12213 */
12214
12215 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012216 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012217
12218 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012219 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12220 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12221 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12222 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12223 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12224 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12225 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12226 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012227
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012228 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012229
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012230 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012231
12232 /*
12233 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012234 * Create "Filter" object.
12235 *
12236 */
12237
12238 /* This table entry is the object "filter" base. */
12239 lua_newtable(L);
12240
12241 /* push flags and constants */
12242 hlua_class_const_int(L, "CONTINUE", 1);
12243 hlua_class_const_int(L, "WAIT", 0);
12244 hlua_class_const_int(L, "ERROR", -1);
12245
12246 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12247
Christopher Fauletc404f112020-02-26 15:03:09 +010012248 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12249 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12250 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12251
Christopher Faulet69c581a2021-05-31 08:54:04 +020012252 lua_setglobal(L, "filter");
12253
12254 /*
12255 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012256 * Register class Map
12257 *
12258 */
12259
12260 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012261 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012262
12263 /* register pattern types. */
12264 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012265 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012266 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012267 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012268 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012269 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012270
12271 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012272 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012273
12274 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012275 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012276
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 FOURNIER3def3932015-04-07 11:27:54 +020012280
12281 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012282 hlua_class_function(L, "lookup", hlua_map_lookup);
12283 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012284
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012285 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012286
Thierry Fournier45e78d72016-02-19 18:34:46 +010012287 /* Register previous table in the registry with reference and named entry.
12288 * The function hlua_register_metatable() pops the stack, so we
12289 * previously create a copy of the table.
12290 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012291 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12292 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012293
12294 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012295 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012296
12297 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012298 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012299
12300 /*
12301 *
William Lallemand30fcca12022-03-30 12:03:12 +020012302 * Register "CertCache" class
12303 *
12304 */
12305
12306 /* Create and fill the metatable. */
12307 lua_newtable(L);
12308 /* Register */
12309 hlua_class_function(L, "set", hlua_ckch_set);
12310 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12311
12312 /*
12313 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012314 * Register class Channel
12315 *
12316 */
12317
12318 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012319 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012320
Ilya Shipitsind4259502020-04-08 01:07:56 +050012321 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012322 lua_pushstring(L, "__index");
12323 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012324
12325 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012326 hlua_class_function(L, "data", hlua_channel_get_data);
12327 hlua_class_function(L, "line", hlua_channel_get_line);
12328 hlua_class_function(L, "set", hlua_channel_set_data);
12329 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012330 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012331 hlua_class_function(L, "prepend", hlua_channel_prepend);
12332 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012333 hlua_class_function(L, "send", hlua_channel_send);
12334 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012335 hlua_class_function(L, "input", hlua_channel_get_in_len);
12336 hlua_class_function(L, "output", hlua_channel_get_out_len);
12337 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012338 hlua_class_function(L, "is_full", hlua_channel_is_full);
12339 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012340
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012341 /* Deprecated API */
12342 hlua_class_function(L, "get", hlua_channel_get);
12343 hlua_class_function(L, "dup", hlua_channel_dup);
12344 hlua_class_function(L, "getline", hlua_channel_getline);
12345 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12346 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12347
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012348 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012349
12350 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012351 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012352
12353 /*
12354 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012355 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012356 *
12357 */
12358
12359 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012360 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012361
Ilya Shipitsind4259502020-04-08 01:07:56 +050012362 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012363 lua_pushstring(L, "__index");
12364 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012365
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012366 /* Browse existing fetches and create the associated
12367 * object method.
12368 */
12369 sf = NULL;
12370 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012371 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12372 * by an underscore.
12373 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012374 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012375 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012376 if (*p == '.' || *p == '-' || *p == '+')
12377 *p = '_';
12378
12379 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012380 lua_pushstring(L, trash.area);
12381 lua_pushlightuserdata(L, sf);
12382 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12383 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012384 }
12385
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012386 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012387
12388 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012389 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012390
12391 /*
12392 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012393 * Register class Converters
12394 *
12395 */
12396
12397 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012398 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012399
12400 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012401 lua_pushstring(L, "__index");
12402 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012403
12404 /* Browse existing converters and create the associated
12405 * object method.
12406 */
12407 sc = NULL;
12408 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012409 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12410 * by an underscore.
12411 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012412 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012413 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012414 if (*p == '.' || *p == '-' || *p == '+')
12415 *p = '_';
12416
12417 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012418 lua_pushstring(L, trash.area);
12419 lua_pushlightuserdata(L, sc);
12420 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12421 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012422 }
12423
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012424 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012425
12426 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012427 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012428
12429 /*
12430 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012431 * Register class HTTP
12432 *
12433 */
12434
12435 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012436 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012437
Ilya Shipitsind4259502020-04-08 01:07:56 +050012438 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012439 lua_pushstring(L, "__index");
12440 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012441
12442 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012443 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12444 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12445 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12446 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12447 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12448 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12449 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12450 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12451 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12452 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012453
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012454 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12455 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12456 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12457 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12458 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12459 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12460 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012461
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012462 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012463
12464 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012465 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012466
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012467 /*
12468 *
12469 * Register class HTTPMessage
12470 *
12471 */
12472
12473 /* Create and fill the metatable. */
12474 lua_newtable(L);
12475
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012476 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012477 lua_pushstring(L, "__index");
12478 lua_newtable(L);
12479
12480 /* Register Lua functions. */
12481 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12482 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12483 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12484 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12485 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12486 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12487 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12488 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12489 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12490 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12491 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12492 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12493 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12494 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12495 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12496 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12497 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12498 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12499
12500 hlua_class_function(L, "body", hlua_http_msg_get_body);
12501 hlua_class_function(L, "set", hlua_http_msg_set_data);
12502 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12503 hlua_class_function(L, "append", hlua_http_msg_append);
12504 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12505 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12506 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12507 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12508
12509 hlua_class_function(L, "send", hlua_http_msg_send);
12510 hlua_class_function(L, "forward", hlua_http_msg_forward);
12511
12512 lua_rawset(L, -3);
12513
12514 /* Register previous table in the registry with reference and named entry. */
12515 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012516
12517 /*
12518 *
12519 * Register class HTTPClient
12520 *
12521 */
12522
12523 /* Create and fill the metatable. */
12524 lua_newtable(L);
12525 lua_pushstring(L, "__index");
12526 lua_newtable(L);
12527 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012528 hlua_class_function(L, "head", hlua_httpclient_head);
12529 hlua_class_function(L, "put", hlua_httpclient_put);
12530 hlua_class_function(L, "post", hlua_httpclient_post);
12531 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012532 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012533 /* Register the garbage collector entry. */
12534 lua_pushstring(L, "__gc");
12535 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12536 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12537
William Lallemand3956c4e2021-09-21 16:25:15 +020012538
12539
12540 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012541 /*
12542 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012543 * Register class AppletTCP
12544 *
12545 */
12546
12547 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012548 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012549
Ilya Shipitsind4259502020-04-08 01:07:56 +050012550 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012551 lua_pushstring(L, "__index");
12552 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012553
12554 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012555 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12556 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12557 hlua_class_function(L, "send", hlua_applet_tcp_send);
12558 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12559 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12560 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12561 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12562 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012563
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012564 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012565
12566 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012567 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012568
12569 /*
12570 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012571 * Register class AppletHTTP
12572 *
12573 */
12574
12575 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012576 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012577
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 FOURNIERa30b5db2015-09-18 09:04:27 +020012581
12582 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012583 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12584 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12585 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12586 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12587 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12588 hlua_class_function(L, "getline", hlua_applet_http_getline);
12589 hlua_class_function(L, "receive", hlua_applet_http_recv);
12590 hlua_class_function(L, "send", hlua_applet_http_send);
12591 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12592 hlua_class_function(L, "set_status", hlua_applet_http_status);
12593 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012594
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012595 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012596
12597 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012598 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012599
12600 /*
12601 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012602 * Register class TXN
12603 *
12604 */
12605
12606 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012607 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012608
Ilya Shipitsind4259502020-04-08 01:07:56 +050012609 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012610 lua_pushstring(L, "__index");
12611 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012612
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012613 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012614 hlua_class_function(L, "set_priv", hlua_set_priv);
12615 hlua_class_function(L, "get_priv", hlua_get_priv);
12616 hlua_class_function(L, "set_var", hlua_set_var);
12617 hlua_class_function(L, "unset_var", hlua_unset_var);
12618 hlua_class_function(L, "get_var", hlua_get_var);
12619 hlua_class_function(L, "done", hlua_txn_done);
12620 hlua_class_function(L, "reply", hlua_txn_reply_new);
12621 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12622 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12623 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12624 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12625 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12626 hlua_class_function(L, "deflog", hlua_txn_deflog);
12627 hlua_class_function(L, "log", hlua_txn_log);
12628 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12629 hlua_class_function(L, "Info", hlua_txn_log_info);
12630 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12631 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012632
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012633 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012634
12635 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012636 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012637
12638 /*
12639 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012640 * Register class reply
12641 *
12642 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012643 lua_newtable(L);
12644 lua_pushstring(L, "__index");
12645 lua_newtable(L);
12646 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12647 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12648 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12649 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12650 lua_settable(L, -3); /* Sets the __index entry. */
12651 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012652
12653
12654 /*
12655 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012656 * Register class Socket
12657 *
12658 */
12659
12660 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012661 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012662
Ilya Shipitsind4259502020-04-08 01:07:56 +050012663 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012664 lua_pushstring(L, "__index");
12665 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012666
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012667#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012668 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012669#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012670 hlua_class_function(L, "connect", hlua_socket_connect);
12671 hlua_class_function(L, "send", hlua_socket_send);
12672 hlua_class_function(L, "receive", hlua_socket_receive);
12673 hlua_class_function(L, "close", hlua_socket_close);
12674 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12675 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12676 hlua_class_function(L, "setoption", hlua_socket_setoption);
12677 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012678
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012679 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012680
12681 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012682 lua_pushstring(L, "__gc");
12683 lua_pushcclosure(L, hlua_socket_gc, 0);
12684 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012685
12686 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012687 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012688
Thierry Fournieraafc7772020-12-04 11:47:47 +010012689 lua_atpanic(L, hlua_panic_safe);
12690
12691 return L;
12692}
12693
12694void hlua_init(void) {
12695 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012696 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012697#ifdef USE_OPENSSL
12698 struct srv_kw *kw;
12699 int tmp_error;
12700 char *error;
12701 char *args[] = { /* SSL client configuration. */
12702 "ssl",
12703 "verify",
12704 "none",
12705 NULL
12706 };
12707#endif
12708
12709 /* Init post init function list head */
12710 for (i = 0; i < MAX_THREADS + 1; i++)
12711 LIST_INIT(&hlua_init_functions[i]);
12712
12713 /* Init state for common/shared lua parts */
12714 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012715 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012716 hlua_states[0] = hlua_init_state(0);
12717
12718 /* Init state 1 for thread 0. We have at least one thread. */
12719 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012720 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012721 hlua_states[1] = hlua_init_state(1);
12722
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012723 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012724 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012725 if (!socket_proxy) {
12726 fprintf(stderr, "Lua init: %s\n", errmsg);
12727 exit(1);
12728 }
12729 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012730
12731 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012732 socket_tcp = new_server(socket_proxy);
12733 if (!socket_tcp) {
12734 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12735 exit(1);
12736 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012737
12738#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012739 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012740 socket_ssl = new_server(socket_proxy);
12741 if (!socket_ssl) {
12742 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12743 exit(1);
12744 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012745
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012746 socket_ssl->use_ssl = 1;
12747 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012748
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012749 for (i = 0; args[i] != NULL; i++) {
12750 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012751 /*
12752 *
12753 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012754 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012755 * features like client certificates and ssl_verify.
12756 *
12757 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012758 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012759 if (tmp_error != 0) {
12760 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12761 abort(); /* This must be never arrives because the command line
12762 not editable by the user. */
12763 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012764 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012765 }
12766 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012767#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012768
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012769}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012770
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012771static void hlua_deinit()
12772{
Willy Tarreau186f3762020-12-04 11:48:12 +010012773 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012774 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12775
12776 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12777 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012778
12779 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12780 if (hlua_states[thr])
12781 lua_close(hlua_states[thr]);
12782 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012783
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012784 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012785
Willy Tarreau0f143af2021-03-05 10:41:48 +010012786#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012787 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012788#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012789
12790 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012791}
12792
12793REGISTER_POST_DEINIT(hlua_deinit);
12794
Willy Tarreau80713382018-11-26 10:19:54 +010012795static void hlua_register_build_options(void)
12796{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012797 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012798
Willy Tarreaubb57d942016-12-21 19:04:56 +010012799 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12800 hap_register_build_opts(ptr, 1);
12801}
Willy Tarreau80713382018-11-26 10:19:54 +010012802
12803INITCALL0(STG_REGISTER, hlua_register_build_options);