blob: f567c8d5b4fc28eaf351fb54361b792a957b3c31 [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 */
478__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
479{
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 */
493__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
494{
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);
8722 hlua->nargs = 0;
8723
8724 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008725 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008726
8727 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008728
8729 alloc_error:
8730 task_destroy(task);
8731 hlua_ctx_destroy(hlua);
8732 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8733 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008734}
8735
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008736/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8737 * doesn't allow "yield" functions because the HAProxy engine cannot
8738 * resume converters.
8739 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008740static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008741{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008742 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008743 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008744 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008745
Willy Tarreaube508f12016-03-10 11:47:01 +01008746 if (!stream)
8747 return 0;
8748
Willy Tarreau87b09662015-04-03 00:22:06 +02008749 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008750 * Lua context can be not initialized. This behavior
8751 * permits to save performances because a systematic
8752 * Lua initialization cause 5% performances loss.
8753 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008754 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008755 struct hlua *hlua;
8756
8757 hlua = pool_alloc(pool_head_hlua);
8758 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008759 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8760 return 0;
8761 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008762 HLUA_INIT(hlua);
8763 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008764 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008765 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8766 return 0;
8767 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008768 }
8769
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008770 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008771 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008772
8773 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008774 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008775 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8776 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008777 else
8778 error = "critical error";
8779 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008780 return 0;
8781 }
8782
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008783 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008784 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008785 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008786 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008787 return 0;
8788 }
8789
8790 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008791 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008792
8793 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008794 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008795 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008796 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008797 return 0;
8798 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008799 hlua_smp2lua(stream->hlua->T, smp);
8800 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008801
8802 /* push keywords in the stack. */
8803 if (arg_p) {
8804 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008805 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008806 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008807 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008808 return 0;
8809 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008810 hlua_arg2lua(stream->hlua->T, arg_p);
8811 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008812 }
8813 }
8814
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008815 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008816 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008817
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008818 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008819 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008820 }
8821
8822 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008823 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008824 /* finished. */
8825 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008826 /* If the stack is empty, the function fails. */
8827 if (lua_gettop(stream->hlua->T) <= 0)
8828 return 0;
8829
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008830 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008831 hlua_lua2smp(stream->hlua->T, -1, smp);
8832 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008833 return 1;
8834
8835 /* yield. */
8836 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008837 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008838 return 0;
8839
8840 /* finished with error. */
8841 case HLUA_E_ERRMSG:
8842 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008843 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008844 fcn->name, lua_tostring(stream->hlua->T, -1));
8845 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008846 return 0;
8847
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008848 case HLUA_E_ETMOUT:
8849 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8850 return 0;
8851
8852 case HLUA_E_NOMEM:
8853 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8854 return 0;
8855
8856 case HLUA_E_YIELD:
8857 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8858 return 0;
8859
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008860 case HLUA_E_ERR:
8861 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008862 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01008863 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008864
8865 default:
8866 return 0;
8867 }
8868}
8869
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008870/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8871 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008872 * resume sample-fetches. This function will be called by the sample
8873 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008874 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008875static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8876 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008877{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008878 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008879 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008880 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008881 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008882
Willy Tarreaube508f12016-03-10 11:47:01 +01008883 if (!stream)
8884 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008885
Willy Tarreau87b09662015-04-03 00:22:06 +02008886 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008887 * Lua context can be not initialized. This behavior
8888 * permits to save performances because a systematic
8889 * Lua initialization cause 5% performances loss.
8890 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008891 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008892 struct hlua *hlua;
8893
8894 hlua = pool_alloc(pool_head_hlua);
8895 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008896 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8897 return 0;
8898 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008899 hlua->T = NULL;
8900 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008901 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008902 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8903 return 0;
8904 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008905 }
8906
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008907 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008908 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008909
8910 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008911 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008912 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8913 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008914 else
8915 error = "critical error";
8916 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008917 return 0;
8918 }
8919
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008920 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008921 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008922 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008923 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008924 return 0;
8925 }
8926
8927 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008928 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008929
8930 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008931 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008932 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008933 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008934 return 0;
8935 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008936 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008937
8938 /* push keywords in the stack. */
8939 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8940 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008941 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008942 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008943 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008944 return 0;
8945 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008946 hlua_arg2lua(stream->hlua->T, arg_p);
8947 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008948 }
8949
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008950 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008951 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008952
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008953 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008954 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008955 }
8956
8957 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008958 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008959 /* finished. */
8960 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008961 /* If the stack is empty, the function fails. */
8962 if (lua_gettop(stream->hlua->T) <= 0)
8963 return 0;
8964
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008965 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008966 hlua_lua2smp(stream->hlua->T, -1, smp);
8967 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008968
8969 /* Set the end of execution flag. */
8970 smp->flags &= ~SMP_F_MAY_CHANGE;
8971 return 1;
8972
8973 /* yield. */
8974 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008975 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008976 return 0;
8977
8978 /* finished with error. */
8979 case HLUA_E_ERRMSG:
8980 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008981 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008982 fcn->name, lua_tostring(stream->hlua->T, -1));
8983 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008984 return 0;
8985
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008986 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008987 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8988 return 0;
8989
8990 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008991 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8992 return 0;
8993
8994 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008995 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8996 return 0;
8997
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008998 case HLUA_E_ERR:
8999 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009000 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009001 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009002
9003 default:
9004 return 0;
9005 }
9006}
9007
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009008/* This function is an LUA binding used for registering
9009 * "sample-conv" functions. It expects a converter name used
9010 * in the haproxy configuration file, and an LUA function.
9011 */
9012__LJMP static int hlua_register_converters(lua_State *L)
9013{
9014 struct sample_conv_kw_list *sck;
9015 const char *name;
9016 int ref;
9017 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009018 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009019 struct sample_conv *sc;
9020 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009021
9022 MAY_LJMP(check_args(L, 2, "register_converters"));
9023
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009024 if (hlua_gethlua(L)) {
9025 /* runtime processing */
9026 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9027 }
9028
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009029 /* First argument : converter name. */
9030 name = MAY_LJMP(luaL_checkstring(L, 1));
9031
9032 /* Second argument : lua function. */
9033 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9034
Thierry Fournierf67442e2020-11-28 20:41:07 +01009035 /* Check if the converter is already registered */
9036 trash = get_trash_chunk();
9037 chunk_printf(trash, "lua.%s", name);
9038 sc = find_sample_conv(trash->area, trash->data);
9039 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009040 fcn = sc->private;
9041 if (fcn->function_ref[hlua_state_id] != -1) {
9042 ha_warning("Trying to register converter 'lua.%s' more than once. "
9043 "This will become a hard error in version 2.5.\n", name);
9044 }
9045 fcn->function_ref[hlua_state_id] = ref;
9046 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009047 }
9048
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009049 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009050 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009051 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02009052 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009053 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009054 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02009055 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009056
9057 /* Fill fcn. */
9058 fcn->name = strdup(name);
9059 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02009060 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009061 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009062
9063 /* List head */
9064 sck->list.n = sck->list.p = NULL;
9065
9066 /* converter keyword. */
9067 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009068 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009069 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02009070 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009071
9072 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
9073 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009074 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 +01009075 sck->kw[0].val_args = NULL;
9076 sck->kw[0].in_type = SMP_T_STR;
9077 sck->kw[0].out_type = SMP_T_STR;
9078 sck->kw[0].private = fcn;
9079
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009080 /* Register this new converter */
9081 sample_register_convs(sck);
9082
9083 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02009084
9085 alloc_error:
9086 release_hlua_function(fcn);
9087 ha_free(&sck);
9088 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9089 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009090}
9091
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009092/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009093 * "sample-fetch" functions. It expects a converter name used
9094 * in the haproxy configuration file, and an LUA function.
9095 */
9096__LJMP static int hlua_register_fetches(lua_State *L)
9097{
9098 const char *name;
9099 int ref;
9100 int len;
9101 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02009102 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009103 struct sample_fetch *sf;
9104 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009105
9106 MAY_LJMP(check_args(L, 2, "register_fetches"));
9107
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009108 if (hlua_gethlua(L)) {
9109 /* runtime processing */
9110 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
9111 }
9112
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009113 /* First argument : sample-fetch name. */
9114 name = MAY_LJMP(luaL_checkstring(L, 1));
9115
9116 /* Second argument : lua function. */
9117 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9118
Thierry Fournierf67442e2020-11-28 20:41:07 +01009119 /* Check if the sample-fetch is already registered */
9120 trash = get_trash_chunk();
9121 chunk_printf(trash, "lua.%s", name);
9122 sf = find_sample_fetch(trash->area, trash->data);
9123 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009124 fcn = sf->private;
9125 if (fcn->function_ref[hlua_state_id] != -1) {
9126 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
9127 "This will become a hard error in version 2.5.\n", name);
9128 }
9129 fcn->function_ref[hlua_state_id] = ref;
9130 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009131 }
9132
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009133 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009134 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009135 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02009136 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009137 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009138 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02009139 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009140
9141 /* Fill fcn. */
9142 fcn->name = strdup(name);
9143 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02009144 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009145 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009146
9147 /* List head */
9148 sfk->list.n = sfk->list.p = NULL;
9149
9150 /* sample-fetch keyword. */
9151 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009152 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009153 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02009154 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009155
9156 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
9157 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01009158 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 +01009159 sfk->kw[0].val_args = NULL;
9160 sfk->kw[0].out_type = SMP_T_STR;
9161 sfk->kw[0].use = SMP_USE_HTTP_ANY;
9162 sfk->kw[0].val = 0;
9163 sfk->kw[0].private = fcn;
9164
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009165 /* Register this new fetch. */
9166 sample_register_fetches(sfk);
9167
9168 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009169
9170 alloc_error:
9171 release_hlua_function(fcn);
9172 ha_free(&sfk);
9173 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9174 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009175}
9176
Christopher Faulet501465d2020-02-26 14:54:16 +01009177/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009178 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009179__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009180{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009181 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009182 unsigned int delay;
9183 unsigned int wakeup_ms;
9184
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009185 /* Get hlua struct, or NULL if we execute from main lua state */
9186 hlua = hlua_gethlua(L);
9187 if (!hlua) {
9188 return 0;
9189 }
9190
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009191 MAY_LJMP(check_args(L, 1, "wake_time"));
9192
9193 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9194 wakeup_ms = tick_add(now_ms, delay);
9195 hlua->wake_time = wakeup_ms;
9196 return 0;
9197}
9198
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009199/* This function is a wrapper to execute each LUA function declared as an action
9200 * wrapper during the initialisation period. This function may return any
9201 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9202 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9203 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009204 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009205static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009206 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009207{
9208 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009209 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009210 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009211 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009212
9213 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009214 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9215 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9216 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9217 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009218 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009219 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009220 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009221 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009222
Willy Tarreau87b09662015-04-03 00:22:06 +02009223 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009224 * Lua context can be not initialized. This behavior
9225 * permits to save performances because a systematic
9226 * Lua initialization cause 5% performances loss.
9227 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009228 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009229 struct hlua *hlua;
9230
9231 hlua = pool_alloc(pool_head_hlua);
9232 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009233 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009234 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009235 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009236 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009237 HLUA_INIT(hlua);
9238 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009239 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 +01009240 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009241 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009242 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009243 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009244 }
9245
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009246 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009247 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009248
9249 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009250 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009251 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9252 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009253 else
9254 error = "critical error";
9255 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009256 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009257 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009258 }
9259
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009260 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009261 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009262 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009263 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009264 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009265 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009266 }
9267
9268 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009269 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 +01009270
Willy Tarreau87b09662015-04-03 00:22:06 +02009271 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009272 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009273 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009274 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009275 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009276 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009277 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009278 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009279
9280 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009281 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009282 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009283 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009284 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009285 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009286 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009287 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009288 lua_pushstring(s->hlua->T, *arg);
9289 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009290 }
9291
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009292 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009293 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009294
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009295 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009296 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009297 }
9298
9299 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009300 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009301 /* finished. */
9302 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009303 /* Catch the return value */
9304 if (lua_gettop(s->hlua->T) > 0)
9305 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009306
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009307 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009308 if (act_ret == ACT_RET_YIELD) {
9309 if (flags & ACT_OPT_FINAL)
9310 goto err_yield;
9311
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009312 if (dir == SMP_OPT_DIR_REQ)
9313 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9314 s->hlua->wake_time);
9315 else
9316 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9317 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009318 }
9319 goto end;
9320
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009321 /* yield. */
9322 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009323 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009324 if (dir == SMP_OPT_DIR_REQ)
9325 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9326 s->hlua->wake_time);
9327 else
9328 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9329 s->hlua->wake_time);
9330
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009331 /* Some actions can be wake up when a "write" event
9332 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009333 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009334 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009335 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009336 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009337 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009338 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009339 act_ret = ACT_RET_YIELD;
9340 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009341
9342 /* finished with error. */
9343 case HLUA_E_ERRMSG:
9344 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009345 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009346 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009347 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009348 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009349
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009350 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009351 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009352 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009353
9354 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009355 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009356 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009357
9358 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009359 err_yield:
9360 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009361 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009362 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009363 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009364
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009365 case HLUA_E_ERR:
9366 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009367 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009368 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009369
9370 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009371 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009372 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009373
9374 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009375 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009376 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009377 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009378}
9379
Willy Tarreau144f84a2021-03-02 16:09:26 +01009380struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009381{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009382 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009383
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009384 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009385 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009386 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387}
9388
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009389static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009390{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009391 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009392 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009393 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009394 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009395 struct task *task;
9396 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009397 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009398
Willy Tarreaubafbe012017-11-24 17:34:44 +01009399 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009400 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009401 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009402 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009403 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009404 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009405 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009406 tcp_ctx->hlua = hlua;
9407 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009408
9409 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009410 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009411 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009412 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009413 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009414 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009415 }
9416 task->nice = 0;
9417 task->context = ctx;
9418 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009419 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009420
9421 /* In the execution wrappers linked with a stream, the
9422 * Lua context can be not initialized. This behavior
9423 * permits to save performances because a systematic
9424 * Lua initialization cause 5% performances loss.
9425 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009426 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 +01009427 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009428 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009429 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009430 }
9431
9432 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009433 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009434
9435 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009436 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009437 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9438 error = lua_tostring(hlua->T, -1);
9439 else
9440 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009441 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009442 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009443 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009444 }
9445
9446 /* Check stack available size. */
9447 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009448 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009449 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009450 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009451 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009452 }
9453
9454 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009455 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009456
9457 /* Create and and push object stream in the stack. */
9458 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009459 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009460 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009461 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009462 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009463 }
9464 hlua->nargs = 1;
9465
9466 /* push keywords in the stack. */
9467 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9468 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009469 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009470 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009471 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009472 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009473 }
9474 lua_pushstring(hlua->T, *arg);
9475 hlua->nargs++;
9476 }
9477
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009478 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009479
9480 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009481 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02009482 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009483
Christopher Fauletc9929382022-05-12 11:52:27 +02009484 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009485}
9486
Willy Tarreau60409db2019-08-21 14:14:50 +02009487void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009488{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009489 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009490 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009491 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009492 struct act_rule *rule = ctx->rule;
9493 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009494 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009495
Christopher Faulet31572222023-03-31 11:13:48 +02009496 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9497 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009498
Christopher Faulet31572222023-03-31 11:13:48 +02009499 /* The applet execution is already done. */
9500 if (tcp_ctx->flags & APPLET_DONE)
9501 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009502
9503 /* Execute the function. */
9504 switch (hlua_ctx_resume(hlua, 1)) {
9505 /* finished. */
9506 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009507 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009508 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
9509 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009510
9511 /* yield. */
9512 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009513 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009514 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +02009515 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009516
9517 /* finished with error. */
9518 case HLUA_E_ERRMSG:
9519 /* Display log. */
9520 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009521 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009522 lua_pop(hlua->T, 1);
9523 goto error;
9524
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009525 case HLUA_E_ETMOUT:
9526 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009527 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009528 goto error;
9529
9530 case HLUA_E_NOMEM:
9531 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009532 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009533 goto error;
9534
9535 case HLUA_E_YIELD: /* unexpected */
9536 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009537 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009538 goto error;
9539
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009540 case HLUA_E_ERR:
9541 /* Display log. */
9542 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009543 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009544 goto error;
9545
9546 default:
9547 goto error;
9548 }
9549
Christopher Faulet31572222023-03-31 11:13:48 +02009550out:
9551 /* eat the whole request */
9552 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
9553 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009554
Christopher Faulet31572222023-03-31 11:13:48 +02009555error:
9556 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009557 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009558 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009559}
9560
9561static void hlua_applet_tcp_release(struct appctx *ctx)
9562{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009563 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9564
9565 task_destroy(tcp_ctx->task);
9566 tcp_ctx->task = NULL;
9567 hlua_ctx_destroy(tcp_ctx->hlua);
9568 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009569}
9570
Christopher Fauletc9929382022-05-12 11:52:27 +02009571/* The function returns 0 if the initialisation is complete or -1 if
9572 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009573 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009574static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009575{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009576 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +02009577 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009578 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009579 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009580 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009581 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009582 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009583 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009584
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009585 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009586 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009587 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009588 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009589 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009590 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009591 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009592 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009593 http_ctx->hlua = hlua;
9594 http_ctx->left_bytes = -1;
9595 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009596
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009597 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009598 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009599
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009600 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009601 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009602 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009603 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009604 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009605 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009606 }
9607 task->nice = 0;
9608 task->context = ctx;
9609 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009610 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009611
9612 /* In the execution wrappers linked with a stream, the
9613 * Lua context can be not initialized. This behavior
9614 * permits to save performances because a systematic
9615 * Lua initialization cause 5% performances loss.
9616 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009617 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 +01009618 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009619 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +02009620 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009621 }
9622
9623 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009624 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009625
9626 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009627 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009628 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9629 error = lua_tostring(hlua->T, -1);
9630 else
9631 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009632 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009633 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +02009634 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009635 }
9636
9637 /* Check stack available size. */
9638 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009639 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009640 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009641 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009642 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009643 }
9644
9645 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009646 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009647
9648 /* Create and and push object stream in the stack. */
9649 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009650 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009651 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009652 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009653 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009654 }
9655 hlua->nargs = 1;
9656
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009657 /* push keywords in the stack. */
9658 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9659 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009660 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009661 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009662 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +02009663 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009664 }
9665 lua_pushstring(hlua->T, *arg);
9666 hlua->nargs++;
9667 }
9668
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009669 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009670
9671 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +02009672 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009673
Christopher Fauletc9929382022-05-12 11:52:27 +02009674 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009675}
9676
Willy Tarreau60409db2019-08-21 14:14:50 +02009677void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009678{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009679 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02009680 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02009681 struct stream *strm = __sc_strm(sc);
9682 struct channel *req = sc_oc(sc);
9683 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009684 struct act_rule *rule = ctx->rule;
9685 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009686 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009687 struct htx *req_htx, *res_htx;
9688
9689 res_htx = htx_from_buf(&res->buf);
9690
Christopher Faulet31572222023-03-31 11:13:48 +02009691 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
9692 goto out;
9693
9694 /* The applet execution is already done. */
9695 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009696 goto out;
9697
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009698 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009699 if (!b_size(&res->buf)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009700 sc_need_room(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009701 goto out;
9702 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009703
9704 /* Set the currently running flag. */
9705 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009706 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009707 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02009708 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009709 goto out;
9710 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009711 }
9712
Christopher Faulet31572222023-03-31 11:13:48 +02009713 /* Execute the function. */
9714 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009715 /* finished. */
9716 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009717 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009718 break;
9719
9720 /* yield. */
9721 case HLUA_E_AGAIN:
9722 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009723 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009724 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009725
9726 /* finished with error. */
9727 case HLUA_E_ERRMSG:
9728 /* Display log. */
9729 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009730 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009731 lua_pop(hlua->T, 1);
9732 goto error;
9733
9734 case HLUA_E_ETMOUT:
9735 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009736 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009737 goto error;
9738
9739 case HLUA_E_NOMEM:
9740 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009741 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009742 goto error;
9743
9744 case HLUA_E_YIELD: /* unexpected */
9745 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009746 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009747 goto error;
9748
9749 case HLUA_E_ERR:
9750 /* Display log. */
9751 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +02009752 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009753 goto error;
9754
9755 default:
9756 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009757 }
9758
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009759 if (http_ctx->flags & APPLET_DONE) {
9760 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +02009761 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009762
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009763 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009764 goto error;
9765
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009766 /* no more data are expected. If the response buffer is empty
9767 * for a chunked message, be sure to add something (EOT block in
9768 * this case) to have something to send. It is important to be
9769 * sure the EOM flags will be handled by the endpoint.
9770 */
9771 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9772 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02009773 sc_need_room(sc);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009774 goto out;
9775 }
9776 channel_add_input(res, 1);
9777 }
9778
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009779 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +02009780 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009781 strm->txn->status = http_ctx->status;
9782 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009783 }
9784
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009785 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009786 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +02009787 /* eat the whole request */
9788 if (co_data(req)) {
9789 req_htx = htx_from_buf(&req->buf);
9790 co_htx_skip(req, req_htx, co_data(req));
9791 htx_to_buf(req_htx, &req->buf);
9792 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009793 return;
9794
9795 error:
9796
9797 /* If we are in HTTP mode, and we are not send any
9798 * data, return a 500 server error in best effort:
9799 * if there is no room available in the buffer,
9800 * just close the connection.
9801 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009802 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009803 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009804
9805 channel_erase(res);
9806 res->buf.data = b_data(err);
9807 memcpy(res->buf.area, b_head(err), b_data(err));
9808 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009809 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +02009810 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009811 }
Christopher Faulet31572222023-03-31 11:13:48 +02009812 else
9813 se_fl_set(ctx->sedesc, SE_FL_ERROR);
9814
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009815 if (!(strm->flags & SF_ERR_MASK))
9816 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009817 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +02009818 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009819}
9820
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009821static void hlua_applet_http_release(struct appctx *ctx)
9822{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009823 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9824
9825 task_destroy(http_ctx->task);
9826 http_ctx->task = NULL;
9827 hlua_ctx_destroy(http_ctx->hlua);
9828 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009829}
9830
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009831/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009832 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009833 *
9834 * This function can fail with an abort() due to an Lua critical error.
9835 * We are in the configuration parsing process of HAProxy, this abort() is
9836 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009837 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009838static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9839 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009840{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009841 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009842 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009843
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009844 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009845 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009846 if (!rule->arg.hlua_rule) {
9847 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009848 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009849 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009850
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009851 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009852 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9853 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009854 if (!rule->arg.hlua_rule->args) {
9855 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009856 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009857 }
9858
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009859 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009860 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009861
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009862 /* Expect some arguments */
9863 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009864 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009865 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009866 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009867 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009868 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009869 if (!rule->arg.hlua_rule->args[i]) {
9870 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009871 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009872 }
9873 (*cur_arg)++;
9874 }
9875 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009876
Thierry FOURNIER42148732015-09-02 17:17:33 +02009877 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009878 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009879 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009880
9881 error:
9882 if (rule->arg.hlua_rule) {
9883 if (rule->arg.hlua_rule->args) {
9884 for (i = 0; i < fcn->nargs; i++)
9885 ha_free(&rule->arg.hlua_rule->args[i]);
9886 ha_free(&rule->arg.hlua_rule->args);
9887 }
9888 ha_free(&rule->arg.hlua_rule);
9889 }
9890 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009891}
9892
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009893static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9894 struct act_rule *rule, char **err)
9895{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009896 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009897
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009898 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009899 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009900 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009901 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009902 * the call of this analyzer.
9903 */
9904 if (rule->from != ACT_F_HTTP_REQ) {
9905 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9906 return ACT_RET_PRS_ERR;
9907 }
9908
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009909 /* Memory for the rule. */
9910 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9911 if (!rule->arg.hlua_rule) {
9912 memprintf(err, "out of memory error");
9913 return ACT_RET_PRS_ERR;
9914 }
9915
9916 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009917 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009918
9919 /* TODO: later accept arguments. */
9920 rule->arg.hlua_rule->args = NULL;
9921
9922 /* Add applet pointer in the rule. */
9923 rule->applet.obj_type = OBJ_TYPE_APPLET;
9924 rule->applet.name = fcn->name;
9925 rule->applet.init = hlua_applet_http_init;
9926 rule->applet.fct = hlua_applet_http_fct;
9927 rule->applet.release = hlua_applet_http_release;
9928 rule->applet.timeout = hlua_timeout_applet;
9929
9930 return ACT_RET_PRS_OK;
9931}
9932
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009933/* This function is an LUA binding used for registering
9934 * "sample-conv" functions. It expects a converter name used
9935 * in the haproxy configuration file, and an LUA function.
9936 */
9937__LJMP static int hlua_register_action(lua_State *L)
9938{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009939 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009940 const char *name;
9941 int ref;
9942 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009943 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009944 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009945 struct buffer *trash;
9946 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009947
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009948 /* Initialise the number of expected arguments at 0. */
9949 nargs = 0;
9950
9951 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9952 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009953
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009954 if (hlua_gethlua(L)) {
9955 /* runtime processing */
9956 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
9957 }
9958
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009959 /* First argument : converter name. */
9960 name = MAY_LJMP(luaL_checkstring(L, 1));
9961
9962 /* Second argument : environment. */
9963 if (lua_type(L, 2) != LUA_TTABLE)
9964 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9965
9966 /* Third argument : lua function. */
9967 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9968
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009969 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009970 if (lua_gettop(L) >= 4)
9971 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9972
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009973 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009974 lua_pushnil(L);
9975 while (lua_next(L, 2) != 0) {
9976 if (lua_type(L, -1) != LUA_TSTRING)
9977 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9978
Thierry Fournierf67442e2020-11-28 20:41:07 +01009979 /* Check if action exists */
9980 trash = get_trash_chunk();
9981 chunk_printf(trash, "lua.%s", name);
9982 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9983 akw = tcp_req_cont_action(trash->area);
9984 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9985 akw = tcp_res_cont_action(trash->area);
9986 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9987 akw = action_http_req_custom(trash->area);
9988 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9989 akw = action_http_res_custom(trash->area);
9990 } else {
9991 akw = NULL;
9992 }
9993 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009994 fcn = akw->private;
9995 if (fcn->function_ref[hlua_state_id] != -1) {
9996 ha_warning("Trying to register action 'lua.%s' more than once. "
9997 "This will become a hard error in version 2.5.\n", name);
9998 }
9999 fcn->function_ref[hlua_state_id] = ref;
10000
10001 /* pop the environment string. */
10002 lua_pop(L, 1);
10003 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010004 }
10005
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010006 /* Check required environment. Only accepted "http" or "tcp". */
10007 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010008 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010009 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010010 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010011 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010012 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010013 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010014
10015 /* Fill fcn. */
10016 fcn->name = strdup(name);
10017 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010018 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010019 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010020
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010021 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010022 fcn->nargs = nargs;
10023
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010024 /* List head */
10025 akl->list.n = akl->list.p = NULL;
10026
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010027 /* action keyword. */
10028 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010029 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010030 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010031 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010032
10033 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10034
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010035 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010036 akl->kw[0].private = fcn;
10037 akl->kw[0].parse = action_register_lua;
10038
10039 /* select the action registering point. */
10040 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
10041 tcp_req_cont_keywords_register(akl);
10042 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
10043 tcp_res_cont_keywords_register(akl);
10044 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
10045 http_req_keywords_register(akl);
10046 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
10047 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010048 else {
10049 release_hlua_function(fcn);
10050 if (akl)
10051 ha_free((char **)&(akl->kw[0].kw));
10052 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010053 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010054 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
10055 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010056 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010057
10058 /* pop the environment string. */
10059 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010060
10061 /* reset for next loop */
10062 akl = NULL;
10063 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010064 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010065 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010066
10067 alloc_error:
10068 release_hlua_function(fcn);
10069 ha_free(&akl);
10070 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10071 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010072}
10073
10074static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
10075 struct act_rule *rule, char **err)
10076{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010077 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010078
Christopher Faulet280f85b2019-07-15 15:02:04 +020010079 if (px->mode == PR_MODE_HTTP) {
10080 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010010081 return ACT_RET_PRS_ERR;
10082 }
10083
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010084 /* Memory for the rule. */
10085 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10086 if (!rule->arg.hlua_rule) {
10087 memprintf(err, "out of memory error");
10088 return ACT_RET_PRS_ERR;
10089 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010090
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010091 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010092 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010093
10094 /* TODO: later accept arguments. */
10095 rule->arg.hlua_rule->args = NULL;
10096
10097 /* Add applet pointer in the rule. */
10098 rule->applet.obj_type = OBJ_TYPE_APPLET;
10099 rule->applet.name = fcn->name;
10100 rule->applet.init = hlua_applet_tcp_init;
10101 rule->applet.fct = hlua_applet_tcp_fct;
10102 rule->applet.release = hlua_applet_tcp_release;
10103 rule->applet.timeout = hlua_timeout_applet;
10104
10105 return 0;
10106}
10107
10108/* This function is an LUA binding used for registering
10109 * "sample-conv" functions. It expects a converter name used
10110 * in the haproxy configuration file, and an LUA function.
10111 */
10112__LJMP static int hlua_register_service(lua_State *L)
10113{
10114 struct action_kw_list *akl;
10115 const char *name;
10116 const char *env;
10117 int ref;
10118 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010119 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010120 struct buffer *trash;
10121 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010122
10123 MAY_LJMP(check_args(L, 3, "register_service"));
10124
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010125 if (hlua_gethlua(L)) {
10126 /* runtime processing */
10127 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
10128 }
10129
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010130 /* First argument : converter name. */
10131 name = MAY_LJMP(luaL_checkstring(L, 1));
10132
10133 /* Second argument : environment. */
10134 env = MAY_LJMP(luaL_checkstring(L, 2));
10135
10136 /* Third argument : lua function. */
10137 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10138
Thierry Fournierf67442e2020-11-28 20:41:07 +010010139 /* Check for service already registered */
10140 trash = get_trash_chunk();
10141 chunk_printf(trash, "lua.%s", name);
10142 akw = service_find(trash->area);
10143 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010144 fcn = akw->private;
10145 if (fcn->function_ref[hlua_state_id] != -1) {
10146 ha_warning("Trying to register service 'lua.%s' more than once. "
10147 "This will become a hard error in version 2.5.\n", name);
10148 }
10149 fcn->function_ref[hlua_state_id] = ref;
10150 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010151 }
10152
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010153 /* Allocate and fill the sample fetch keyword struct. */
10154 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
10155 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010156 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010157 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010158 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010159 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010160
10161 /* Fill fcn. */
10162 len = strlen("<lua.>") + strlen(name) + 1;
10163 fcn->name = calloc(1, len);
10164 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010165 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010166 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010167 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010168
10169 /* List head */
10170 akl->list.n = akl->list.p = NULL;
10171
10172 /* converter keyword. */
10173 len = strlen("lua.") + strlen(name) + 1;
10174 akl->kw[0].kw = calloc(1, len);
10175 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010176 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010177
10178 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10179
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010180 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010181 if (strcmp(env, "tcp") == 0)
10182 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010183 else if (strcmp(env, "http") == 0)
10184 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010185 else {
10186 release_hlua_function(fcn);
10187 if (akl)
10188 ha_free((char **)&(akl->kw[0].kw));
10189 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010190 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010191 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010192 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010193
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010194 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010195 akl->kw[0].private = fcn;
10196
10197 /* End of array. */
10198 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10199
10200 /* Register this new converter */
10201 service_keywords_register(akl);
10202
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010203 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010204
10205 alloc_error:
10206 release_hlua_function(fcn);
10207 ha_free(&akl);
10208 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10209 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010210}
10211
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010212/* This function initialises Lua cli handler. It copies the
10213 * arguments in the Lua stack and create channel IO objects.
10214 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010215static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010216{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010217 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010218 struct hlua *hlua;
10219 struct hlua_function *fcn;
10220 int i;
10221 const char *error;
10222
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010223 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010224 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010225
Willy Tarreaubafbe012017-11-24 17:34:44 +010010226 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010227 if (!hlua) {
10228 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010229 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010230 }
10231 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010232 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010233
10234 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010235 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010236 * applet_http. It is absolutely compatible.
10237 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010238 ctx->task = task_new_here();
10239 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010240 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010241 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010242 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010243 ctx->task->nice = 0;
10244 ctx->task->context = appctx;
10245 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010246
10247 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010248 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010249 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010250 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010251 }
10252
10253 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010254 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010255 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10256 error = lua_tostring(hlua->T, -1);
10257 else
10258 error = "critical error";
10259 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10260 goto error;
10261 }
10262
10263 /* Check stack available size. */
10264 if (!lua_checkstack(hlua->T, 2)) {
10265 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10266 goto error;
10267 }
10268
10269 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010270 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010271
10272 /* Once the arguments parsed, the CLI is like an AppletTCP,
10273 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010274 */
10275 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10276 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10277 goto error;
10278 }
10279 hlua->nargs = 1;
10280
10281 /* push keywords in the stack. */
10282 for (i = 0; *args[i]; i++) {
10283 /* Check stack available size. */
10284 if (!lua_checkstack(hlua->T, 1)) {
10285 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10286 goto error;
10287 }
10288 lua_pushstring(hlua->T, args[i]);
10289 hlua->nargs++;
10290 }
10291
10292 /* We must initialize the execution timeouts. */
10293 hlua->max_time = hlua_timeout_session;
10294
10295 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010296 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010297
10298 /* It's ok */
10299 return 0;
10300
10301 /* It's not ok. */
10302error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010303 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010304 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010305 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010306 return 1;
10307}
10308
10309static int hlua_cli_io_handler_fct(struct appctx *appctx)
10310{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010311 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010312 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020010313 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010314 struct hlua_function *fcn;
10315
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010316 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010317 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010318 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010319
10320 /* If the stream is disconnect or closed, ldo nothing. */
Willy Tarreau475e4632022-05-27 10:26:46 +020010321 if (unlikely(sc->state == SC_ST_DIS || sc->state == SC_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010322 return 1;
10323
10324 /* Execute the function. */
10325 switch (hlua_ctx_resume(hlua, 1)) {
10326
10327 /* finished. */
10328 case HLUA_E_OK:
10329 return 1;
10330
10331 /* yield. */
10332 case HLUA_E_AGAIN:
10333 /* We want write. */
10334 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau475e4632022-05-27 10:26:46 +020010335 sc_need_room(sc);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010336 /* Set the timeout. */
10337 if (hlua->wake_time != TICK_ETERNITY)
10338 task_schedule(hlua->task, hlua->wake_time);
10339 return 0;
10340
10341 /* finished with error. */
10342 case HLUA_E_ERRMSG:
10343 /* Display log. */
10344 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10345 fcn->name, lua_tostring(hlua->T, -1));
10346 lua_pop(hlua->T, 1);
10347 return 1;
10348
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010349 case HLUA_E_ETMOUT:
10350 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10351 fcn->name);
10352 return 1;
10353
10354 case HLUA_E_NOMEM:
10355 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10356 fcn->name);
10357 return 1;
10358
10359 case HLUA_E_YIELD: /* unexpected */
10360 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10361 fcn->name);
10362 return 1;
10363
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010364 case HLUA_E_ERR:
10365 /* Display log. */
10366 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10367 fcn->name);
10368 return 1;
10369
10370 default:
10371 return 1;
10372 }
10373
10374 return 1;
10375}
10376
10377static void hlua_cli_io_release_fct(struct appctx *appctx)
10378{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010379 struct hlua_cli_ctx *ctx = appctx->svcctx;
10380
10381 hlua_ctx_destroy(ctx->hlua);
10382 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010383}
10384
10385/* This function is an LUA binding used for registering
10386 * new keywords in the cli. It expects a list of keywords
10387 * which are the "path". It is limited to 5 keywords. A
10388 * description of the command, a function to be executed
10389 * for the parsing and a function for io handlers.
10390 */
10391__LJMP static int hlua_register_cli(lua_State *L)
10392{
10393 struct cli_kw_list *cli_kws;
10394 const char *message;
10395 int ref_io;
10396 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010397 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010398 int index;
10399 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010400 struct buffer *trash;
10401 const char *kw[5];
10402 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010403 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010404
10405 MAY_LJMP(check_args(L, 3, "register_cli"));
10406
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010407 if (hlua_gethlua(L)) {
10408 /* runtime processing */
10409 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
10410 }
10411
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010412 /* First argument : an array of maximum 5 keywords. */
10413 if (!lua_istable(L, 1))
10414 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10415
10416 /* Second argument : string with contextual message. */
10417 message = MAY_LJMP(luaL_checkstring(L, 2));
10418
10419 /* Third and fourth argument : lua function. */
10420 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10421
Thierry Fournierf67442e2020-11-28 20:41:07 +010010422 /* Check for CLI service already registered */
10423 trash = get_trash_chunk();
10424 index = 0;
10425 lua_pushnil(L);
10426 memset(kw, 0, sizeof(kw));
10427 while (lua_next(L, 1) != 0) {
10428 if (index >= CLI_PREFIX_KW_NB)
10429 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10430 if (lua_type(L, -1) != LUA_TSTRING)
10431 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10432 kw[index] = lua_tostring(L, -1);
10433 if (index == 0)
10434 chunk_printf(trash, "%s", kw[index]);
10435 else
10436 chunk_appendf(trash, " %s", kw[index]);
10437 index++;
10438 lua_pop(L, 1);
10439 }
10440 cli_kw = cli_find_kw_exact((char **)kw);
10441 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010442 fcn = cli_kw->private;
10443 if (fcn->function_ref[hlua_state_id] != -1) {
10444 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10445 "This will become a hard error in version 2.5.\n", trash->area);
10446 }
10447 fcn->function_ref[hlua_state_id] = ref_io;
10448 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010449 }
10450
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010451 /* Allocate and fill the sample fetch keyword struct. */
10452 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010453 if (!cli_kws) {
10454 errmsg = "Lua out of memory error.";
10455 goto error;
10456 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010457 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010458 if (!fcn) {
10459 errmsg = "Lua out of memory error.";
10460 goto error;
10461 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010462
10463 /* Fill path. */
10464 index = 0;
10465 lua_pushnil(L);
10466 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010467 if (index >= 5) {
10468 errmsg = "1st argument must be a table with a maximum of 5 entries";
10469 goto error;
10470 }
10471 if (lua_type(L, -1) != LUA_TSTRING) {
10472 errmsg = "1st argument must be a table filled with strings";
10473 goto error;
10474 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010475 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010476 if (!cli_kws->kw[0].str_kw[index]) {
10477 errmsg = "Lua out of memory error.";
10478 goto error;
10479 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010480 index++;
10481 lua_pop(L, 1);
10482 }
10483
10484 /* Copy help message. */
10485 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010486 if (!cli_kws->kw[0].usage) {
10487 errmsg = "Lua out of memory error.";
10488 goto error;
10489 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010490
10491 /* Fill fcn io handler. */
10492 len = strlen("<lua.cli>") + 1;
10493 for (i = 0; i < index; i++)
10494 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10495 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010496 if (!fcn->name) {
10497 errmsg = "Lua out of memory error.";
10498 goto error;
10499 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010500 strncat((char *)fcn->name, "<lua.cli", len);
10501 for (i = 0; i < index; i++) {
10502 strncat((char *)fcn->name, ".", len);
10503 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10504 }
10505 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010506 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010507
10508 /* Fill last entries. */
10509 cli_kws->kw[0].private = fcn;
10510 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10511 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10512 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10513
10514 /* Register this new converter */
10515 cli_register_kw(cli_kws);
10516
10517 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010518
10519 error:
10520 release_hlua_function(fcn);
10521 if (cli_kws) {
10522 for (i = 0; i < index; i++)
10523 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10524 ha_free((char **)&(cli_kws->kw[0].usage));
10525 }
10526 ha_free(&cli_kws);
10527 WILL_LJMP(luaL_error(L, errmsg));
10528 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010529}
10530
Christopher Faulet69c581a2021-05-31 08:54:04 +020010531static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10532{
10533 struct hlua_flt_config *conf = fconf->conf;
10534 lua_State *L;
10535 int error, pos, state_id, flt_ref;
10536
10537 state_id = reg_flt_to_stack_id(conf->reg);
10538 L = hlua_states[state_id];
10539 pos = lua_gettop(L);
10540
10541 /* The filter parsing function */
10542 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10543
10544 /* Push the filter class on the stack and resolve all callbacks */
10545 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10546
10547 /* Duplicate the filter class so each filter will have its own copy */
10548 lua_newtable(L);
10549 lua_pushnil(L);
10550
10551 while (lua_next(L, pos+2)) {
10552 lua_pushvalue(L, -2);
10553 lua_insert(L, -2);
10554 lua_settable(L, -4);
10555 }
10556 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10557
10558 /* Remove the original lua filter class from the stack */
10559 lua_pop(L, 1);
10560
10561 /* Push the copy on the stack */
10562 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10563
10564 /* extra args are pushed in a table */
10565 lua_newtable(L);
10566 for (pos = 0; conf->args[pos]; pos++) {
10567 /* Check stack available size. */
10568 if (!lua_checkstack(L, 1)) {
10569 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10570 goto error;
10571 }
10572 lua_pushstring(L, conf->args[pos]);
10573 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10574 }
10575
10576 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10577 switch (error) {
10578 case LUA_OK:
10579 /* replace the filter ref */
10580 conf->ref[state_id] = flt_ref;
10581 break;
10582 case LUA_ERRRUN:
10583 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10584 goto error;
10585 case LUA_ERRMEM:
10586 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10587 goto error;
10588 case LUA_ERRERR:
10589 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10590 goto error;
10591#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10592 case LUA_ERRGCMM:
10593 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10594 goto error;
10595#endif
10596 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010597 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010598 goto error;
10599 }
10600
10601 lua_settop(L, 0);
10602 return 0;
10603
10604 error:
10605 lua_settop(L, 0);
10606 return -1;
10607}
10608
10609static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10610{
10611 struct hlua_flt_config *conf = fconf->conf;
10612 lua_State *L;
10613 int state_id;
10614
10615 if (!conf)
10616 return;
10617
10618 state_id = reg_flt_to_stack_id(conf->reg);
10619 L = hlua_states[state_id];
10620 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10621}
10622
10623static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10624{
10625 struct hlua_flt_config *conf = fconf->conf;
10626 int state_id = reg_flt_to_stack_id(conf->reg);
10627
10628 /* Rely on per-thread init for global scripts */
10629 if (!state_id)
10630 return hlua_filter_init_per_thread(px, fconf);
10631 return 0;
10632}
10633
10634static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10635{
10636
10637 if (fconf->conf) {
10638 struct hlua_flt_config *conf = fconf->conf;
10639 int state_id = reg_flt_to_stack_id(conf->reg);
10640 int pos;
10641
10642 /* Rely on per-thread deinit for global scripts */
10643 if (!state_id)
10644 hlua_filter_deinit_per_thread(px, fconf);
10645
10646 for (pos = 0; conf->args[pos]; pos++)
10647 free(conf->args[pos]);
10648 free(conf->args);
10649 }
10650 ha_free(&fconf->conf);
10651 ha_free((char **)&fconf->id);
10652 ha_free(&fconf->ops);
10653}
10654
10655static int hlua_filter_new(struct stream *s, struct filter *filter)
10656{
10657 struct hlua_flt_config *conf = FLT_CONF(filter);
10658 struct hlua_flt_ctx *flt_ctx = NULL;
10659 int ret = 1;
10660
10661 /* In the execution wrappers linked with a stream, the
10662 * Lua context can be not initialized. This behavior
10663 * permits to save performances because a systematic
10664 * Lua initialization cause 5% performances loss.
10665 */
10666 if (!s->hlua) {
10667 struct hlua *hlua;
10668
10669 hlua = pool_alloc(pool_head_hlua);
10670 if (!hlua) {
10671 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10672 conf->reg->name);
10673 ret = 0;
10674 goto end;
10675 }
10676 HLUA_INIT(hlua);
10677 s->hlua = hlua;
10678 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10679 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10680 conf->reg->name);
10681 ret = 0;
10682 goto end;
10683 }
10684 }
10685
10686 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10687 if (!flt_ctx) {
10688 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10689 conf->reg->name);
10690 ret = 0;
10691 goto end;
10692 }
10693 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10694 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10695 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10696 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10697 conf->reg->name);
10698 ret = 0;
10699 goto end;
10700 }
10701 HLUA_INIT(flt_ctx->hlua[0]);
10702 HLUA_INIT(flt_ctx->hlua[1]);
10703 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10704 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10705 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10706 conf->reg->name);
10707 ret = 0;
10708 goto end;
10709 }
10710
10711 if (!HLUA_IS_RUNNING(s->hlua)) {
10712 /* The following Lua calls can fail. */
10713 if (!SET_SAFE_LJMP(s->hlua)) {
10714 const char *error;
10715
10716 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10717 error = lua_tostring(s->hlua->T, -1);
10718 else
10719 error = "critical error";
10720 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10721 ret = 0;
10722 goto end;
10723 }
10724
10725 /* Check stack size. */
10726 if (!lua_checkstack(s->hlua->T, 1)) {
10727 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010728 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010729 ret = 0;
10730 goto end;
10731 }
10732
10733 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10734 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10735 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10736 conf->reg->name);
10737 RESET_SAFE_LJMP(s->hlua);
10738 ret = 0;
10739 goto end;
10740 }
10741 lua_insert(s->hlua->T, -2);
10742
10743 /* Push the copy on the stack */
10744 s->hlua->nargs = 1;
10745
10746 /* We must initialize the execution timeouts. */
10747 s->hlua->max_time = hlua_timeout_session;
10748
10749 /* At this point the execution is safe. */
10750 RESET_SAFE_LJMP(s->hlua);
10751 }
10752
10753 switch (hlua_ctx_resume(s->hlua, 0)) {
10754 case HLUA_E_OK:
10755 /* Nothing returned or not a table, ignore the filter for current stream */
10756 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10757 ret = 0;
10758 goto end;
10759 }
10760
10761 /* Attached the filter pointer to the ctx */
10762 lua_pushstring(s->hlua->T, "__filter");
10763 lua_pushlightuserdata(s->hlua->T, filter);
10764 lua_settable(s->hlua->T, -3);
10765
10766 /* Save a ref on the filter ctx */
10767 lua_pushvalue(s->hlua->T, 1);
10768 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10769 filter->ctx = flt_ctx;
10770 break;
10771 case HLUA_E_ERRMSG:
10772 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10773 ret = -1;
10774 goto end;
10775 case HLUA_E_ETMOUT:
10776 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10777 ret = 0;
10778 goto end;
10779 case HLUA_E_NOMEM:
10780 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10781 ret = 0;
10782 goto end;
10783 case HLUA_E_AGAIN:
10784 case HLUA_E_YIELD:
10785 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10786 " are not allowed from 'new' function.\n", conf->reg->name);
10787 ret = 0;
10788 goto end;
10789 case HLUA_E_ERR:
10790 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10791 ret = 0;
10792 goto end;
10793 default:
10794 ret = 0;
10795 goto end;
10796 }
10797
10798 end:
10799 if (s->hlua)
10800 lua_settop(s->hlua->T, 0);
10801 if (ret <= 0) {
10802 if (flt_ctx) {
10803 hlua_ctx_destroy(flt_ctx->hlua[0]);
10804 hlua_ctx_destroy(flt_ctx->hlua[1]);
10805 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10806 }
10807 }
10808 return ret;
10809}
10810
10811static void hlua_filter_delete(struct stream *s, struct filter *filter)
10812{
10813 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10814
10815 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10816 hlua_ctx_destroy(flt_ctx->hlua[0]);
10817 hlua_ctx_destroy(flt_ctx->hlua[1]);
10818 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10819 filter->ctx = NULL;
10820}
10821
Christopher Faulet9f55a502020-02-25 15:21:02 +010010822static int hlua_filter_from_payload(struct filter *filter)
10823{
10824 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10825
10826 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10827}
10828
Christopher Fauletc404f112020-02-26 15:03:09 +010010829static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10830 int dir, unsigned int flags)
10831{
10832 struct hlua *flt_hlua;
10833 struct hlua_flt_config *conf = FLT_CONF(filter);
10834 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10835 unsigned int hflags = HLUA_TXN_FLT_CTX;
10836 int ret = 1;
10837
10838 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10839 if (!flt_hlua)
10840 goto end;
10841
10842 if (!HLUA_IS_RUNNING(flt_hlua)) {
10843 int extra_idx = lua_gettop(flt_hlua->T);
10844
10845 /* The following Lua calls can fail. */
10846 if (!SET_SAFE_LJMP(flt_hlua)) {
10847 const char *error;
10848
10849 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10850 error = lua_tostring(flt_hlua->T, -1);
10851 else
10852 error = "critical error";
10853 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10854 goto end;
10855 }
10856
10857 /* Check stack size. */
10858 if (!lua_checkstack(flt_hlua->T, 3)) {
10859 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10860 RESET_SAFE_LJMP(flt_hlua);
10861 goto end;
10862 }
10863
10864 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10865 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10866 RESET_SAFE_LJMP(flt_hlua);
10867 goto end;
10868 }
10869 lua_insert(flt_hlua->T, -2);
10870
10871 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10872 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10873 RESET_SAFE_LJMP(flt_hlua);
10874 goto end;
10875 }
10876 flt_hlua->nargs = 2;
10877
10878 if (flags & HLUA_FLT_CB_ARG_CHN) {
10879 if (dir == SMP_OPT_DIR_REQ)
10880 lua_getfield(flt_hlua->T, -1, "req");
10881 else
10882 lua_getfield(flt_hlua->T, -1, "res");
10883 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10884 lua_pushstring(flt_hlua->T, "__filter");
10885 lua_pushlightuserdata(flt_hlua->T, filter);
10886 lua_settable(flt_hlua->T, -3);
10887 }
10888 flt_hlua->nargs++;
10889 }
10890 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010891 if (dir == SMP_OPT_DIR_REQ)
10892 lua_getfield(flt_hlua->T, -1, "http_req");
10893 else
10894 lua_getfield(flt_hlua->T, -1, "http_res");
10895 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10896 lua_pushstring(flt_hlua->T, "__filter");
10897 lua_pushlightuserdata(flt_hlua->T, filter);
10898 lua_settable(flt_hlua->T, -3);
10899 }
10900 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010901 }
10902
10903 /* Check stack size. */
10904 if (!lua_checkstack(flt_hlua->T, 1)) {
10905 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10906 RESET_SAFE_LJMP(flt_hlua);
10907 goto end;
10908 }
10909
10910 while (extra_idx--) {
10911 lua_pushvalue(flt_hlua->T, 1);
10912 lua_remove(flt_hlua->T, 1);
10913 flt_hlua->nargs++;
10914 }
10915
10916 /* We must initialize the execution timeouts. */
10917 flt_hlua->max_time = hlua_timeout_session;
10918
10919 /* At this point the execution is safe. */
10920 RESET_SAFE_LJMP(flt_hlua);
10921 }
10922
10923 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10924 case HLUA_E_OK:
10925 /* Catch the return value if it required */
10926 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10927 ret = lua_tointeger(flt_hlua->T, -1);
10928 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10929 }
10930
10931 /* Set timeout in the required channel. */
10932 if (flt_hlua->wake_time != TICK_ETERNITY) {
10933 if (dir == SMP_OPT_DIR_REQ)
10934 s->req.analyse_exp = flt_hlua->wake_time;
10935 else
10936 s->res.analyse_exp = flt_hlua->wake_time;
10937 }
10938 break;
10939 case HLUA_E_AGAIN:
10940 /* Set timeout in the required channel. */
10941 if (flt_hlua->wake_time != TICK_ETERNITY) {
10942 if (dir == SMP_OPT_DIR_REQ)
10943 s->req.analyse_exp = flt_hlua->wake_time;
10944 else
10945 s->res.analyse_exp = flt_hlua->wake_time;
10946 }
10947 /* Some actions can be wake up when a "write" event
10948 * is detected on a response channel. This is useful
10949 * only for actions targeted on the requests.
10950 */
10951 if (HLUA_IS_WAKERESWR(flt_hlua))
10952 s->res.flags |= CF_WAKE_WRITE;
10953 if (HLUA_IS_WAKEREQWR(flt_hlua))
10954 s->req.flags |= CF_WAKE_WRITE;
10955 ret = 0;
10956 goto end;
10957 case HLUA_E_ERRMSG:
10958 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10959 ret = -1;
10960 goto end;
10961 case HLUA_E_ETMOUT:
10962 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10963 goto end;
10964 case HLUA_E_NOMEM:
10965 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10966 goto end;
10967 case HLUA_E_YIELD:
10968 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10969 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10970 goto end;
10971 case HLUA_E_ERR:
10972 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10973 goto end;
10974 default:
10975 goto end;
10976 }
10977
10978
10979 end:
10980 return ret;
10981}
10982
10983static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10984{
10985 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10986
10987 flt_ctx->flags = 0;
10988 return hlua_filter_callback(s, filter, "start_analyze",
10989 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10990 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10991}
10992
10993static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10994{
10995 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10996
10997 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10998 return hlua_filter_callback(s, filter, "end_analyze",
10999 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11000 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11001}
11002
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011003static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11004{
11005 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11006
11007 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11008 return hlua_filter_callback(s, filter, "http_headers",
11009 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11010 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11011}
11012
11013static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
11014 unsigned int offset, unsigned int len)
11015{
11016 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11017 struct hlua *flt_hlua;
11018 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11019 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11020 int ret;
11021
11022 flt_hlua = flt_ctx->hlua[idx];
11023 flt_ctx->cur_off[idx] = offset;
11024 flt_ctx->cur_len[idx] = len;
11025 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11026 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11027 if (ret != -1) {
11028 ret = flt_ctx->cur_len[idx];
11029 if (lua_gettop(flt_hlua->T) > 0) {
11030 ret = lua_tointeger(flt_hlua->T, -1);
11031 if (ret > flt_ctx->cur_len[idx])
11032 ret = flt_ctx->cur_len[idx];
11033 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11034 }
11035 }
11036 return ret;
11037}
11038
11039static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
11040{
11041 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11042
11043 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11044 return hlua_filter_callback(s, filter, "http_end",
11045 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11046 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11047}
11048
Christopher Fauletc404f112020-02-26 15:03:09 +010011049static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
11050 unsigned int offset, unsigned int len)
11051{
11052 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11053 struct hlua *flt_hlua;
11054 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
11055 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
11056 int ret;
11057
11058 flt_hlua = flt_ctx->hlua[idx];
11059 flt_ctx->cur_off[idx] = offset;
11060 flt_ctx->cur_len[idx] = len;
11061 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
11062 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
11063 if (ret != -1) {
11064 ret = flt_ctx->cur_len[idx];
11065 if (lua_gettop(flt_hlua->T) > 0) {
11066 ret = lua_tointeger(flt_hlua->T, -1);
11067 if (ret > flt_ctx->cur_len[idx])
11068 ret = flt_ctx->cur_len[idx];
11069 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11070 }
11071 }
11072 return ret;
11073}
11074
Christopher Faulet69c581a2021-05-31 08:54:04 +020011075static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
11076 struct flt_conf *fconf, char **err, void *private)
11077{
11078 struct hlua_reg_filter *reg_flt = private;
11079 lua_State *L;
11080 struct hlua_flt_config *conf = NULL;
11081 const char *flt_id = NULL;
11082 int state_id, pos, flt_flags = 0;
11083 struct flt_ops *hlua_flt_ops = NULL;
11084
11085 state_id = reg_flt_to_stack_id(reg_flt);
11086 L = hlua_states[state_id];
11087
11088 /* Initialize the filter ops with default callbacks */
11089 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011090 if (!hlua_flt_ops)
11091 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011092 hlua_flt_ops->init = hlua_filter_init;
11093 hlua_flt_ops->deinit = hlua_filter_deinit;
11094 if (state_id) {
11095 /* Set per-thread callback if script is loaded per-thread */
11096 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
11097 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
11098 }
11099 hlua_flt_ops->attach = hlua_filter_new;
11100 hlua_flt_ops->detach = hlua_filter_delete;
11101
11102 /* Push the filter class on the stack and resolve all callbacks */
11103 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
11104
Christopher Fauletc404f112020-02-26 15:03:09 +010011105 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
11106 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
11107 lua_pop(L, 1);
11108 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
11109 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
11110 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011111 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
11112 hlua_flt_ops->http_headers = hlua_filter_http_headers;
11113 lua_pop(L, 1);
11114 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
11115 hlua_flt_ops->http_payload = hlua_filter_http_payload;
11116 lua_pop(L, 1);
11117 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
11118 hlua_flt_ops->http_end = hlua_filter_http_end;
11119 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010011120 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
11121 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
11122 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011123
11124 /* Get id and flags of the filter class */
11125 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
11126 flt_id = lua_tostring(L, -1);
11127 lua_pop(L, 1);
11128 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
11129 flt_flags = lua_tointeger(L, -1);
11130 lua_pop(L, 1);
11131
11132 /* Create the filter config */
11133 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011134 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020011135 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011136 conf->reg = reg_flt;
11137
11138 /* duplicate args */
11139 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
11140 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020011141 if (!conf->args)
11142 goto error;
11143 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011144 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011145 if (!conf->args[pos])
11146 goto error;
11147 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011148 conf->args[pos] = NULL;
11149 *cur_arg += pos + 1;
11150
Christopher Fauletc86bb872021-08-13 08:33:57 +020011151 if (flt_id) {
11152 fconf->id = strdup(flt_id);
11153 if (!fconf->id)
11154 goto error;
11155 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011156 fconf->flags = flt_flags;
11157 fconf->conf = conf;
11158 fconf->ops = hlua_flt_ops;
11159
11160 lua_settop(L, 0);
11161 return 0;
11162
11163 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011164 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011165 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011166 if (conf && conf->args) {
11167 for (pos = 0; conf->args[pos]; pos++)
11168 free(conf->args[pos]);
11169 free(conf->args);
11170 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011171 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011172 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011173 lua_settop(L, 0);
11174 return -1;
11175}
11176
Christopher Fauletc404f112020-02-26 15:03:09 +010011177__LJMP static int hlua_register_data_filter(lua_State *L)
11178{
11179 struct filter *filter;
11180 struct channel *chn;
11181
11182 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11183 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11184 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11185
11186 lua_getfield(L, 1, "__filter");
11187 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11188 filter = lua_touserdata (L, -1);
11189 lua_pop(L, 1);
11190
11191 register_data_filter(chn_strm(chn), chn, filter);
11192 return 1;
11193}
11194
11195__LJMP static int hlua_unregister_data_filter(lua_State *L)
11196{
11197 struct filter *filter;
11198 struct channel *chn;
11199
11200 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11201 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11202 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11203
11204 lua_getfield(L, 1, "__filter");
11205 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11206 filter = lua_touserdata (L, -1);
11207 lua_pop(L, 1);
11208
11209 unregister_data_filter(chn_strm(chn), chn, filter);
11210 return 1;
11211}
11212
Christopher Faulet69c581a2021-05-31 08:54:04 +020011213/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011214 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011215 * parse configuration arguments.
11216 */
11217__LJMP static int hlua_register_filter(lua_State *L)
11218{
11219 struct buffer *trash;
11220 struct flt_kw_list *fkl;
11221 struct flt_kw *fkw;
11222 const char *name;
11223 struct hlua_reg_filter *reg_flt= NULL;
11224 int flt_ref, fun_ref;
11225 int len;
11226
11227 MAY_LJMP(check_args(L, 3, "register_filter"));
11228
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011229 if (hlua_gethlua(L)) {
11230 /* runtime processing */
11231 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
11232 }
11233
Christopher Faulet69c581a2021-05-31 08:54:04 +020011234 /* First argument : filter name. */
11235 name = MAY_LJMP(luaL_checkstring(L, 1));
11236
11237 /* Second argument : The filter class */
11238 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11239
11240 /* Third argument : lua function. */
11241 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11242
11243 trash = get_trash_chunk();
11244 chunk_printf(trash, "lua.%s", name);
11245 fkw = flt_find_kw(trash->area);
11246 if (fkw != NULL) {
11247 reg_flt = fkw->private;
11248 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11249 ha_warning("Trying to register filter 'lua.%s' more than once. "
11250 "This will become a hard error in version 2.5.\n", name);
11251 }
11252 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11253 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11254 return 0;
11255 }
11256
11257 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11258 if (!fkl)
11259 goto alloc_error;
11260 fkl->scope = "HLUA";
11261
11262 reg_flt = new_hlua_reg_filter(name);
11263 if (!reg_flt)
11264 goto alloc_error;
11265
11266 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11267 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11268
11269 /* The filter keyword */
11270 len = strlen("lua.") + strlen(name) + 1;
11271 fkl->kw[0].kw = calloc(1, len);
11272 if (!fkl->kw[0].kw)
11273 goto alloc_error;
11274
11275 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11276
11277 fkl->kw[0].parse = hlua_filter_parse_fct;
11278 fkl->kw[0].private = reg_flt;
11279 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11280
11281 /* Register this new filter */
11282 flt_register_keywords(fkl);
11283
11284 return 0;
11285
11286 alloc_error:
11287 release_hlua_reg_filter(reg_flt);
11288 ha_free(&fkl);
11289 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11290 return 0; /* Never reached */
11291}
11292
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011293static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011294 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011295 char **err, unsigned int *timeout)
11296{
11297 const char *error;
11298
11299 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011300 if (error == PARSE_TIME_OVER) {
11301 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11302 args[1], args[0]);
11303 return -1;
11304 }
11305 else if (error == PARSE_TIME_UNDER) {
11306 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11307 args[1], args[0]);
11308 return -1;
11309 }
11310 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011311 memprintf(err, "%s: invalid timeout", args[0]);
11312 return -1;
11313 }
11314 return 0;
11315}
11316
11317static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011318 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011319 char **err)
11320{
11321 return hlua_read_timeout(args, section_type, curpx, defpx,
11322 file, line, err, &hlua_timeout_session);
11323}
11324
11325static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011326 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011327 char **err)
11328{
11329 return hlua_read_timeout(args, section_type, curpx, defpx,
11330 file, line, err, &hlua_timeout_task);
11331}
11332
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011333static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011334 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011335 char **err)
11336{
11337 return hlua_read_timeout(args, section_type, curpx, defpx,
11338 file, line, err, &hlua_timeout_applet);
11339}
11340
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011341static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011342 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011343 char **err)
11344{
11345 char *error;
11346
11347 hlua_nb_instruction = strtoll(args[1], &error, 10);
11348 if (*error != '\0') {
11349 memprintf(err, "%s: invalid number", args[0]);
11350 return -1;
11351 }
11352 return 0;
11353}
11354
Willy Tarreau32f61e22015-03-18 17:54:59 +010011355static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011356 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011357 char **err)
11358{
11359 char *error;
11360
11361 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011362 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011363 return -1;
11364 }
11365 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11366 if (*error != '\0') {
11367 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11368 return -1;
11369 }
11370 return 0;
11371}
11372
11373
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011374/* This function is called by the main configuration key "lua-load". It loads and
11375 * execute an lua file during the parsing of the HAProxy configuration file. It is
11376 * the main lua entry point.
11377 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011378 * This function runs with the HAProxy keywords API. It returns -1 if an error
11379 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011380 *
11381 * In some error case, LUA set an error message in top of the stack. This function
11382 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011383 *
11384 * This function can fail with an abort() due to an Lua critical error.
11385 * We are in the configuration parsing process of HAProxy, this abort() is
11386 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011387 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011388static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011389{
11390 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011391 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011392
11393 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011394 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011395 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020011396 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011397 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011398 return -1;
11399 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011400
11401 /* Push args in the Lua stack, except the first one which is the filename */
11402 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020011403 /* Check stack size. */
11404 if (!lua_checkstack(L, 1)) {
11405 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
11406 return -1;
11407 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011408 lua_pushstring(L, args[nargs]);
11409 }
11410 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011411
11412 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020011413 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011414 switch (error) {
11415 case LUA_OK:
11416 break;
11417 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011418 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011419 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011420 return -1;
11421 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011422 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011423 return -1;
11424 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011425 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011426 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011427 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011428#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011429 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011430 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011431 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011432 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011433#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011434 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020011435 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011436 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011437 return -1;
11438 }
11439
11440 return 0;
11441}
11442
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011443static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011444 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011445 char **err)
11446{
11447 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011448 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011449 return -1;
11450 }
11451
Thierry Fournier59f11be2020-11-29 00:37:41 +010011452 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011453 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011454 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011455 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011456}
11457
Thierry Fournier59f11be2020-11-29 00:37:41 +010011458static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011459 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011460 char **err)
11461{
11462 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020011463 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011464
11465 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011466 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011467 return -1;
11468 }
11469
11470 if (per_thread_load == NULL) {
11471 /* allocate the first entry large enough to store the final NULL */
11472 per_thread_load = calloc(1, sizeof(*per_thread_load));
11473 if (per_thread_load == NULL) {
11474 memprintf(err, "out of memory error");
11475 return -1;
11476 }
11477 }
11478
11479 /* count used entries */
11480 for (len = 0; per_thread_load[len] != NULL; len++)
11481 ;
11482
11483 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11484 if (per_thread_load == NULL) {
11485 memprintf(err, "out of memory error");
11486 return -1;
11487 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011488 per_thread_load[len + 1] = NULL;
11489
Thierry Fournierae6b5682022-09-19 09:04:16 +020011490 /* count args excepting the first, allocate array and copy args */
11491 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020011492 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010011493 if (per_thread_load[len] == NULL) {
11494 memprintf(err, "out of memory error");
11495 return -1;
11496 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020011497 for (i = 1; *(args[i]) != 0; i++) {
11498 per_thread_load[len][i - 1] = strdup(args[i]);
11499 if (per_thread_load[len][i - 1] == NULL) {
11500 memprintf(err, "out of memory error");
11501 return -1;
11502 }
11503 }
11504 per_thread_load[len][i - 1] = strdup("");
11505 if (per_thread_load[len][i - 1] == NULL) {
11506 memprintf(err, "out of memory error");
11507 return -1;
11508 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010011509
11510 /* loading for thread 1 only */
11511 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011512 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020011513 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011514}
11515
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011516/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11517 * in the given <ctx>.
11518 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011519static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011520{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011521 lua_getglobal(L, "package"); /* push package variable */
11522 lua_pushstring(L, path); /* push given path */
11523 lua_pushstring(L, ";"); /* push semicolon */
11524 lua_getfield(L, -3, type); /* push old path */
11525 lua_concat(L, 3); /* concatenate to new path */
11526 lua_setfield(L, -2, type); /* store new path */
11527 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011528
11529 return 0;
11530}
11531
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011532static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011533 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011534 char **err)
11535{
11536 char *path;
11537 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011538 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011539 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011540
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011541 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011542 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011543 }
11544
11545 if (!(*args[1])) {
11546 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011547 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011548 }
11549 path = args[1];
11550
11551 if (*args[2]) {
11552 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11553 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011554 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011555 }
11556 type = args[2];
11557 }
11558
Thierry Fournier59f11be2020-11-29 00:37:41 +010011559 p = calloc(1, sizeof(*p));
11560 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011561 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011562 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011563 }
11564 p->path = strdup(path);
11565 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011566 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011567 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011568 }
11569 p->type = strdup(type);
11570 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011571 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011572 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011573 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011574 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011575
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011576 /* Handle the global state and the per-thread state for the first
11577 * thread. The remaining threads will be initialized based on
11578 * prepend_path_list.
11579 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011580 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011581 lua_State *L = hlua_states[i];
11582 const char *error;
11583
11584 if (setjmp(safe_ljmp_env) != 0) {
11585 lua_atpanic(L, hlua_panic_safe);
11586 if (lua_type(L, -1) == LUA_TSTRING)
11587 error = lua_tostring(L, -1);
11588 else
11589 error = "critical error";
11590 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11591 exit(1);
11592 } else {
11593 lua_atpanic(L, hlua_panic_ljmp);
11594 }
11595
11596 hlua_prepend_path(L, type, path);
11597
11598 lua_atpanic(L, hlua_panic_safe);
11599 }
11600
Thierry Fournier59f11be2020-11-29 00:37:41 +010011601 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011602
11603err2:
11604 free(p->type);
11605 free(p->path);
11606err:
11607 free(p);
11608 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011609}
11610
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011611/* configuration keywords declaration */
11612static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011613 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011614 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011615 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011616 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11617 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011618 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011619 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011620 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011621 { 0, NULL, NULL },
11622}};
11623
Willy Tarreau0108d902018-11-25 19:14:37 +010011624INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11625
William Lallemand52139182022-03-30 15:05:42 +020011626#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011627
William Lallemand30fcca12022-03-30 12:03:12 +020011628/*
11629 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11630 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11631 * difference is that the yield in lua and for the CLI is not handled the same
11632 * way.
11633 */
11634__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11635{
11636 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11637 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11638 struct ckch_inst *ckchi = *lua_ckchi;
11639 struct ckch_store *old_ckchs = lua_ckchs[0];
11640 struct ckch_store *new_ckchs = lua_ckchs[1];
11641 struct hlua *hlua;
11642 char *err = NULL;
11643 int y = 1;
11644
11645 hlua = hlua_gethlua(L);
11646
11647 /* get the first ckchi to copy */
11648 if (ckchi == NULL)
11649 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11650
11651 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11652 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11653 struct ckch_inst *new_inst;
11654
11655 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11656 if (y % 10 == 0) {
11657
11658 *lua_ckchi = ckchi;
11659
11660 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11661 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11662 }
11663
11664 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11665 goto error;
11666
11667 /* link the new ckch_inst to the duplicate */
11668 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11669 y++;
11670 }
11671
11672 /* The generation is finished, we can insert everything */
11673 ckch_store_replace(old_ckchs, new_ckchs);
11674
11675 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11676
11677 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11678
11679 return 0;
11680
11681error:
11682 ckch_store_free(new_ckchs);
11683 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11684 WILL_LJMP(luaL_error(L, "%s", err));
11685 free(err);
11686
11687 return 0;
11688}
11689
11690/*
11691 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11692 * from the table in parameter.
11693 *
11694 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11695 * means it does not need to have a transaction since everything is done in the
11696 * same function.
11697 *
11698 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11699 *
11700 */
11701__LJMP static int hlua_ckch_set(lua_State *L)
11702{
11703 struct hlua *hlua;
11704 struct ckch_inst **lua_ckchi;
11705 struct ckch_store **lua_ckchs;
11706 struct ckch_store *old_ckchs = NULL;
11707 struct ckch_store *new_ckchs = NULL;
11708 int errcode = 0;
11709 char *err = NULL;
11710 struct cert_exts *cert_ext = NULL;
11711 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010011712 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020011713 int ret;
11714
11715 if (lua_type(L, -1) != LUA_TTABLE)
11716 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11717
11718 hlua = hlua_gethlua(L);
11719
11720 /* FIXME: this should not return an error but should come back later */
11721 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11722 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11723
11724 ret = lua_getfield(L, -1, "filename");
11725 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011726 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011727 errcode |= ERR_ALERT | ERR_FATAL;
11728 goto end;
11729 }
11730 filename = (char *)lua_tostring(L, -1);
11731
11732
11733 /* look for the filename in the tree */
11734 old_ckchs = ckchs_lookup(filename);
11735 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011736 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011737 errcode |= ERR_ALERT | ERR_FATAL;
11738 goto end;
11739 }
11740 /* TODO: handle extra_files_noext */
11741
11742 new_ckchs = ckchs_dup(old_ckchs);
11743 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011744 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020011745 errcode |= ERR_ALERT | ERR_FATAL;
11746 goto end;
11747 }
11748
William Lallemand52ddd992022-11-22 11:51:53 +010011749 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020011750
11751 /* loop on the field in the table, which have the same name as the
11752 * possible extensions of files */
11753 lua_pushnil(L);
11754 while (lua_next(L, 1)) {
11755 int i;
11756 const char *field = lua_tostring(L, -2);
11757 char *payload = (char *)lua_tostring(L, -1);
11758
11759 if (!field || strcmp(field, "filename") == 0) {
11760 lua_pop(L, 1);
11761 continue;
11762 }
11763
11764 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11765 if (strcmp(field, cert_exts[i].ext) == 0) {
11766 cert_ext = &cert_exts[i];
11767 break;
11768 }
11769 }
11770
11771 /* this is the default type, the field is not supported */
11772 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011773 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020011774 errcode |= ERR_ALERT | ERR_FATAL;
11775 goto end;
11776 }
11777
11778 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010011779 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020011780 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020011781 errcode |= ERR_ALERT | ERR_FATAL;
11782 goto end;
11783 }
11784 lua_pop(L, 1);
11785 }
11786
11787 /* store the pointers on the lua stack */
11788 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11789 lua_ckchs[0] = old_ckchs;
11790 lua_ckchs[1] = new_ckchs;
11791 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11792 *lua_ckchi = NULL;
11793
11794 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11795 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11796
11797end:
11798 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11799
11800 if (errcode & ERR_CODE) {
11801 ckch_store_free(new_ckchs);
11802 WILL_LJMP(luaL_error(L, "%s", err));
11803 }
11804 free(err);
11805
11806 return 0;
11807}
11808
William Lallemand52139182022-03-30 15:05:42 +020011809#else
11810
11811__LJMP static int hlua_ckch_set(lua_State *L)
11812{
11813 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11814
11815 return 0;
11816}
11817#endif /* ! USE_OPENSSL */
11818
11819
11820
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011821/* This function can fail with an abort() due to an Lua critical error.
11822 * We are in the initialisation process of HAProxy, this abort() is
11823 * tolerated.
11824 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011825int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011826{
11827 struct hlua_init_function *init;
11828 const char *msg;
11829 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011830 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011831 const char *kind;
11832 const char *trace;
11833 int return_status = 1;
11834#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11835 int nres;
11836#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011837
Willy Tarreaucdb53462020-12-02 12:12:00 +010011838 /* disable memory limit checks if limit is not set */
11839 if (!hlua_global_allocator.limit)
11840 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11841
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011842 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011843 if (setjmp(safe_ljmp_env) != 0) {
11844 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011845 if (lua_type(L, -1) == LUA_TSTRING)
11846 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011847 else
11848 error = "critical error";
11849 fprintf(stderr, "Lua post-init: %s.\n", error);
11850 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011851 } else {
11852 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011853 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011854
Thierry Fournierc7492592020-11-28 23:57:24 +010011855 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011856 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011857
11858#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011859 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011860#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011861 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011862#endif
11863 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011864 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011865
11866 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011867 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011868 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011869
11870 case LUA_ERRERR:
11871 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011872 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011873 case LUA_ERRRUN:
11874 if (!kind)
11875 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011876 msg = lua_tostring(L, -1);
11877 lua_settop(L, 0); /* Empty the stack. */
11878 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011879 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011880 if (msg)
11881 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11882 else
11883 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11884 return_status = 0;
11885 break;
11886
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011887 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011888 /* Unknown error */
11889 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010011890 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011891 case LUA_YIELD:
11892 /* yield is not configured at this step, this state doesn't happen */
11893 if (!kind)
11894 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010011895 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010011896 case LUA_ERRMEM:
11897 if (!kind)
11898 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011899 lua_settop(L, 0);
11900 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011901 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011902 ha_alert("Lua init: %s: %s\n", kind, trace);
11903 return_status = 0;
11904 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011905 }
Thierry Fournier670db242020-11-28 10:49:59 +010011906 if (!return_status)
11907 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011908 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011909
11910 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011911 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011912}
11913
Thierry Fournierb8cef172020-11-28 15:37:17 +010011914int hlua_post_init()
11915{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011916 int ret;
11917 int i;
11918 int errors;
11919 char *err = NULL;
11920 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011921 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011922
Willy Tarreaub1310492021-08-30 09:35:18 +020011923#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011924 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011925 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011926 int saved_used_backed = global.ssl_used_backend;
11927 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011928 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011929 global.ssl_used_backend = saved_used_backed;
11930 }
11931#endif
11932
Thierry Fournierc7492592020-11-28 23:57:24 +010011933 /* Perform post init of common thread */
11934 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011935 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011936 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11937 if (ret == 0)
11938 return 0;
11939
11940 /* init remaining lua states and load files */
11941 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11942
11943 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011944 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011945
11946 /* Init lua state */
11947 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11948
11949 /* Load lua files */
11950 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11951 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11952 if (ret != 0) {
11953 ha_alert("Lua init: %s\n", err);
11954 return 0;
11955 }
11956 }
11957 }
11958
11959 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011960 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011961
11962 /* Execute post init for all states */
11963 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11964
11965 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011966 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011967
11968 /* run post init */
11969 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11970 if (ret == 0)
11971 return 0;
11972 }
11973
11974 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011975 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011976
11977 /* control functions registering. Each function must have:
11978 * - only the function_ref[0] set positive and all other to -1
11979 * - only the function_ref[0] set to -1 and all other positive
11980 * This ensure a same reference is not used both in shared
11981 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011982 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011983 * complicated to found for the end user.
11984 */
11985 errors = 0;
11986 list_for_each_entry(fcn, &referenced_functions, l) {
11987 ret = 0;
11988 for (i = 1; i < global.nbthread + 1; i++) {
11989 if (fcn->function_ref[i] == -1)
11990 ret--;
11991 else
11992 ret++;
11993 }
11994 if (abs(ret) != global.nbthread) {
11995 ha_alert("Lua function '%s' is not referenced in all thread. "
11996 "Expect function in all thread or in none thread.\n", fcn->name);
11997 errors++;
11998 continue;
11999 }
12000
12001 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012002 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
12003 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010012004 "exclusive.\n", fcn->name);
12005 errors++;
12006 }
12007 }
12008
Christopher Faulet69c581a2021-05-31 08:54:04 +020012009 /* Do the same with registered filters */
12010 list_for_each_entry(reg_flt, &referenced_filters, l) {
12011 ret = 0;
12012 for (i = 1; i < global.nbthread + 1; i++) {
12013 if (reg_flt->flt_ref[i] == -1)
12014 ret--;
12015 else
12016 ret++;
12017 }
12018 if (abs(ret) != global.nbthread) {
12019 ha_alert("Lua filter '%s' is not referenced in all thread. "
12020 "Expect function in all thread or in none thread.\n", reg_flt->name);
12021 errors++;
12022 continue;
12023 }
12024
12025 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
12026 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
12027 "and per-thread Lua context (through lua-load-per-thread). these two context "
12028 "exclusive.\n", fcn->name);
12029 errors++;
12030 }
12031 }
12032
12033
Thierry Fournier59f11be2020-11-29 00:37:41 +010012034 if (errors > 0)
12035 return 0;
12036
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012037 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010012038 * -1 in order to have probably a segfault if someone use it
12039 */
12040 hlua_state_id = -1;
12041
12042 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010012043}
12044
Willy Tarreau32f61e22015-03-18 17:54:59 +010012045/* The memory allocator used by the Lua stack. <ud> is a pointer to the
12046 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
12047 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012048 * allocation. <nsize> is the requested new size. A new allocation is
12049 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010012050 * zero. This one verifies that the limits are respected but is optimized
12051 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012052 *
12053 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
12054 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
12055 * that and will simply allocate zero as if it were the result of malloc(0),
12056 * so mapping this onto realloc() will lead to memory leaks on non-glibc
12057 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010012058 */
12059static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
12060{
12061 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010012062 size_t limit, old, new;
12063
12064 /* a limit of ~0 means unlimited and boot complete, so there's no need
12065 * for accounting anymore.
12066 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012067 if (likely(~zone->limit == 0)) {
12068 if (!nsize)
12069 ha_free(&ptr);
12070 else
12071 ptr = realloc(ptr, nsize);
12072 return ptr;
12073 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010012074
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010012075 if (!ptr)
12076 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010012077
Willy Tarreaucdb53462020-12-02 12:12:00 +010012078 /* enforce strict limits across all threads */
12079 limit = zone->limit;
12080 old = _HA_ATOMIC_LOAD(&zone->allocated);
12081 do {
12082 new = old + nsize - osize;
12083 if (unlikely(nsize && limit && new > limit))
12084 return NULL;
12085 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010012086
Willy Tarreaua5efdff2021-10-22 16:00:02 +020012087 if (!nsize)
12088 ha_free(&ptr);
12089 else
12090 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010012091
12092 if (unlikely(!ptr && nsize)) // failed
12093 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
12094
12095 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010012096 return ptr;
12097}
12098
Thierry Fournierecb83c22020-11-28 15:49:44 +010012099/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012100 * We are in the initialisation process of HAProxy, this abort() is
12101 * tolerated.
12102 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010012103lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012104{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012105 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012106 int idx;
12107 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012108 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012109 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012110 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012111 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012112 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012113 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012114
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012115 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012116 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012117
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012118 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012119 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010012120 *context = NULL;
12121
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012122 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012123 * the Lua function can fail with an abort. We are in the initialisation
12124 * process of HAProxy, this abort() is tolerated.
12125 */
12126
Thierry Fournier3c539322020-11-28 16:05:05 +010012127 /* Call post initialisation function in safe environment. */
12128 if (setjmp(safe_ljmp_env) != 0) {
12129 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012130 if (lua_type(L, -1) == LUA_TSTRING)
12131 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012132 else
12133 error_msg = "critical error";
12134 fprintf(stderr, "Lua init: %s.\n", error_msg);
12135 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012136 } else {
12137 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010012138 }
12139
Thierry FOURNIER380d0932015-01-23 14:27:52 +010012140 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012141 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012142#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
12143#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
12144#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012145 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012146#endif
12147#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012148 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010012149#endif
12150#undef HLUA_PREPEND_PATH_TOSTRING
12151#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012152
Thierry Fournier59f11be2020-11-29 00:37:41 +010012153 /* Apply configured prepend path */
12154 list_for_each_entry(pp, &prepend_path_list, l)
12155 hlua_prepend_path(L, pp->type, pp->path);
12156
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012157 /*
12158 *
12159 * Create "core" object.
12160 *
12161 */
12162
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010012163 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012164 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012165
Thierry Fournierecb83c22020-11-28 15:49:44 +010012166 /* set the thread id */
12167 hlua_class_const_int(L, "thread", thread_num);
12168
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012169 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010012170 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010012172
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012173 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012174 hlua_class_function(L, "register_init", hlua_register_init);
12175 hlua_class_function(L, "register_task", hlua_register_task);
12176 hlua_class_function(L, "register_fetches", hlua_register_fetches);
12177 hlua_class_function(L, "register_converters", hlua_register_converters);
12178 hlua_class_function(L, "register_action", hlua_register_action);
12179 hlua_class_function(L, "register_service", hlua_register_service);
12180 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012181 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012182 hlua_class_function(L, "yield", hlua_yield);
12183 hlua_class_function(L, "set_nice", hlua_set_nice);
12184 hlua_class_function(L, "sleep", hlua_sleep);
12185 hlua_class_function(L, "msleep", hlua_msleep);
12186 hlua_class_function(L, "add_acl", hlua_add_acl);
12187 hlua_class_function(L, "del_acl", hlua_del_acl);
12188 hlua_class_function(L, "set_map", hlua_set_map);
12189 hlua_class_function(L, "del_map", hlua_del_map);
12190 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012191 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012192 hlua_class_function(L, "log", hlua_log);
12193 hlua_class_function(L, "Debug", hlua_log_debug);
12194 hlua_class_function(L, "Info", hlua_log_info);
12195 hlua_class_function(L, "Warning", hlua_log_warning);
12196 hlua_class_function(L, "Alert", hlua_log_alert);
12197 hlua_class_function(L, "done", hlua_done);
12198 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012199
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012201
12202 /*
12203 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012204 * Create "act" object.
12205 *
12206 */
12207
12208 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012209 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012210
12211 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012212 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12213 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12214 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12215 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12216 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12217 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12218 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12219 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012220
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012221 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012222
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012223 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012224
12225 /*
12226 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012227 * Create "Filter" object.
12228 *
12229 */
12230
12231 /* This table entry is the object "filter" base. */
12232 lua_newtable(L);
12233
12234 /* push flags and constants */
12235 hlua_class_const_int(L, "CONTINUE", 1);
12236 hlua_class_const_int(L, "WAIT", 0);
12237 hlua_class_const_int(L, "ERROR", -1);
12238
12239 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12240
Christopher Fauletc404f112020-02-26 15:03:09 +010012241 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12242 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12243 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12244
Christopher Faulet69c581a2021-05-31 08:54:04 +020012245 lua_setglobal(L, "filter");
12246
12247 /*
12248 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012249 * Register class Map
12250 *
12251 */
12252
12253 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012254 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012255
12256 /* register pattern types. */
12257 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012258 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012259 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012260 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012261 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012262 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012263
12264 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012265 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012266
12267 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012268 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012269
Ilya Shipitsind4259502020-04-08 01:07:56 +050012270 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012271 lua_pushstring(L, "__index");
12272 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012273
12274 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012275 hlua_class_function(L, "lookup", hlua_map_lookup);
12276 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012277
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012278 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012279
Thierry Fournier45e78d72016-02-19 18:34:46 +010012280 /* Register previous table in the registry with reference and named entry.
12281 * The function hlua_register_metatable() pops the stack, so we
12282 * previously create a copy of the table.
12283 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012284 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12285 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012286
12287 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012288 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012289
12290 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012291 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012292
12293 /*
12294 *
William Lallemand30fcca12022-03-30 12:03:12 +020012295 * Register "CertCache" class
12296 *
12297 */
12298
12299 /* Create and fill the metatable. */
12300 lua_newtable(L);
12301 /* Register */
12302 hlua_class_function(L, "set", hlua_ckch_set);
12303 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12304
12305 /*
12306 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012307 * Register class Channel
12308 *
12309 */
12310
12311 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012312 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012313
Ilya Shipitsind4259502020-04-08 01:07:56 +050012314 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012315 lua_pushstring(L, "__index");
12316 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012317
12318 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012319 hlua_class_function(L, "data", hlua_channel_get_data);
12320 hlua_class_function(L, "line", hlua_channel_get_line);
12321 hlua_class_function(L, "set", hlua_channel_set_data);
12322 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012323 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012324 hlua_class_function(L, "prepend", hlua_channel_prepend);
12325 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012326 hlua_class_function(L, "send", hlua_channel_send);
12327 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012328 hlua_class_function(L, "input", hlua_channel_get_in_len);
12329 hlua_class_function(L, "output", hlua_channel_get_out_len);
12330 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012331 hlua_class_function(L, "is_full", hlua_channel_is_full);
12332 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012333
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012334 /* Deprecated API */
12335 hlua_class_function(L, "get", hlua_channel_get);
12336 hlua_class_function(L, "dup", hlua_channel_dup);
12337 hlua_class_function(L, "getline", hlua_channel_getline);
12338 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12339 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12340
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012341 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012342
12343 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012344 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012345
12346 /*
12347 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012348 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012349 *
12350 */
12351
12352 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012353 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012354
Ilya Shipitsind4259502020-04-08 01:07:56 +050012355 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012356 lua_pushstring(L, "__index");
12357 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012358
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012359 /* Browse existing fetches and create the associated
12360 * object method.
12361 */
12362 sf = NULL;
12363 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012364 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12365 * by an underscore.
12366 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012367 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012368 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012369 if (*p == '.' || *p == '-' || *p == '+')
12370 *p = '_';
12371
12372 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012373 lua_pushstring(L, trash.area);
12374 lua_pushlightuserdata(L, sf);
12375 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12376 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012377 }
12378
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012379 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012380
12381 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012382 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012383
12384 /*
12385 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012386 * Register class Converters
12387 *
12388 */
12389
12390 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012391 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012392
12393 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012394 lua_pushstring(L, "__index");
12395 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012396
12397 /* Browse existing converters and create the associated
12398 * object method.
12399 */
12400 sc = NULL;
12401 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012402 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12403 * by an underscore.
12404 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012405 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012406 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012407 if (*p == '.' || *p == '-' || *p == '+')
12408 *p = '_';
12409
12410 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012411 lua_pushstring(L, trash.area);
12412 lua_pushlightuserdata(L, sc);
12413 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12414 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012415 }
12416
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012417 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012418
12419 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012420 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012421
12422 /*
12423 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012424 * Register class HTTP
12425 *
12426 */
12427
12428 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012429 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012430
Ilya Shipitsind4259502020-04-08 01:07:56 +050012431 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012432 lua_pushstring(L, "__index");
12433 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012434
12435 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012436 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12437 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12438 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12439 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12440 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12441 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12442 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12443 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12444 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12445 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012446
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012447 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12448 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12449 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12450 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12451 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12452 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12453 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012454
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012455 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012456
12457 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012458 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012459
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012460 /*
12461 *
12462 * Register class HTTPMessage
12463 *
12464 */
12465
12466 /* Create and fill the metatable. */
12467 lua_newtable(L);
12468
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012469 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012470 lua_pushstring(L, "__index");
12471 lua_newtable(L);
12472
12473 /* Register Lua functions. */
12474 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12475 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12476 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12477 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12478 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12479 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12480 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12481 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12482 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12483 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12484 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12485 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12486 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12487 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12488 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12489 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12490 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12491 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12492
12493 hlua_class_function(L, "body", hlua_http_msg_get_body);
12494 hlua_class_function(L, "set", hlua_http_msg_set_data);
12495 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12496 hlua_class_function(L, "append", hlua_http_msg_append);
12497 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12498 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12499 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12500 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12501
12502 hlua_class_function(L, "send", hlua_http_msg_send);
12503 hlua_class_function(L, "forward", hlua_http_msg_forward);
12504
12505 lua_rawset(L, -3);
12506
12507 /* Register previous table in the registry with reference and named entry. */
12508 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012509
12510 /*
12511 *
12512 * Register class HTTPClient
12513 *
12514 */
12515
12516 /* Create and fill the metatable. */
12517 lua_newtable(L);
12518 lua_pushstring(L, "__index");
12519 lua_newtable(L);
12520 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012521 hlua_class_function(L, "head", hlua_httpclient_head);
12522 hlua_class_function(L, "put", hlua_httpclient_put);
12523 hlua_class_function(L, "post", hlua_httpclient_post);
12524 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012525 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012526 /* Register the garbage collector entry. */
12527 lua_pushstring(L, "__gc");
12528 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12529 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12530
William Lallemand3956c4e2021-09-21 16:25:15 +020012531
12532
12533 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012534 /*
12535 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012536 * Register class AppletTCP
12537 *
12538 */
12539
12540 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012541 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012542
Ilya Shipitsind4259502020-04-08 01:07:56 +050012543 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012544 lua_pushstring(L, "__index");
12545 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012546
12547 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012548 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12549 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12550 hlua_class_function(L, "send", hlua_applet_tcp_send);
12551 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12552 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12553 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12554 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12555 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012556
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012557 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012558
12559 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012560 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012561
12562 /*
12563 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012564 * Register class AppletHTTP
12565 *
12566 */
12567
12568 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012569 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012570
Ilya Shipitsind4259502020-04-08 01:07:56 +050012571 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012572 lua_pushstring(L, "__index");
12573 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012574
12575 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012576 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12577 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12578 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12579 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12580 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12581 hlua_class_function(L, "getline", hlua_applet_http_getline);
12582 hlua_class_function(L, "receive", hlua_applet_http_recv);
12583 hlua_class_function(L, "send", hlua_applet_http_send);
12584 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12585 hlua_class_function(L, "set_status", hlua_applet_http_status);
12586 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012587
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012588 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012589
12590 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012591 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012592
12593 /*
12594 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012595 * Register class TXN
12596 *
12597 */
12598
12599 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012600 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012601
Ilya Shipitsind4259502020-04-08 01:07:56 +050012602 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012603 lua_pushstring(L, "__index");
12604 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012605
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012606 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012607 hlua_class_function(L, "set_priv", hlua_set_priv);
12608 hlua_class_function(L, "get_priv", hlua_get_priv);
12609 hlua_class_function(L, "set_var", hlua_set_var);
12610 hlua_class_function(L, "unset_var", hlua_unset_var);
12611 hlua_class_function(L, "get_var", hlua_get_var);
12612 hlua_class_function(L, "done", hlua_txn_done);
12613 hlua_class_function(L, "reply", hlua_txn_reply_new);
12614 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12615 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12616 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12617 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12618 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12619 hlua_class_function(L, "deflog", hlua_txn_deflog);
12620 hlua_class_function(L, "log", hlua_txn_log);
12621 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12622 hlua_class_function(L, "Info", hlua_txn_log_info);
12623 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12624 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012625
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012626 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012627
12628 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012629 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012630
12631 /*
12632 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012633 * Register class reply
12634 *
12635 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012636 lua_newtable(L);
12637 lua_pushstring(L, "__index");
12638 lua_newtable(L);
12639 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12640 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12641 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12642 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12643 lua_settable(L, -3); /* Sets the __index entry. */
12644 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012645
12646
12647 /*
12648 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012649 * Register class Socket
12650 *
12651 */
12652
12653 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012654 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012655
Ilya Shipitsind4259502020-04-08 01:07:56 +050012656 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012657 lua_pushstring(L, "__index");
12658 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012659
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012660#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012661 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012662#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012663 hlua_class_function(L, "connect", hlua_socket_connect);
12664 hlua_class_function(L, "send", hlua_socket_send);
12665 hlua_class_function(L, "receive", hlua_socket_receive);
12666 hlua_class_function(L, "close", hlua_socket_close);
12667 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12668 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12669 hlua_class_function(L, "setoption", hlua_socket_setoption);
12670 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012671
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012672 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012673
12674 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012675 lua_pushstring(L, "__gc");
12676 lua_pushcclosure(L, hlua_socket_gc, 0);
12677 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012678
12679 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012680 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012681
Thierry Fournieraafc7772020-12-04 11:47:47 +010012682 lua_atpanic(L, hlua_panic_safe);
12683
12684 return L;
12685}
12686
12687void hlua_init(void) {
12688 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012689 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012690#ifdef USE_OPENSSL
12691 struct srv_kw *kw;
12692 int tmp_error;
12693 char *error;
12694 char *args[] = { /* SSL client configuration. */
12695 "ssl",
12696 "verify",
12697 "none",
12698 NULL
12699 };
12700#endif
12701
12702 /* Init post init function list head */
12703 for (i = 0; i < MAX_THREADS + 1; i++)
12704 LIST_INIT(&hlua_init_functions[i]);
12705
12706 /* Init state for common/shared lua parts */
12707 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012708 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012709 hlua_states[0] = hlua_init_state(0);
12710
12711 /* Init state 1 for thread 0. We have at least one thread. */
12712 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012713 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012714 hlua_states[1] = hlua_init_state(1);
12715
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012716 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012717 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012718 if (!socket_proxy) {
12719 fprintf(stderr, "Lua init: %s\n", errmsg);
12720 exit(1);
12721 }
12722 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012723
12724 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012725 socket_tcp = new_server(socket_proxy);
12726 if (!socket_tcp) {
12727 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12728 exit(1);
12729 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012730
12731#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012732 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012733 socket_ssl = new_server(socket_proxy);
12734 if (!socket_ssl) {
12735 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12736 exit(1);
12737 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012738
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012739 socket_ssl->use_ssl = 1;
12740 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012741
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012742 for (i = 0; args[i] != NULL; i++) {
12743 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012744 /*
12745 *
12746 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012747 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012748 * features like client certificates and ssl_verify.
12749 *
12750 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012751 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012752 if (tmp_error != 0) {
12753 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12754 abort(); /* This must be never arrives because the command line
12755 not editable by the user. */
12756 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012757 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012758 }
12759 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012760#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012761
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012762}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012763
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012764static void hlua_deinit()
12765{
Willy Tarreau186f3762020-12-04 11:48:12 +010012766 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012767 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12768
12769 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12770 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012771
12772 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12773 if (hlua_states[thr])
12774 lua_close(hlua_states[thr]);
12775 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012776
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012777 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012778
Willy Tarreau0f143af2021-03-05 10:41:48 +010012779#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012780 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012781#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012782
12783 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012784}
12785
12786REGISTER_POST_DEINIT(hlua_deinit);
12787
Willy Tarreau80713382018-11-26 10:19:54 +010012788static void hlua_register_build_options(void)
12789{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012790 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012791
Willy Tarreaubb57d942016-12-21 19:04:56 +010012792 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12793 hap_register_build_opts(ptr, 1);
12794}
Willy Tarreau80713382018-11-26 10:19:54 +010012795
12796INITCALL0(STG_REGISTER, hlua_register_build_options);